AI-assisted exploration with widgets
When you explore data, a lot of your thinking happens directly on the plot: you lasso a cluster of odd points, zoom in on a region, pan a map to a neighborhood. Reactive accessors make those gestures available to your Python code. plot.selected_rows() returns the rows you lassoed; map.bounds() returns the part of the map on screen.
That makes accessors a natural fit for an AI assistant. Give the model a function that reads an accessor, and you can lasso a few points and just ask “why are these so low?” – the model knows which points you mean, and can bring in knowledge your data doesn’t have. Give it a function that changes the widget, and it can answer by pointing: highlighting the countries it’s talking about, or moving the map where you asked. You keep exploring with the mouse, the model keeps up, and you’re both looking at the same view.
This guide builds that up in small steps, starting from one plot and a chat.
Before you start
You’ll need a few packages besides shinywidgets:
pip install shinychat chatlas anthropic querychat
shinychat provides the chat interface and chatlas talks to the model; querychat is only needed for the last example. The examples use Anthropic’s claude-haiku-5-5, so set ANTHROPIC_API_KEY before running them. To use another provider, swap chatlas.ChatAnthropic for a different chatlas client.
1. Ask about a selection
Start with a scatter plot of countries and a chat beside it. The app needs three pieces:
- An accessor to read.
@render_plotly(listen_to=["selected_rows"])records the user’s lasso. Plotly’s selection accessors are opt-in, hencelisten_to. - A tool.
get_selection()is a plain Python function that readsplot.selected_rows(df)and returns the rows as CSV. Its docstring tells the model what it’s for. - A chat that can call the tool.
client.register_tool(get_selection)hands the function to the model, andChat(..., client=client)connects the chat to it.
# Lasso some points, then ask the chat about them. The get_selection tool
# hands the model the selected rows, and the model brings its own knowledge
# of those countries.
import chatlas
import plotly.express as px
from shiny import reactive
from shiny.express import ui
from shinychat.express import Chat
from shinywidgets import render_plotly
df = px.data.gapminder().query("year == 2007").reset_index(drop=True)
ui.page_opts(title="Ask about your selection", fillable=True)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("Lasso some countries")
@render_plotly(listen_to=["selected_rows"])
def plot():
fig = px.scatter(
df, x="gdpPercap", y="lifeExp", hover_name="country",
log_x=True, custom_data=[df.index],
)
return fig.update_layout(dragmode="lasso")
with ui.card(full_screen=True):
ui.card_header("Ask about your selection")
def get_selection() -> str:
"""The countries the user lassoed on the scatter plot, with their
GDP per capita and life expectancy."""
# Currently required to read reactive values from a chat tool.
with reactive.isolate():
rows = plot.selected_rows(df)
return rows[["country", "continent", "gdpPercap", "lifeExp"]].to_csv(
index=False
)
client = chatlas.ChatAnthropic(
model="claude-haiku-5-5",
system_prompt="You help explore a scatter plot of 2007 gapminder data "
"(GDP per capita vs. life expectancy). Call get_selection to see "
"which countries the user has lassoed.",
)
client.register_tool(get_selection)
chat = Chat(
"chat",
client=client,
greeting="Lasso some points, then ask me about them.",
)
chat.ui()Lasso the four countries sitting well below the trend, then ask “Why are these below the curve?”. The model calls get_selection, sees Botswana, Equatorial Guinea, Gabon, and South Africa, and explains the gap with things the data doesn’t contain: HIV/AIDS, and national incomes driven by oil and diamonds.

