Skip to content

Commit 8e699a5

Browse files
committed
feat(pkg-py): Add .app() method, enable bookmarking by default
1 parent 86ccace commit 8e699a5

File tree

6 files changed

+156
-13
lines changed

6 files changed

+156
-13
lines changed

pkg-py/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313

1414
### New features
1515

16+
* New `QueryChat.app()` method enables quicker/easier chatting with a dataset. (#104)
17+
18+
* Enabled bookmarking by default in both `.app()` and `.server()` methods. In latter case, you'll need to also specify the `bookmark_store` (either in `shiny.App()` or `shiny.express.app_opts()`) for it to take effect. (#104)
19+
1620
* The current SQL query and title can now be programmatically set through the `.sql()` and `.title()` methods of `QueryChat()`. (#98, #101)
1721

1822
* Added a `.generate_greeting()` method to help you create a greeting message for your querychat bot. (#87)

pkg-py/src/querychat/_icons.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import Literal
2+
3+
from shiny import ui
4+
5+
ICON_NAMES = Literal["funnel-fill", "terminal-fill", "table"]
6+
7+
8+
def bs_icon(name: ICON_NAMES) -> ui.HTML:
9+
"""Get Bootstrap icon SVG by name."""
10+
if name not in BS_ICONS:
11+
raise ValueError(f"Unknown Bootstrap icon: {name}")
12+
return ui.HTML(BS_ICONS[name])
13+
14+
15+
BS_ICONS = {
16+
"funnel-fill": '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-funnel-fill" viewBox="0 0 16 16"><path d="M1.5 1.5A.5.5 0 0 1 2 1h12a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.128.334L10 8.692V13.5a.5.5 0 0 1-.342.474l-3 1A.5.5 0 0 1 6 14.5V8.692L1.628 3.834A.5.5 0 0 1 1.5 3.5z"/></svg>',
17+
"terminal-fill": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="bi bi-terminal-fill " style="height:1em;width:1em;fill:currentColor;vertical-align:-0.125em;" aria-hidden="true" role="img" ><path d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3zm9.5 5.5h-3a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1zm-6.354-.354a.5.5 0 1 0 .708.708l2-2a.5.5 0 0 0 0-.708l-2-2a.5.5 0 1 0-.708.708L4.793 6.5 3.146 8.146z"></path></svg>',
18+
"table": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="bi bi-table " style="height:1em;width:1em;fill:currentColor;vertical-align:-0.125em;" aria-hidden="true" role="img" ><path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm0 4h-4v3h4V8zm0 4h-4v3h3a1 1 0 0 0 1-1v-2zm-5 3v-3H6v3h4zm-5 0v-3H1v2a1 1 0 0 0 1 1h3zm-4-4h4V8H1v3zm0-4h4V4H1v3zm5-3v3h4V4H6zm4 4H6v3h4V8z"></path></svg>',
19+
}

pkg-py/src/querychat/_querychat.py

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
import chatlas
1111
import chevron
1212
import sqlalchemy
13-
from shiny import ui
13+
from shiny import App, Inputs, Outputs, Session, reactive, render, req, ui
1414
from shiny.session import get_current_session
15+
from shinychat import output_markdown_stream
1516

17+
from ._icons import bs_icon
1618
from ._querychat_module import ModServerResult, mod_server, mod_ui
1719
from .datasource import DataFrameSource, DataSource, SQLAlchemySource
1820

@@ -133,6 +135,99 @@ def __init__(
133135
# Populated when ._server() gets called (in an active session)
134136
self._server_values: ModServerResult | None = None
135137

138+
def app(
139+
self, *, bookmark_store: Literal["url", "server", "disable"] = "url"
140+
) -> App:
141+
"""
142+
Quickly chat with a dataset.
143+
144+
Creates a Shiny app with a chat sidebar and data table view -- providing a
145+
quick-and-easy way to start chatting with your data.
146+
147+
Parameters
148+
----------
149+
bookmark_store
150+
The bookmarking store to use for the Shiny app. Options are:
151+
- `"url"`: Store bookmarks in the URL (default).
152+
- `"server"`: Store bookmarks on the server.
153+
- `"disable"`: Disable bookmarking.
154+
155+
Returns
156+
-------
157+
:
158+
A Shiny App object that can be run with `app.run()` or served with `shiny run`.
159+
160+
"""
161+
enable_bookmarking = bookmark_store != "disable"
162+
table_name = self.data_source.table_name
163+
164+
def app_ui(request):
165+
return ui.page_sidebar(
166+
self.sidebar(),
167+
ui.card(
168+
ui.card_header(
169+
ui.div(
170+
ui.div(
171+
bs_icon("terminal-fill"),
172+
ui.output_text("query_title", inline=True),
173+
class_="d-flex align-items-center gap-2",
174+
),
175+
ui.output_ui("ui_reset", inline=True),
176+
class_="hstack gap-3",
177+
),
178+
),
179+
ui.output_ui("sql_output"),
180+
fill=False,
181+
style="max-height: 33%;",
182+
),
183+
ui.card(
184+
ui.card_header(bs_icon("table"), " Data"),
185+
ui.output_data_frame("dt"),
186+
),
187+
title=ui.span("querychat with ", ui.code(table_name)),
188+
class_="bslib-page-dashboard",
189+
fillable=True,
190+
)
191+
192+
def app_server(input: Inputs, output: Outputs, session: Session):
193+
self._server(enable_bookmarking=enable_bookmarking)
194+
195+
@render.text
196+
def query_title():
197+
return self.title() or "SQL Query"
198+
199+
@render.ui
200+
def ui_reset():
201+
req(self.sql())
202+
return ui.input_action_button(
203+
"reset_query",
204+
"Reset Query",
205+
class_="btn btn-outline-danger btn-sm lh-1 ms-auto",
206+
)
207+
208+
@reactive.effect
209+
@reactive.event(input.reset_query)
210+
def _():
211+
self.sql("")
212+
self.title(None)
213+
214+
@render.data_frame
215+
def dt():
216+
return self.df()
217+
218+
@render.ui
219+
def sql_output():
220+
sql = self.sql() or f"SELECT * FROM {table_name}"
221+
sql_code = f"```sql\n{sql}\n```"
222+
return output_markdown_stream(
223+
"sql_code",
224+
content=sql_code,
225+
auto_scroll=False,
226+
width="100%",
227+
)
228+
229+
return App(app_ui, app_server, bookmark_store=bookmark_store)
230+
136231
def sidebar(
137232
self,
138233
*,
@@ -183,7 +278,7 @@ def ui(self, **kwargs):
183278
"""
184279
return mod_ui(self.id, **kwargs)
185280

186-
def _server(self):
281+
def _server(self, *, enable_bookmarking: bool = True) -> None:
187282
"""
188283
Initialize the server module.
189284
@@ -211,6 +306,7 @@ def _server(self):
211306
system_prompt=self.system_prompt,
212307
greeting=self.greeting,
213308
client=self.client,
309+
enable_bookmarking=enable_bookmarking,
214310
)
215311

216312
return

pkg-py/src/querychat/_querychat_module.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import chatlas
1515
import pandas as pd
1616
from shiny import Inputs, Outputs, Session
17+
from shiny.bookmark import BookmarkState, RestoreState
1718

1819
from .datasource import DataSource
1920

@@ -60,10 +61,12 @@ def mod_server(
6061
system_prompt: str,
6162
greeting: str | None,
6263
client: chatlas.Chat,
64+
enable_bookmarking: bool = False,
6365
):
6466
# Reactive values to store state
6567
sql = ReactiveString("")
6668
title = ReactiveStringOrNone(None)
69+
has_greeted = reactive.value[bool](False) # noqa: FBT003
6770

6871
# Set up the chat object for this session
6972
chat = copy.deepcopy(client)
@@ -99,6 +102,9 @@ async def _(user_input: str):
99102

100103
@reactive.effect
101104
async def greet_on_startup():
105+
if has_greeted():
106+
return
107+
102108
if greeting:
103109
await chat_ui.append_message(greeting)
104110
elif greeting is None:
@@ -108,6 +114,8 @@ async def greet_on_startup():
108114
)
109115
await chat_ui.append_message_stream(stream)
110116

117+
has_greeted.set(True)
118+
111119
# Handle update button clicks
112120
@reactive.effect
113121
@reactive.event(input.chat_update)
@@ -125,4 +133,26 @@ def _():
125133
if new_title is not None:
126134
title.set(new_title)
127135

136+
if enable_bookmarking:
137+
chat_ui.enable_bookmarking(client)
138+
139+
def _on_bookmark(x: BookmarkState) -> None:
140+
vals = x.values # noqa: PD011
141+
vals["querychat_sql"] = sql.get()
142+
vals["querychat_title"] = title.get()
143+
vals["querychat_has_greeted"] = has_greeted.get()
144+
145+
session.bookmark.on_bookmark(_on_bookmark)
146+
147+
def _on_restore(x: RestoreState) -> None:
148+
vals = x.values # noqa: PD011
149+
if "querychat_sql" in vals:
150+
sql.set(vals["querychat_sql"])
151+
if "querychat_title" in vals:
152+
title.set(vals["querychat_title"])
153+
if "querychat_has_greeted" in vals:
154+
has_greeted.set(vals["querychat_has_greeted"])
155+
156+
session.bookmark.on_restore(_on_restore)
157+
128158
return ModServerResult(df=filtered_df, sql=sql, title=title, client=chat)

pkg-py/src/querychat/tools.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55

66
import chevron
77
from chatlas import ContentToolResult, Tool
8-
from htmltools import HTML
98
from shinychat.types import ToolResultDisplay
109

10+
from ._icons import bs_icon
1111
from ._utils import df_to_html
1212

1313
if TYPE_CHECKING:
@@ -66,9 +66,7 @@ def update_dashboard(query: str, title: str) -> ContentToolResult:
6666
title=title,
6767
show_request=False,
6868
open=True,
69-
icon=HTML(
70-
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-funnel-fill" viewBox="0 0 16 16"><path d="M1.5 1.5A.5.5 0 0 1 2 1h12a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.128.334L10 8.692V13.5a.5.5 0 0 1-.342.474l-3 1A.5.5 0 0 1 6 14.5V8.692L1.628 3.834A.5.5 0 0 1 1.5 3.5z"/></svg>',
71-
),
69+
icon=bs_icon("funnel-fill"),
7270
),
7371
},
7472
)
@@ -142,9 +140,7 @@ def reset_dashboard() -> ContentToolResult:
142140
title=None,
143141
show_request=False,
144142
open=False,
145-
icon=HTML(
146-
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="bi bi-arrow-counterclockwise" style="height:1em;width:1em;fill:currentColor;vertical-align:-0.125em;" aria-hidden="true" role="img"><path fill-rule="evenodd" d="M8 3a5 5 0 1 1-4.546 2.914.5.5 0 0 0-.908-.417A6 6 0 1 0 8 2v1z"></path><path d="M8 4.466V.534a.25.25 0 0 0-.41-.192L5.23 2.308a.25.25 0 0 0 0 .384l2.36 1.966A.25.25 0 0 0 8 4.466z"></path></svg>',
147-
),
143+
icon=bs_icon("terminal-fill"),
148144
),
149145
},
150146
)
@@ -213,9 +209,7 @@ def query(query: str, _intent: str = "") -> ContentToolResult:
213209
markdown=markdown,
214210
show_request=False,
215211
open=True,
216-
icon=HTML(
217-
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-table" viewBox="0 0 16 16"><path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zm15 2h-4v3h4zm0 4h-4v3h4zm0 4h-4v3h3a1 1 0 0 0 1-1zm-5 3v-3H6v3zm-5 0v-3H1v2a1 1 0 0 0 1 1zm-4-4h4V8H1zm0-4h4V4H1zm5-3v3h4V4zm4 4H6v3h4z"/></svg>',
218-
),
212+
icon=bs_icon("table"),
219213
),
220214
},
221215
)

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ maintainers = [
2121
dependencies = [
2222
"duckdb",
2323
"pandas",
24-
"shiny",
24+
"shiny @ git+https://github.com/posit-dev/py-shiny.git",
2525
"shinywidgets",
2626
"htmltools",
2727
"chatlas>=0.13.2",

0 commit comments

Comments
 (0)