Nothing reads the selection until the model asks for it. The accessor records the lasso as it happens, so it’s there whenever the tool runs (see “Read on demand”).
2. Let the model change the plot
A second tool can change the widget, so the model can show you what it means instead of only describing it. highlight() recolors points through plot.widget, the same in-place update you’d use anywhere else in an app:
# Example 1 plus a second tool: highlight() lets the model point things out
# on the plot itself. Try lassoing a few countries, then asking "highlight
# other countries like these".
import chatlas
import plotly.express as px
from shiny import reactive
from shiny.express import ui
from shinychat.express import Chat
from shinywidgets import render_plotly
df = px.data.gapminder().query("year == 2007").reset_index(drop=True)
ui.page_opts(title="Let the model highlight points", fillable=True)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("Lasso some countries")
@render_plotly(listen_to=["selected_rows"])
def plot():
fig = px.scatter(
df, x="gdpPercap", y="lifeExp", hover_name="country",
log_x=True, custom_data=[df.index],
)
# Keep the lasso blue and don't fade the rest, so highlights stay visible.
fig.update_traces(selected_marker_color="#636efa", unselected_marker_opacity=1)
return fig.update_layout(dragmode="lasso")
with ui.card(full_screen=True):
ui.card_header("Ask about your selection")
def get_selection() -> str:
"""The countries the user lassoed on the scatter plot, with their
GDP per capita and life expectancy."""
# Currently required to read reactive values from a chat tool.
with reactive.isolate():
rows = plot.selected_rows(df)
return rows[["country", "continent", "gdpPercap", "lifeExp"]].to_csv(
index=False
)
def highlight(countries: list[str]) -> str:
"""Highlight countries on the scatter plot, replacing any current
highlight. Pass an empty list to clear it."""
found = set(countries) & set(df["country"])
others = "#d3d3d3" if found else "#636efa"
plot.widget.data[0].marker.color = [
"#ef553b" if c in found else others for c in df["country"]
]
unknown = sorted(set(countries) - found)
return f"Highlighted {len(found)} countries." + (
f" Not in the data: {', '.join(unknown)}." if unknown else ""
)
client = chatlas.ChatAnthropic(
model="claude-haiku-5-5",
system_prompt="You help explore a scatter plot of 2007 gapminder data "
"(GDP per capita vs. life expectancy). Call get_selection to see "
"which countries the user has lassoed, and highlight to point out "
"countries on the plot.",
)
client.register_tool(get_selection)
client.register_tool(highlight)
chat = Chat(
"chat",
client=client,
greeting="Lasso some points, then ask me about them.",
)
chat.ui()The model can name a country that isn’t in the data, so highlight() colors only the names it finds and reports the rest back. The model can then correct itself or tell the user.
Lasso the same four countries and ask “Why are these below the curve? Highlight other countries in a similar situation.”:

Your lasso stays blue, and the model’s picks – here Angola, Namibia, and Swaziland – turn red.
3. Several widgets, one view
The same two kinds of tools work with any widget, and with several at once. Here a map of car-share pods sits next to a bar chart of the pods currently on screen. The chat gets two tools: summarize_view() reads map.bounds(), the same accessor the chart reads, and fly_to() moves the map to one of a few known places.
# A map, a chart of what's visible on it, and a chat. summarize_view reads
# the same map.bounds() the chart does, so the two always agree; fly_to moves
# the map to one of a few known places. Data: 249 car-share pods in Montreal
# (plotly's carshare dataset).
import chatlas
import ipyleaflet as L
import pandas as pd
import plotly.express as px
from shiny import reactive
from shiny.express import ui
from shinychat.express import Chat
from shinywidgets import render_ipyleaflet, render_plotly
pods = px.data.carshare()
pods["period"] = pd.cut(
pods["peak_hour"], bins=[-1, 5, 11, 17, 23],
labels=["night", "morning", "afternoon", "evening"],
)
PERIODS = ["night", "morning", "afternoon", "evening"]
PLACES = {
"downtown": (45.5017, -73.5673, 13),
"old port": (45.5075, -73.5540, 15),
"plateau": (45.5234, -73.5825, 14),
"west island": (45.4443, -73.8275, 12),
"overview": (45.52, -73.59, 11),
}
ui.page_opts(title="Map + chart + chat", fillable=True)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("Pan or zoom; fly_to() moves this map in place")
@render_ipyleaflet
def map():
m = L.Map(center=(45.52, -73.59), zoom=11)
markers = [L.Marker(location=(r.centroid_lat, r.centroid_lon)) for r in pods.itertuples()]
m.add(L.MarkerCluster(markers=markers))
return m
with ui.div(class_="d-flex flex-column gap-3", style="height: 100%;"):
with ui.card(full_screen=True):
ui.card_header("Visible pods, by time of day")
@render_plotly
def chart():
(south, west), (north, east) = map.bounds()
visible = pods[pods.centroid_lat.between(south, north) & pods.centroid_lon.between(west, east)]
counts = visible["period"].value_counts().reindex(PERIODS).reset_index()
counts.columns = ["period", "count"]
return px.bar(counts, x="period", y="count")
with ui.card(full_screen=True):
ui.card_header("Ask about the map")
def summarize_view() -> str:
"""Summarize the car-share pods currently visible on the map, by time of day."""
# Currently required to read reactive values from a chat tool.
with reactive.isolate():
(south, west), (north, east) = map.bounds()
visible = pods[pods.centroid_lat.between(south, north) & pods.centroid_lon.between(west, east)]
counts = visible["period"].value_counts().reindex(PERIODS, fill_value=0)
parts = ", ".join(f"{p}: {n}" for p, n in counts.items())
return f"{len(visible)} pods visible ({parts})."
def fly_to(place: str) -> str:
"""
Move the map to a named place.
Parameters
----------
place : str
One of: downtown, old port, plateau, west island, overview.
"""
key = place.strip().lower()
if key not in PLACES:
return f"Unknown place {place!r}. Valid places: {', '.join(PLACES)}."
lat, lng, zoom = PLACES[key]
map.widget.center = (lat, lng)
map.widget.zoom = zoom
return f"Map moved to {place} (zoom {zoom})."
chat_client = chatlas.ChatAnthropic(
model="claude-haiku-5-5",
system_prompt="You help explore a map of Montreal car-share pods. "
"Use summarize_view to describe what's currently visible, and "
"fly_to to move the map to one of its supported places.",
)
chat_client.register_tool(summarize_view)
chat_client.register_tool(fly_to)
chat = Chat(
"chat",
client=chat_client,
greeting="Pan the map, or ask what's visible. "
"I can also fly to downtown, old port, plateau, or west island.",
)
chat.ui()Ask “what’s visible on the map right now?”, then “fly to the west island”:


The chart and the chat agree because they read the same accessor. When fly_to moves the map, the browser reports the new viewport, bounds() updates, and the chart follows on its own. This app is also in the gallery as the map-chart-chat showcase.
4. Going further: let querychat write the queries
So far you’ve written each tool yourself. querychat packages up a common one: the user asks for a subset of the data in plain English, querychat turns that into a SQL query, and you get the result as qc.df(), an ordinary reactive value any widget can read. Here it highlights matches on the gapminder scatter plot and fills a table:
# Ask querychat to filter the data in plain English. The filtered frame
# highlights points on a plotly scatter plot (updated in place, so zoom and
# pan survive) and fills a table. Try: "just the countries in the Americas
# with gdp per capita over 20000".
import chatlas
import plotly.graph_objects as go
import plotly.express as px
from shiny import reactive
from shiny.express import ui
from querychat.express import QueryChat
from shinywidgets import render_itables, render_plotly
gapminder = px.data.gapminder().query("year == 2007").reset_index(drop=True)
qc = QueryChat(
gapminder,
"gapminder",
client=chatlas.ChatAnthropic(model="claude-haiku-5-5"),
tools=("filter", "query"), # skip querychat's own chart tool; we have our own
greeting="Ask me to filter the 2007 gapminder countries, e.g. "
"\"just the Americas with gdp per capita over 20000\".",
)
ui.page_opts(title="querychat drives a chart and a table", fillable=True)
with ui.sidebar(width=380):
qc.ui()
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("All countries; querychat's matches lit up")
@render_plotly
def scatter():
return go.FigureWidget(
go.Scatter(
x=gapminder["gdpPercap"],
y=gapminder["lifeExp"],
mode="markers",
marker={"color": "#ccc", "size": 8},
text=gapminder["country"],
)
).update_xaxes(type="log", title="GDP per capita").update_yaxes(
title="Life expectancy"
)
@reactive.effect
def _highlight_matches():
matched = set(qc.df()["country"])
all_matched = len(matched) == len(gapminder) # no filter applied yet
with reactive.isolate():
scatter.widget.data[0].marker.color = [
"#ccc" if all_matched or c not in matched else "#e41a1c"
for c in gapminder["country"]
]
with ui.card(full_screen=True):
ui.card_header("querychat's current result set")
@render_itables
def table():
cols = ["country", "continent", "lifeExp", "gdpPercap", "pop"]
return qc.df()[cols]Asking “just the countries in the Americas with gdp per capita over 20000”:


The scatter plot updates in place, so your zoom or pan survives each new question; the table just re-renders.
Pitfalls
Keep what a tool returns small. get_selection() returns every selected row, which is fine for 142 countries. When a selection could be large, return a capped sample (.head(n)) or a summary instead.
Check the model’s input. The model can call a tool with any arguments its signature allows, whatever the system prompt says. highlight() ignores names it doesn’t know and fly_to() accepts only known places; anything that ends up in a file path, URL, or SQL string needs the same care.
Where to go next
- Reacting to widgets for how accessors work.
- Linking widgets for more ways to connect widgets, each of which can be turned into a chat tool.
- The plotly, itables, and ipyleaflet guides for the full accessor reference on each widget used above.