API by module¶
The docstrings of the public modules, generated from the source. The API overview defines what is public and covered by semantic versioning; anything documented here but not listed there is subject to change.
Components¶
AgentChat
¶
Bases: Viewer
Renders the items of a RunState as a chat feed.
User and assistant messages become chat messages whose content
streams in place, thinking becomes a collapsed step, model requests
become ModelCallCards, tool calls ToolCallCards and a failed
run an error alert, all in timeline order. A finished run's usage
totals are shown under its last message. Submitted text is
passed to runner.run (e.g. an AgentRunner, which records the
user message itself) or to a plain callback. With readonly=True no input is shown, e.g. to replay a recording.
With layout="document" the feed reads as a document: a wide centred
column with every message on the left, and the artifacts each run
published shown inline as ArtifactCells under the run's last
message, with the artifact_actions that apply to them.
action_registry = param.ClassSelector(class_=ActionRegistry, default=None, allow_None=True, doc='\n The registry running the ``artifact_actions`` of inline artifacts.')
class-attribute
instance-attribute
¶
add_user_message = param.Boolean(default=True, doc='\n Whether submitting adds the text to the state as a user message\n before invoking the callback. Disable it if the callback emits the\n user message itself. Ignored when a runner is given.')
class-attribute
instance-attribute
¶
approval_factory = param.Callable(default=None, doc='\n Callable ``(ApprovalRequest, RunState) -> Viewable`` rendering\n pending approvals inside tool call cards. Defaults to the\n ApprovalCard factory; set to None to show a placeholder.')
class-attribute
instance-attribute
¶
artifact_actions = param.List(default=[], item_type=ArtifactAction, doc='\n Actions offered on each inline artifact they apply to, e.g. "Add to\n dashboard"; see ``ArtifactAction``.')
class-attribute
instance-attribute
¶
assistant = param.String(default='Assistant', doc='\n Name shown for assistant messages when the run has no agent name.')
class-attribute
instance-attribute
¶
avatars = param.Dict(default={}, doc='\n Avatars of the people and agents in the feed, keyed by the name\n shown, e.g. ``{"Dashboard": "📊"}``: an emoji, text or image URL.\n Names left out get panel-material-ui\'s default for the name.')
class-attribute
instance-attribute
¶
callback = param.Callable(default=None, doc='\n Callable, usually async, invoked with the submitted text when no\n runner is given.')
class-attribute
instance-attribute
¶
can_approve = param.Callable(default=None, allow_None=True, doc="\n Permission hook ``(request, user) -> bool`` set on the approval\n cards the default factory creates. Defaults to the runner's\n ``approval_policy.can_approve`` when it has one.")
class-attribute
instance-attribute
¶
cell_renderer = param.Callable(default=None, allow_None=True, doc="\n Callable ``(artifact) -> Viewable`` rendering the body of an inline\n artifact, e.g. the live object an artifact's value refers to.\n Defaults to the renderer registry.")
class-attribute
instance-attribute
¶
cells
property
¶
The inline artifact cells built so far, keyed by artifact id.
feed
property
¶
feed_params = param.Dict(default={}, doc='\n Additional parameters passed to the underlying pmui ChatFeed or ChatInterface.')
class-attribute
instance-attribute
¶
group_tool_calls = param.Boolean(default=True, doc='\n Whether consecutive tool calls of a run that finished without\n trouble, and the model requests between them, fold into one row,\n "3 steps · 2.1s", that expands to show them. Calls that failed,\n were denied, wait for approval or published an artifact are always\n shown.')
class-attribute
instance-attribute
¶
inline_artifacts = param.Callable(default=None, allow_None=True, doc='\n Predicate ``(artifact) -> bool`` choosing the artifacts shown inline\n in the document layout. Defaults to every artifact that does not\n mirror a host document (``Artifact.is_document``).')
class-attribute
instance-attribute
¶
layout = param.Selector(default='chat', objects=['chat', 'document'], constant=True, doc='\n chat: user messages on the right, artifacts reachable from the\n tool calls that published them. document: a wide centred column\n with every message on the left and the artifacts a run published\n shown inline under its last message.')
class-attribute
instance-attribute
¶
max_cells = param.Integer(default=6, bounds=(1, None), doc='\n How many inline artifacts of a run are shown before the rest wait\n behind a "Show more" button, so a run publishing many is quick to\n show.')
class-attribute
instance-attribute
¶
mentions = param.List(default=[], item_type=Mention, doc='\n What the next message is about, e.g. an item a person handed over\n from elsewhere in the app, shown as chips in the input that they\n can remove. Sending a message writes them at its start, see\n ``Mention``, and clears them.')
class-attribute
instance-attribute
¶
message_params = param.Dict(default={}, doc='\n Parameters given to every ``ChatMessage`` on top of the chat\'s\n own, e.g. ``{"show_avatar": False, "show_user": False}`` to leave\n out who sent each message. ``visible`` is left to the chat, which\n hides and shows messages as runs stream and steps fold, and\n ``css_classes`` are added to the chat\'s own. Changing it builds\n the messages already shown again.')
class-attribute
instance-attribute
¶
model_id = param.String(default=None, allow_None=True, doc="\n The id of the picked model, one of the ``models``' ids. Defaults to the first usable one.")
class-attribute
instance-attribute
¶
model_picker
property
¶
The menu of models below the input; None for a readonly chat.
models = param.List(default=[], doc="\n Models a person may pick for the next request, in a small menu\n below the input (see ``ModelPicker``): model ids, dicts of\n ``ModelChoice`` fields or ``ModelChoice`` objects. The menu is\n shown when there is more than one, and sets the runner's ``model``.")
class-attribute
instance-attribute
¶
on_show_run = param.Callable(default=None, allow_None=True, doc='\n Called with a run id when a person asks how a finished run\'s\n answer was made. When set, every finished top-level run gets a\n "Details" link under its last message, after its usage line if\n one is shown, e.g. opening a ``SpanView`` of the run, as\n ``AgentDrawer`` does.')
class-attribute
instance-attribute
¶
placeholder = param.String(default='Ask the agent…', doc='Placeholder of the input.')
class-attribute
instance-attribute
¶
readonly = param.Boolean(default=False, constant=True, doc='\n Whether to render the feed without an input, e.g. for replay.')
class-attribute
instance-attribute
¶
remember_model = param.String(default=None, allow_None=True, doc='\n A localStorage key under which the browser remembers the picked\n model for the next session, see ``ModelPicker.remember``.')
class-attribute
instance-attribute
¶
runner = param.Parameter(default=None, doc='\n Object with an (async) ``run(text)`` method that adds the user\n message to the state itself, such as an ``AgentRunner``. Its\n ``state`` is used when no state is given.')
class-attribute
instance-attribute
¶
show_model_calls = param.Boolean(default=True, doc="\n Whether model requests are shown as steps. Like tool calls, the\n requests of a run fold into its step group once they succeed; a\n request with no step group to fold into is left out once its run\n finished, when ``show_usage`` reports the run's totals.")
class-attribute
instance-attribute
¶
show_usage = param.Boolean(default=True, doc="\n Whether a finished run's model requests, tokens, cost and wall\n time are shown in a line under its last message.")
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, constant=True)
class-attribute
instance-attribute
¶
tool_labels = param.Dict(default={}, doc='\n Labels for tool calls in the user\'s words, keyed by tool name: a\n string, or a callable taking the call\'s arguments and returning\n one, e.g. ``{"get_report": "Read the report", "update_report":\n lambda args: f"Change {\', \'.join(args)}"}``. Imperative labels\n read right whether the call runs, succeeded, failed or waits. See\n ``ToolCallCard.label``.')
class-attribute
instance-attribute
¶
user = param.String(default='User', doc='Name shown for user messages.')
class-attribute
instance-attribute
¶
user_placement = param.Selector(default=None, objects=[None, 'left', 'right'], allow_None=True, doc='\n Where the user\'s messages are placed. By default on the right in\n the chat layout, as bubbles, and on the left in the document\n layout; "right" makes them bubbles in the document layout too.\n Changing it builds the messages already shown again.')
class-attribute
instance-attribute
¶
refresh_actions()
¶
Evaluate the inline artifacts' actions again, e.g. after the host's state changed.
submit(text)
async
¶
Submit text as the user would through the input, after the mentions, which it clears.
view_for(item)
¶
The component rendering a timeline item. Steps that are not shown, such as calls folded into a collapsed group, are only built when they are shown or asked for here.
AgentDrawer
¶
Bases: Viewer
A collapsible right-hand drawer holding an AgentChat, with views
of the session's artifacts and pending approvals.
Given main, the drawer renders beside that content and, in the
persistent variant, narrows it while open. Place toggle in the
app's header to open and close it; its badge counts pending
approvals. To use the drawer as the contextbar of a pmui.Page
instead, put content in the page's contextbar.
drawer = AgentDrawer(runner, main=dashboard, title="Assistant") pmui.Page(header=[drawer.toggle], main=[drawer])
approvals
property
¶
artifacts
property
¶
can_approve = param.Callable(default=None, allow_None=True, doc="\n Permission hook ``(request, user) -> bool`` for approvals.\n Defaults to the runner's ``approval_policy.can_approve``.")
class-attribute
instance-attribute
¶
chat
property
¶
chat_params = param.Dict(default={}, doc='Additional parameters passed to the AgentChat.')
class-attribute
instance-attribute
¶
content
property
¶
The body of the drawer, for placing it in another container such as a page's contextbar.
main = param.Parameter(default=None, doc='\n The app content the drawer docks beside. Without it the drawer\n renders on its own, e.g. as the last item of an existing layout.')
class-attribute
instance-attribute
¶
max_resize_ratio = param.Number(default=0.6, bounds=(0, 1), doc="\n The largest share of the window's width that dragging the drawer's\n edge makes it, e.g. 0.5 for half the window. It never goes below\n ``min_resize_width``.")
class-attribute
instance-attribute
¶
min_resize_width = param.Integer(default=240, bounds=(240, None), doc="\n The narrowest, in pixels, that dragging the drawer's edge makes it.")
class-attribute
instance-attribute
¶
on_apply = param.Callable(default=None, allow_None=True, doc='\n Callback ``(artifact, version)`` applying a version of a document\n artifact to the host app; see ``ArtifactView.on_apply``.')
class-attribute
instance-attribute
¶
open = param.Boolean(default=False, doc='Whether the drawer is open.')
class-attribute
instance-attribute
¶
open_on_approval = param.Boolean(default=True, doc="\n Whether a new pending approval opens a persistent drawer, so a\n paused run does not go unnoticed. A temporary drawer would cover\n the app, so it only updates the toggle's badge.")
class-attribute
instance-attribute
¶
overlay_below = param.Integer(default=None, allow_None=True, bounds=(0, None), doc="\n Window width in pixels below which a persistent drawer overlays the\n content like a temporary one instead of narrowing it, e.g. 1200 so\n a narrow window keeps its full width for the app. As in the\n temporary variant, a new approval then only updates the toggle's\n badge.")
class-attribute
instance-attribute
¶
redact_runs = param.Parameter(default=False, doc="\n Whether the runs ``show_run`` opens are shown redacted, without\n their content (see ``SpanView.redacted``): a boolean, or a callable\n taking a run id and returning one, e.g. a host's check of whether\n the person viewing may see the data.")
class-attribute
instance-attribute
¶
resizable = param.Boolean(default=True, doc="\n Whether the drawer's left edge can be dragged to resize it, from\n ``min_resize_width`` to ``max_resize_ratio`` of the window. A\n resize sets ``width``, which a host may store to open the drawer\n at that width next time.")
class-attribute
instance-attribute
¶
runner = param.Parameter(default=None, doc='\n Object with an (async) ``run(text)`` method, such as an\n ``AgentRunner``. Its ``state`` and ``approval_policy`` are used\n unless given explicitly.')
class-attribute
instance-attribute
¶
show_approvals = param.Boolean(default=True, doc='Whether the pending approvals bar and view are shown.')
class-attribute
instance-attribute
¶
show_artifacts = param.Boolean(default=True, doc='Whether the artifacts view can be opened.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, constant=True, doc='The RunState to display.')
class-attribute
instance-attribute
¶
tab = param.Selector(default='chat', objects=list(_TABS), doc='\n The view shown in the drawer: the chat, the artifacts (opened from\n the header) or the pending approvals (opened from the bar above the\n chat).')
class-attribute
instance-attribute
¶
title = param.String(default='Assistant', doc='Title shown at the top of the drawer.')
class-attribute
instance-attribute
¶
toggle
property
¶
A button opening and closing the drawer for the app's header. It
shows the number of pending approvals, includes it in its
accessible name and reports whether the drawer is open with
aria-expanded.
variant = param.Selector(default='persistent', objects=['persistent', 'temporary'], doc='\n persistent: the drawer sits beside the content and narrows it.\n temporary: the drawer overlays the content and closes on outside clicks.')
class-attribute
instance-attribute
¶
width = param.Integer(default=420, bounds=(240, None), doc='Width of the open drawer in pixels.')
class-attribute
instance-attribute
¶
new_conversation()
¶
Forget the runner's message history and clear the session's runs, artifacts and approvals. The button in the drawer asks first when there are document artifacts, whose versions would be lost.
show_run(run_id, *, redacted=None)
¶
Open a dialog showing how the run run_id was made: a
SpanView with its question, model requests, tool calls and the
versions it published. Clicking a version opens it in the
artifacts view. The chat's "Details" link and the history's "How
was this made?" action call this. redacted defaults to what
redact_runs says for the run.
ApprovalCard
¶
Bases: Viewer
Review card for a single tool call awaiting human approval.
Shows the tool, its description and the proposed arguments. The
arguments can be edited in a form generated from the tool's JSON
schema, with a field-level diff of the edits. Approving or denying
calls RunState.resolve_approval; once resolved the card collapses
into a compact summary.
can_approve = param.Callable(default=None, allow_None=True, doc='\n Policy hook called as can_approve(request, user). When it returns\n False the decision buttons are disabled and policy_message is shown.')
class-attribute
instance-attribute
¶
current_user
property
¶
edited_args = param.Dict(default=None, allow_None=True, doc='\n Arguments as edited in the form, or None when not editing.')
class-attribute
instance-attribute
¶
editing = param.Boolean(default=False, doc='Whether the arguments editor is shown.')
class-attribute
instance-attribute
¶
embedded = param.Boolean(default=False, doc='\n Whether the card is embedded inside another card such as ``ToolCallCard``.\n Embedded cards drop their outer border, hide the repeated tool title and\n place the description beside the edit toggle.')
class-attribute
instance-attribute
¶
error = param.String(default='', doc='Message explaining why the last action was rejected.')
class-attribute
instance-attribute
¶
form
property
¶
The arguments form, created the first time editing is enabled.
is_edited
property
¶
labels = Labels(default=None, allow_None=True, doc='\n Wording of the actions and outcomes, e.g. {"deny": "Remove",\n "denied": "Removed"} for a plan step. Keys: approve, deny,\n approved, denied, edit, approve_edited, approved_edited,\n approve_all and deny_all. A changed approve or deny needs its\n past tense too; the "with edits" and "all" wording is derived\n from them. Labels on the request, declared with\n ApprovalRule(labels=...), take precedence.')
class-attribute
instance-attribute
¶
permitted
property
¶
policy_message = param.String(default=None, allow_None=True, doc='\n Explanation shown when can_approve rejects the current user.\n Defaults to a sentence using the action labels.')
class-attribute
instance-attribute
¶
request = param.ClassSelector(class_=ApprovalRequest, doc='The approval request to review.')
class-attribute
instance-attribute
¶
require_reason = param.Selector(default='never', objects=['never', 'deny', 'edit', 'always'], doc='\n When a reason must be given: never, when denying, when approving\n with edits, or always.')
class-attribute
instance-attribute
¶
resolved_labels
property
¶
The action labels in effect: defaults, then labels, then the request's own.
state = param.ClassSelector(class_=RunState, doc='The RunState the request belongs to.')
class-attribute
instance-attribute
¶
user = param.String(default=None, allow_None=True, doc='\n User recorded on the decision. Defaults to pn.state.user.')
class-attribute
instance-attribute
¶
approve()
¶
Approve the call, with edits if any. Returns whether it was resolved.
deny()
¶
Deny the call. Returns whether it was resolved.
ApprovalQueue
¶
Bases: Viewer
Lists the pending approvals of a RunState as ApprovalCards, with approve-all / deny-all actions for batches.
batch_labels
property
¶
The labels of the batch actions: the queue's, or those all pending requests share.
can_approve = param.Callable(default=None, allow_None=True, doc='Policy hook passed to each card.')
class-attribute
instance-attribute
¶
card_factory = param.Callable(default=None, allow_None=True, doc='\n Optional callable(request, state, **params) returning an ApprovalCard.')
class-attribute
instance-attribute
¶
cards
property
¶
labels = Labels(default=None, allow_None=True, doc='\n Action labels passed to each card, see ApprovalCard.labels. The\n batch buttons use them too, unless every pending request carries\n the same labels of its own.')
class-attribute
instance-attribute
¶
message = param.String(default='', doc='Outcome of the last batch action.')
class-attribute
instance-attribute
¶
require_reason = param.Selector(default='never', objects=['never', 'deny', 'edit', 'always'], doc='\n Reason requirement passed to each card.')
class-attribute
instance-attribute
¶
show_resolved = param.Boolean(default=False, doc='Whether resolved requests stay listed as summaries.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, doc='The RunState whose pending approvals are listed.')
class-attribute
instance-attribute
¶
title = param.String(default='Pending approvals')
class-attribute
instance-attribute
¶
user = param.String(default=None, allow_None=True, doc='User recorded on decisions, defaults to pn.state.user.')
class-attribute
instance-attribute
¶
approve_all()
¶
Approve every pending request whose card allows it. Returns the number resolved.
deny_all()
¶
Deny every pending request whose card allows it. Returns the number resolved.
ArtifactAction
dataclass
¶
A button offered on artifact cells that runs an action of an
ActionRegistry, e.g. "Add to dashboard".
arguments maps an artifact to the action's arguments, or to None
when the action does not apply to it, which hides the button. done
maps an artifact to a short label shown instead of the button once
the action has nothing left to do for it, e.g. "On dashboard", or to
None.
ArtifactCell
¶
Bases: Viewer
A card showing an artifact's latest version inline, under a header with its kind, its title and the actions that apply to it.
The value is rendered by renderer or the renderer registry, and
rendered again when a new version is published.
actions = param.ClassSelector(class_=ActionRegistry, default=None, allow_None=True, doc="\n The registry that runs the cell's actions.")
class-attribute
instance-attribute
¶
artifact = param.ClassSelector(class_=Artifact, constant=True)
class-attribute
instance-attribute
¶
artifact_actions = param.List(default=[], item_type=ArtifactAction, doc='\n The actions offered on the cell; those whose action the registry\n does not have are left out.')
class-attribute
instance-attribute
¶
renderer = param.Callable(default=None, allow_None=True, doc="\n Callable ``(artifact) -> Viewable`` rendering the cell's body, e.g.\n a host's view of the live object an artifact refers to. Defaults\n to ``render(value, kind)``.")
class-attribute
instance-attribute
¶
refresh()
¶
Evaluate again which actions apply to the artifact and which are done.
release()
¶
Stop following the artifact, e.g. when the feed showing the cell is cleared.
ArtifactPane
¶
Bases: Viewer
Lists the artifacts in an ArtifactStore and shows the active one,
following store.active so newly published artifacts come into focus.
active_view
property
¶
empty_message = param.String(default='Artifacts the agent publishes will appear here.', doc='\n Shown while the store is empty.')
class-attribute
instance-attribute
¶
list_width = param.Integer(default=260, doc='Width of the artifact list in pixels.')
class-attribute
instance-attribute
¶
on_apply = param.Callable(default=None, allow_None=True, doc='\n Callback applying a version of a document artifact to the host\n document; see ``ArtifactView.on_apply``.')
class-attribute
instance-attribute
¶
on_show_run = param.Callable(default=None, allow_None=True, doc='\n Called with a run id from a history\'s "How was this made?"\n action; see ``ArtifactView.on_show_run``.')
class-attribute
instance-attribute
¶
show_list = param.Boolean(default=True, doc='Whether to show the artifact list.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, default=None, allow_None=True, doc='\n RunState recording applied versions. Its artifacts are shown when\n no store is given.')
class-attribute
instance-attribute
¶
store = param.ClassSelector(class_=ArtifactStore, doc='The store to display.')
class-attribute
instance-attribute
¶
view_options = param.Dict(default={}, doc="\n Parameters passed to each ArtifactView, e.g. ``{'diff_layout': 'split'}``.")
class-attribute
instance-attribute
¶
views
property
¶
ArtifactView
¶
Bases: Viewer
A single artifact with its version history, download and a compare mode showing the difference between two versions.
The history lists the versions grouped by the run that made them,
newest first. For a document artifact with an on_apply callback
it also offers undo and redo, which move the applied version through
on_apply and are recorded as ArtifactApplied events; no
version is ever changed or removed.
artifact = param.ClassSelector(class_=Artifact, doc='The artifact to display.')
class-attribute
instance-attribute
¶
base = param.Integer(default=None, allow_None=True, doc='\n Number of the version compared against, counting from 1. Defaults\n to the applied version of a document, otherwise to the one before\n the target.')
class-attribute
instance-attribute
¶
can_redo = param.Boolean(default=False, constant=True, doc='\n Whether ``redo`` can change the applied version.')
class-attribute
instance-attribute
¶
can_undo = param.Boolean(default=False, constant=True, doc='\n Whether ``undo`` can change the applied version.')
class-attribute
instance-attribute
¶
diff_layout = param.Selector(default='unified', objects=['unified', 'split'], doc='\n Layout of text diffs.')
class-attribute
instance-attribute
¶
diff_options = param.Dict(default={}, doc="\n Options passed to the diff strategy, e.g. ``{'key': 'id'}`` for tables.")
class-attribute
instance-attribute
¶
history = param.Boolean(default=None, allow_None=True, doc='\n Whether the version history is open. None opens it for document\n artifacts and keeps it closed for others; the History button in\n the header toggles it.')
class-attribute
instance-attribute
¶
mode = param.Selector(default='preview', objects=['preview', 'compare', 'metadata'], doc='\n Which tab is shown.')
class-attribute
instance-attribute
¶
on_apply = param.Callable(default=None, allow_None=True, doc='\n Callback ``(artifact, version) -> None | bool``, possibly async,\n making the host document match a version of a document artifact.\n When set, the header offers "Apply" for versions after the\n applied one and "Revert to" for earlier ones. Raise an exception\n or return False to refuse; the message is shown.')
class-attribute
instance-attribute
¶
on_show_run = param.Callable(default=None, allow_None=True, doc='\n Called with a run id from the "How was this made?" action on the\n history\'s runs, e.g. opening a ``SpanView``.')
class-attribute
instance-attribute
¶
show_header = param.Boolean(default=True, doc='Whether to show the title row.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, default=None, allow_None=True, doc='\n RunState recording applied versions as ``ArtifactApplied`` events,\n so they show up in recordings. Without it the artifact is updated\n directly.')
class-attribute
instance-attribute
¶
target = param.Integer(default=None, allow_None=True, doc='\n Number of the version compared, counting from 1; defaults to the latest.')
class-attribute
instance-attribute
¶
user = param.String(default=None, allow_None=True, doc='\n User recorded on applied versions. Defaults to pn.state.user.')
class-attribute
instance-attribute
¶
versions
property
¶
apply_version(version=None, *, action=None)
async
¶
Apply version number version (default: the one shown) to the
host document through on_apply and record it. Returns whether
it was applied; False also while another apply is in progress.
action is "undo" or "redo" when applying the version
undoes or redoes changes, as undo and redo do.
compute_diff()
¶
The diff between the base and target versions.
redo()
async
¶
Apply again the version the last undo moved away from through
on_apply, as RunState.redo does. Returns whether the
version was applied.
redo_run(run_id=None)
async
¶
Redo a whole undo, e.g. an undo_run, through on_apply, as
RunState.redo_run does. Returns whether the version was applied.
show_version(number)
¶
Open the history at version number and show it, compared with the applied version of a document.
undo()
async
¶
Undo the last change to the applied version of a document through
on_apply, as RunState.undo does. Returns whether the
version was applied.
undo_run(run_id=None)
async
¶
Undo a whole run through on_apply, as RunState.undo_run
does, resolving child runs through state. Raises
ValueError if the run never changed the applied version.
Returns whether the version was applied, so False if the run is
undone already.
Mention
dataclass
¶
Something a person's next message is about, e.g. an item handed over to the chat from elsewhere in the app.
It shows as a chip in the chat's input, which the person can remove,
and sending a message writes its text at the start of the message,
so the agent reads what the message is about and the conversation
shows it. By default that is @ and the label, quoted unless
it is made of letters, digits and _ . - / : only
(@"Sales by region"), so the name stays one token; pass text
to write something else, e.g. an id. The label must not be empty.
ModelCallCard
¶
Bases: Viewer
Collapsible card for one model request, bound to a ModelCallState.
The header shows the model, the input and output tokens, the cost and the latency; the body lists the cached tokens, finish reason, response, request and run ids, the tool calls the response issued and any error.
call = param.ClassSelector(class_=ModelCallState, constant=True)
class-attribute
instance-attribute
¶
collapsed = param.Boolean(default=True, doc='Whether the card body is collapsed.')
class-attribute
instance-attribute
¶
redacted = param.Boolean(default=False, constant=True, doc='\n Whether to leave out error messages, which can quote the data a\n request was sent, e.g. for a viewer who may not see it.')
class-attribute
instance-attribute
¶
show_tool_count = param.Boolean(default=False, doc='\n Whether the header counts the tool calls the response issued.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, default=None, allow_None=True, constant=True, doc='\n The RunState the call belongs to, used to name the tool calls it issued.')
class-attribute
instance-attribute
¶
ModelChoice
dataclass
¶
A model a person may pick for the agent's next request.
id names the model the way the runner's framework does, e.g. a
pydantic-ai model string such as "openai:gpt-5". model
optionally holds a ready-made model object the runner uses instead of
the id, e.g. one with a custom provider; the id then only identifies
the choice. description is a short hint, e.g. about cost or speed.
description = None
class-attribute
instance-attribute
¶
id
instance-attribute
¶
label = None
class-attribute
instance-attribute
¶
model = None
class-attribute
instance-attribute
¶
name
property
¶
target
property
¶
What the runner is given: the model object if there is one, else the id.
coerce(spec)
classmethod
¶
Make a ModelChoice from a model id, a dict of its fields or a ModelChoice.
ModelPicker
¶
Bases: Viewer
A small menu of the models the agent may run with, for a chat's composer.
The picked model is set as the runner's model, which an
AgentRunner reads when a request starts, so a change applies from
the next request and never to one that is running. Models the runner's
unavailable_reason finds unusable, e.g. because the provider's API key is
missing, are listed disabled with the reason under their label, and a
model's description is shown under its label too.
With a single model there is nothing to pick, so the picker shows that
model's name as plain text, marked when it cannot be used. The text
takes the keyboard focus and shows the model's id and description, or
why it is unavailable, as a tooltip that screen readers announce. With
no models the picker is hidden.
choices
property
¶
label = param.String(default='Model', doc='The accessible name of the picker.')
class-attribute
instance-attribute
¶
models = param.List(default=[], doc='\n The models to choose from: model ids, dicts of ``ModelChoice``\n fields or ``ModelChoice`` objects.')
class-attribute
instance-attribute
¶
remember = param.String(default=None, allow_None=True, doc='\n A localStorage key under which the browser remembers the picked\n model, so the next session starts with it if it is still offered\n and usable. None remembers nothing.')
class-attribute
instance-attribute
¶
runner = param.Parameter(default=None, doc='\n The runner whose ``model`` follows the picked model, e.g. an\n ``AgentRunner``. Its ``unavailable_reason(model)``, if it has one, tells\n why a model cannot be used.')
class-attribute
instance-attribute
¶
unavailable = param.Dict(default={}, constant=True, doc='Why each unusable model cannot be used, by id.')
class-attribute
instance-attribute
¶
value = param.String(default=None, allow_None=True, doc='\n The id of the picked model. Defaults to the first usable model.')
class-attribute
instance-attribute
¶
RunTrace
¶
Bases: Viewer
Every step of one run, unfolded: each model request with the tool calls it issued nested under it, a bar per step on the run's time axis, and the run's totals (model requests, input tokens with those read from the cache, output tokens, cost and wall time) on top.
Expanding a model request shows its details. The view is readonly
and follows the run while it is in progress, so a host can show the
provenance of any run by its run_id, e.g. in a dialog.
include_children = param.Boolean(default=False, doc="\n Whether the steps of the run's child runs, e.g. a sub-agent's, are\n shown with the run's own, under a label naming the child run, and\n counted in the totals.")
class-attribute
instance-attribute
¶
redacted = param.Boolean(default=False, constant=True, doc="\n Whether to show the run's shape without its content: which tools\n ran, the models, tokens, cost and timings stay, the question, the\n agent's text, tool arguments and results, approval descriptions and\n error messages are hidden.")
class-attribute
instance-attribute
¶
row_limit = param.Integer(default=None, allow_None=True, bounds=(1, None), doc='\n Number of steps built at first, with a button building the next\n as many, or None to build them all. Keeps a long run cheap to open.')
class-attribute
instance-attribute
¶
run
property
¶
The RunInfo of the run shown, or None.
run_id = param.String(default=None, allow_None=True, doc='Id of the run to show.')
class-attribute
instance-attribute
¶
show_totals = param.Boolean(default=True, doc="Whether to show the run's usage totals above the steps.")
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, constant=True)
class-attribute
instance-attribute
¶
release()
¶
Stop following the state, e.g. once the view is closed for good. A view that is not released keeps updating, and keeps its cards alive, for as long as the state lives.
SchemaForm
¶
Bases: Viewer
The SchemaForm generates a form of Material UI widgets from a JSON
schema and keeps value in sync with the widgets in both directions.
Strings map to text inputs (or text areas for long text), enums to
selects, numbers to numeric inputs honoring minimum/maximum,
booleans to switches, date/date-time formats to pickers, enum
arrays to multi-choice inputs and nested objects to grouped cards.
$ref/$defs, allOf and nullable anyOf unions are resolved;
any other shape falls back to a JSON editor for that field.
:Example:
SchemaForm(schema={ ... "type": "object", ... "properties": {"name": {"type": "string"}, "age": {"type": "integer", "minimum": 0}}, ... "required": ["name"], ... }, value={"name": "Ada"})
boolean_widget = param.Selector(default='switch', objects=['switch', 'checkbox'], doc='\n Widget used for boolean fields.')
class-attribute
instance-attribute
¶
disabled = param.Boolean(default=False, doc='Whether the form widgets are disabled.')
class-attribute
instance-attribute
¶
errors = param.List(default=[], constant=True, doc='\n Errors found by the most recent call to validate().')
class-attribute
instance-attribute
¶
live_validation = param.Boolean(default=False, doc='\n Whether to validate (and display errors) on every change rather\n than only when validate() is called.')
class-attribute
instance-attribute
¶
schema = param.Dict(default={'type': 'object', 'properties': {}}, doc='\n The JSON schema describing the form, usually an object schema.')
class-attribute
instance-attribute
¶
valid
property
¶
value = param.Dict(default={}, doc='\n The current form value as JSON-compatible data.')
class-attribute
instance-attribute
¶
field(path)
¶
Return the panel-material-ui widget of the field at path, a dotted
string or tuple of keys, or the card holding a nested object's fields.
validate()
¶
Validate the current value against the schema, display errors
on the widgets and return them as "<path>: <message>" strings.
SpanView
¶
Bases: Viewer
Everything one run did, read-only: the question, the run's totals,
every model request with the tool calls it issued on one time axis
(a RunTrace), the artifact versions it published and the problems
it ran into. Child runs count as part of the run. The view follows a
run still in progress until release is called.
Built for provenance, e.g. a host's "How was this made?" on something
an agent produced: RunState.span gives the same information as
data. With redacted=True it shows the run's shape without its
content, for people who may not see the data.
on_artifact = param.Callable(default=None, allow_None=True, doc='\n Called with an artifact id and a version number when a published\n version is clicked, e.g. to open that version.')
class-attribute
instance-attribute
¶
redacted = param.Boolean(default=False, constant=True, doc="\n Whether to show which tools ran, the models, tokens, cost, timings\n and the titles and numbers of the versions published, but not the\n question, the agent's text, tool arguments and results, approval\n descriptions, error messages or version details.")
class-attribute
instance-attribute
¶
row_limit = param.Integer(default=50, allow_None=True, bounds=(1, None), constant=True, doc='\n Number of steps built when the view opens, with a button building\n the next as many; None builds them all.')
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True, doc='Id of the run to show.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, constant=True)
class-attribute
instance-attribute
¶
release()
¶
Stop following the state, e.g. once the view is closed for good. A view that is not released keeps updating for as long as the state lives.
ToolCallCard
¶
Bases: Viewer
Collapsible card for one tool call, bound to a ToolCallState.
The header summarizes the call (tool name, arguments, status and duration); the body shows the arguments as they stream, the rendered result or error, a pending approval and the artifacts the call published. Collapsed by default, it expands when the call fails or needs approval.
approval_factory = param.Callable(default=None, doc='\n Callable ``(ApprovalRequest, RunState) -> Viewable`` producing the\n widget shown while the call awaits approval. When None a short\n notice is shown instead.')
class-attribute
instance-attribute
¶
call = param.ClassSelector(class_=ToolCallState, constant=True)
class-attribute
instance-attribute
¶
collapsed = param.Boolean(default=True, doc='Whether the card body is collapsed.')
class-attribute
instance-attribute
¶
label = param.Parameter(default=None, doc='\n What the call does in the user\'s words, e.g. "Read the dashboard",\n shown in the header instead of the tool name and arguments, which\n move into the body. A callable is called with the call\'s arguments;\n if it raises or returns anything but a non-empty string the header\n shows the tool name and arguments as without a label.')
class-attribute
instance-attribute
¶
max_chars = param.Integer(default=20000, bounds=(1, None), doc='\n Maximum number of characters of a string result to display.')
class-attribute
instance-attribute
¶
max_items = param.Integer(default=1000, bounds=(1, None), doc='\n Maximum number of items or rows of a result to display.')
class-attribute
instance-attribute
¶
max_lines = param.Integer(default=30, bounds=(1, None), doc='\n Number of lines of a code or JSON result shown before a\n "Show all" button expands it.')
class-attribute
instance-attribute
¶
redacted = param.Boolean(default=False, constant=True, doc='\n Whether to show which tool ran, its status and duration without\n its arguments, result or error message, e.g. for a viewer who may\n not see the data. A callable ``label`` is not used, as it reads\n the arguments.')
class-attribute
instance-attribute
¶
show_artifact = param.Callable(default=None, allow_None=True, doc='\n Predicate ``(artifact) -> bool`` choosing which published artifacts\n get a chip, e.g. leaving out those a feed shows inline already.\n Defaults to all of them.')
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, default=None, allow_None=True, constant=True, doc='\n The RunState the call belongs to, used to find published artifacts.')
class-attribute
instance-attribute
¶
published_artifacts()
¶
Artifacts published by this call, as (artifact, latest matching version) pairs.
resolved_label()
¶
The label of the call, or None when there is none or it could not be made.
approval_factory(request, state)
¶
Build an ApprovalCard, matching the Callable[[ApprovalRequest, RunState], Viewable] hook.
register_renderer(func=None, *, kind=None, type=None, applies=None, priority=0)
¶
Register a renderer, usable as a decorator.
The renderer is called as func(value, **options) and must return
something pn.panel accepts.
render(value, kind=None, **options)
¶
Render a tool result or artifact value with the registered renderers.
Text, including a renderer returning a string, is rendered with
security.inert_markdown and without math, so it cannot run script
or load remote resources by itself, and values with no renderer that
would render as HTML are shown as plain text.
Run state¶
Reactive state of agent runs, built by applying normalized events.
Components bind to the parameterized objects defined here and never see framework-specific objects. Because the state is derived purely from events, replaying a recording reproduces the same state.
ApprovalRequest
¶
Bases: Parameterized
args = param.Dict(default={}, doc='Arguments the agent proposed.')
class-attribute
instance-attribute
¶
description = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
edited
property
¶
final_args = param.Dict(default=None, allow_None=True, doc='Arguments after user edits, if approved.')
class-attribute
instance-attribute
¶
labels = param.Dict(default=None, allow_None=True, doc='\n Wording of the decision actions, e.g. {"approve": "Approve", "deny": "Remove"},\n overriding the approval components\' own labels.')
class-attribute
instance-attribute
¶
reason = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
requested_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
resolved_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
schema = param.Dict(default=None, allow_None=True, doc='JSON schema of the tool arguments.')
class-attribute
instance-attribute
¶
status = param.Selector(default='pending', objects=['pending', 'approved', 'denied'])
class-attribute
instance-attribute
¶
tool_call_id = param.String(constant=True)
class-attribute
instance-attribute
¶
tool_name = param.String(constant=True)
class-attribute
instance-attribute
¶
user = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
MessageState
¶
Bases: Parameterized
content = param.String(default='')
class-attribute
instance-attribute
¶
created_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
finished = param.Boolean(default=False)
class-attribute
instance-attribute
¶
kind = param.Selector(default='text', objects=['text', 'thinking', 'error'], doc='\n ``error`` messages report a failed run; their content is the error message.')
class-attribute
instance-attribute
¶
message_id = param.String(constant=True)
class-attribute
instance-attribute
¶
role = param.Selector(default='assistant', objects=['assistant', 'user', 'system', 'developer'])
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
ModelCallState
¶
Bases: Parameterized
One request to the model and its response.
attempts = param.List(default=[], item_type=ev.Usage, doc='\n Failed attempts at this request that a retry or fallback\n recovered from, as their ``Usage`` events.')
class-attribute
instance-attribute
¶
cached_tokens = param.Integer(default=0, doc="Input tokens read from the provider's cache.")
class-attribute
instance-attribute
¶
cost_usd = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
duration
property
¶
elapsed = param.Number(default=None, allow_None=True, doc='\n Seconds the request took as the adapter measured it, if known.')
class-attribute
instance-attribute
¶
ended_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
error = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
finish_reason = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
input_tokens = param.Integer(default=0, doc='Input tokens, including those read from the cache.')
class-attribute
instance-attribute
¶
model = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
output_tokens = param.Integer(default=0)
class-attribute
instance-attribute
¶
provider_response_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
request_id = param.String(constant=True)
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
started_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
status = param.Selector(default='running', objects=['running', 'success', 'failed'])
class-attribute
instance-attribute
¶
tool_call_ids = param.List(default=[], item_type=str, doc='The tool calls the response issued.')
class-attribute
instance-attribute
¶
RunInfo
¶
Bases: Parameterized
agent_name = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
cached_tokens
property
¶
cost_usd
property
¶
duration
property
¶
ended_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
error = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
guardrails = param.List(default=[], item_type=ev.GuardrailFired)
class-attribute
instance-attribute
¶
input = param.Parameter(default=None)
class-attribute
instance-attribute
¶
input_tokens
property
¶
model_duration
property
¶
Seconds spent waiting for the model, summed over the requests that report a duration.
models
property
¶
The models the run requested, in order of first use.
output_tokens
property
¶
parent_run_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
requests
property
¶
Number of model requests, failed ones and retried attempts
included, as reported by Usage events. A request cut off by a
RunError without a Usage of its own is not counted;
AgentRunner always reports one.
result = param.Parameter(default=None)
class-attribute
instance-attribute
¶
run_id = param.String(constant=True)
class-attribute
instance-attribute
¶
started_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
status = param.Selector(default='running', objects=['running', 'finished', 'error', 'cancelled'], doc='\n ``cancelled`` runs were stopped on purpose, e.g. by the user; ``error``\n holds the reason given, as for a failed run.')
class-attribute
instance-attribute
¶
steps = param.List(default=[], doc='Names of steps in the order they started.')
class-attribute
instance-attribute
¶
thread_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
usage = param.List(default=[], item_type=ev.Usage)
class-attribute
instance-attribute
¶
RunSpan
dataclass
¶
Bases: _UsageTotals
Everything one run did, read from a RunState by RunState.span:
the question, the model requests with the tool calls each issued, the
agent's messages, the artifact versions published and what failed.
Child runs count as part of the run, as for RunState.undo_run, and
the totals (requests, input_tokens, output_tokens,
cached_tokens, cached_share, cost_usd, model_duration,
models) cover them too; duration is the run's wall time.
A snapshot: the entities in it are the state's live objects, but the
lists are not updated as the run goes on; call span again.
RunState
¶
Bases: Parameterized
Reactive store for one session's agent runs.
Adapters call apply with normalized events; components watch
the parameters and the per-entity parameterized objects. All
methods must be called from the session's event loop.
agent_state = param.Dict(default={}, doc='Shared state synchronized with the agent.')
class-attribute
instance-attribute
¶
approvals = param.Dict(default={}, doc='Mapping of tool call id to ApprovalRequest.')
class-attribute
instance-attribute
¶
artifacts = param.ClassSelector(class_=ArtifactStore)
class-attribute
instance-attribute
¶
dropped_events
property
¶
How many of the earliest events max_events dropped since the
state was created or reset; while it is above zero, events does
not replay to this state.
events
property
¶
The applied events, or the latest max_events of them.
flush_interval = param.Number(default=0.05, bounds=(0, None), doc='\n Minimum seconds between UI updates while streaming deltas.\n Deltas arriving faster are coalesced. Zero disables coalescing.')
class-attribute
instance-attribute
¶
items = param.List(default=[], doc='\n Messages, model calls and tool calls in the order they started,\n the timeline a chat view renders.')
class-attribute
instance-attribute
¶
max_events = param.Integer(default=None, allow_None=True, bounds=(1, None), doc="\n Number of the latest events ``events`` keeps in memory, or None to\n keep them all. A long session's events otherwise grow without\n limit. Dropping events does not change the state, but ``events``\n then no longer replays to it, so keep the full log with a\n ``Recorder`` (or ``HistoryRecorder``) attached from the start.")
class-attribute
instance-attribute
¶
messages = param.Dict(default={}, doc='Mapping of message id to MessageState.')
class-attribute
instance-attribute
¶
model_calls = param.Dict(default={}, doc='Mapping of request id to ModelCallState.')
class-attribute
instance-attribute
¶
pending_approvals = param.List(default=[], item_type=ApprovalRequest)
class-attribute
instance-attribute
¶
running = param.Boolean(default=False, doc='Whether any top-level run is in progress.')
class-attribute
instance-attribute
¶
runs = param.Dict(default={}, doc='Mapping of run id to RunInfo.')
class-attribute
instance-attribute
¶
tool_calls = param.Dict(default={}, doc='Mapping of tool call id to ToolCallState.')
class-attribute
instance-attribute
¶
add_user_message(content, run_id=None)
¶
apply(event, notify=True)
¶
apply_artifact_version(artifact_id, version, user=None, action=None)
¶
Record that a person applied version (counting from 1) of a
document artifact to the host document. action is "undo"
or "redo" when applying it undoes or redoes changes, see
Artifact.undo_version.
apply_many(events, notify=True)
¶
Apply events in order. With notify=False subscribers such as a
Recorder or an AgentRunner are not called, e.g. when
restoring events that are already stored.
drop_artifact_versions(artifact_id, before)
¶
Drop the values of the versions of a document artifact numbered
below before, except the applied one, and return the numbers
dropped. The artifact lets go of the values, so they are freed once
nothing else holds them: state.events keeps the events that
published them unless max_events trims them, so a long editing
session bounds its memory with both.
A dropped version keeps its number, run, actor, user, tool call,
metadata and time, so version numbers never shift, but its
value becomes None and dropped True. It leaves the undo and
redo history: undo stops at the oldest version kept, an
undo_run or redo_run whose target was dropped has nothing
to do, and applying it raises ValueError. Recorded as an
ArtifactVersionsDropped event, so a replay drops the same
versions. Raises ValueError if before is below 1 or the
artifact is not a document.
flush()
¶
Apply all buffered streaming deltas.
from_events(events, **params)
classmethod
¶
publish_artifact(artifact_id, value, *, kind=None, title=None, metadata=None, applied=False, run_id=None, tool_call_id=None, actor=None, user=None)
¶
Publish a version of an artifact from the host app rather than a
tool, e.g. after the user edited a document directly. With
applied=True the version becomes the one the host document holds.
run_id, tool_call_id, actor and user record who
made the version. Called from code an AgentRunner runs, such
as a mutator a tool calls, they default to the current run and
tool call with the actor "agent"; inside user_run to that
run and its user; anywhere else to the actor "user" and
pn.state.user.
redo(artifact_id, *, user=None, on_apply=None)
¶
Apply again the version the last undo moved away from, recorded with
action="redo". Redo lasts until the applied version changes
other than by undo or redo, i.e. a version is published as applied
or applied by hand; a proposal, published without applied,
keeps it. Arguments and result as for undo.
redo_run(artifact_id, run_id=None, *, user=None, on_apply=None)
¶
Redo a whole undo in one step, e.g. an undo_run: apply again the
version the host held before it, recorded as one ArtifactApplied
event with action="redo". Without run_id this redoes the
last undo; with it, the latest undo still redoable that undid a
version of that run, and any undos after it, or None if those
would also redo a version made outside the run. Redo ends
as for redo. Other arguments and result as for undo.
reset()
¶
resolve_approval(tool_call_id, approved, args=None, reason=None, user=None)
¶
Approve or deny a pending tool call, optionally with edited args.
Raises ValueError if the request was already decided or the
edited arguments are not valid for the tool, and PermissionError
if the runner's approval policy does not allow user to make
this decision.
span(run_id)
¶
Everything the run run_id and its child runs did, as a
RunSpan: the question, each model request with the tool calls
it issued, the agent's messages, the artifact versions published
and the errors. Raises KeyError if the state has no such run,
e.g. because the events of an older session were not loaded.
Reads the items and artifact versions once, so it costs time in proportion to the session, and is meant to be called when a person asks for the span rather than on every event.
subscribe(callback)
¶
Call callback with every applied event; returns an unsubscribe function.
undo(artifact_id, *, user=None, on_apply=None)
¶
Undo the last change to the applied version of a document artifact:
apply the version that was applied before it, recorded as an
ArtifactApplied event with action="undo". Undoing a revert
returns to the version applied before the revert.
on_apply(artifact, version) makes the host document match the
version first; raising or returning False refuses the step, and
nothing is recorded. It must be synchronous; ArtifactView awaits
an async one. user defaults to pn.state.user. Returns the
applied version, or None if there was nothing to undo or the step
was refused.
undo_run(artifact_id, run_id=None, *, user=None, on_apply=None)
¶
Undo a whole run in one step: apply the version the host held
before the run first changed the applied version, recorded as one
ArtifactApplied event with action="undo". run_id
defaults to the run of the applied version, and a child run counts
as part of its top-level run. redo steps forward through the
run's versions again and redo_run redoes them all. Returns None
without calling on_apply if the run is undone already, or if a
version made outside the run came after the run's first change
(Artifact.undo_run_blocked), since undoing the run would take
that version back too; undo still steps back one version
at a time. Raises ValueError if the run never changed the
applied version. Other arguments and result as for undo.
user_run(input=None, *, user=None, run_id=None)
¶
Group a person's edits into a run of their own, yielding its id.
Emits RunStarted with the user as agent_name and input
(e.g. a description of the edit) on entry and RunFinished on
exit, also when the block raises, and makes publish_artifact
inside the block default to this run, the actor "user" and
user, which defaults to pn.state.user. A user run has no
model calls.
Meant for a synchronous batch of edits: a top-level user run
makes the state count as running while the block is open, so
do not await inside it. Called from code a run executes, such as
a tool, it starts a child run of that run instead
(parent_run_id), and versions published in it keep the
enclosing run's attribution, e.g. the agent and its tool call;
user is ignored inside an agent's run. Raises ValueError
if run_id is already a run of this state.
SpanError
dataclass
¶
ToolCallState
¶
Bases: Parameterized
approval = param.ClassSelector(class_=ApprovalRequest, default=None, allow_None=True)
class-attribute
instance-attribute
¶
args = param.Dict(default={}, doc='Best-effort parse of the (possibly partial) arguments.')
class-attribute
instance-attribute
¶
args_text = param.String(default='', doc='Raw JSON-encoded arguments as streamed.')
class-attribute
instance-attribute
¶
duration
property
¶
ended_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
error = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
parent_message_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
result = param.Parameter(default=None)
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True)
class-attribute
instance-attribute
¶
started_at = param.Number(default=None, allow_None=True)
class-attribute
instance-attribute
¶
status = param.Selector(default='pending', objects=['pending', 'awaiting_approval', 'running', 'success', 'failed', 'denied'], doc='\n pending: arguments are still streaming.\n awaiting_approval: the call is blocked on a human decision.\n running: arguments are complete and the tool is executing.\n success / failed: the tool returned or raised.\n denied: a human rejected the call.')
class-attribute
instance-attribute
¶
tool_call_id = param.String(constant=True)
class-attribute
instance-attribute
¶
tool_name = param.String(default='')
class-attribute
instance-attribute
¶
Run context¶
The run and tool call the current code executes in.
An AgentRunner sets them while a run is in progress and around each
tool call, and RunState.user_run sets them for a batch of a
person's edits, so host code called from a tool, such as a document
mutator, can tell which run and tool call it belongs to without being
handed a pydantic-ai RunContext. The values live in a context
variable, so they follow the code into awaited coroutines, tasks it
starts (also after the run ends) and the worker threads pydantic-ai
runs sync tools in, but not into independently scheduled callbacks: a
widget callback that fires while an agent runs sees no run, and its
edits count as the person's. Callbacks reacting to the run's own
events run inside the run.
Events¶
Normalized agent run events.
The taxonomy mirrors the AG-UI protocol so that framework adapters
(pydantic-ai, AG-UI, ...) all translate into the same small set of
events and components never depend on a specific agent framework.
Kit-specific events (artifacts, approvals, usage, guardrails) map onto
AG-UI CUSTOM events when exchanged over that protocol.
ApprovalRequested
dataclass
¶
Bases: Event
args = field(default_factory=dict)
class-attribute
instance-attribute
¶
description = None
class-attribute
instance-attribute
¶
labels = None
class-attribute
instance-attribute
¶
schema = None
class-attribute
instance-attribute
¶
tool_call_id
instance-attribute
¶
tool_name
instance-attribute
¶
type = 'APPROVAL_REQUESTED'
class-attribute
¶
ApprovalResolved
dataclass
¶
ArtifactApplied
dataclass
¶
Bases: Event
A person applied a version of a document artifact to the host document.
action = None
class-attribute
instance-attribute
¶
"undo" or "redo" when the version was applied by undoing or
redoing; None for any other apply, which is a change that can itself
be undone.
artifact_id
instance-attribute
¶
type = 'ARTIFACT_APPLIED'
class-attribute
¶
user = None
class-attribute
instance-attribute
¶
version
instance-attribute
¶
The applied ArtifactVersion.version, counting from 1.
ArtifactPublished
dataclass
¶
Bases: Event
actor = None
class-attribute
instance-attribute
¶
Who made the version, e.g. "agent" or "user".
applied = False
class-attribute
instance-attribute
¶
Whether the host document already holds this version, e.g. because the tool edited the document in place.
artifact_id
instance-attribute
¶
kind = None
class-attribute
instance-attribute
¶
metadata = field(default_factory=dict)
class-attribute
instance-attribute
¶
title = None
class-attribute
instance-attribute
¶
tool_call_id = None
class-attribute
instance-attribute
¶
type = 'ARTIFACT_PUBLISHED'
class-attribute
¶
user = None
class-attribute
instance-attribute
¶
Name of the person who made the version, if a person did.
value
instance-attribute
¶
ArtifactVersionsDropped
dataclass
¶
Custom
dataclass
¶
Event
dataclass
¶
ModelRequestStarted
dataclass
¶
RunError
dataclass
¶
RunFinished
dataclass
¶
RunStarted
dataclass
¶
StateDelta
dataclass
¶
StateSnapshot
dataclass
¶
StepFinished
dataclass
¶
StepStarted
dataclass
¶
TextMessageContent
dataclass
¶
TextMessageEnd
dataclass
¶
TextMessageStart
dataclass
¶
ThinkingContent
dataclass
¶
ThinkingEnd
dataclass
¶
ThinkingStart
dataclass
¶
ToolCallArgs
dataclass
¶
ToolCallEnd
dataclass
¶
ToolCallResult
dataclass
¶
ToolCallStart
dataclass
¶
Usage
dataclass
¶
Bases: Event
The outcome of one model request: its tokens, cost and duration.
Events without a request_id, as written before model requests were
announced by ModelRequestStarted, still describe one request each.
attempt_of = None
class-attribute
instance-attribute
¶
For a failed attempt that a retry or fallback recovered from, the
request_id of the request it belongs to.
cached_tokens = 0
class-attribute
instance-attribute
¶
cost_usd = None
class-attribute
instance-attribute
¶
duration = None
class-attribute
instance-attribute
¶
error = None
class-attribute
instance-attribute
¶
Why the request failed, None if it succeeded.
finish_reason = None
class-attribute
instance-attribute
¶
input_tokens = 0
class-attribute
instance-attribute
¶
message_id = None
class-attribute
instance-attribute
¶
model = None
class-attribute
instance-attribute
¶
output_tokens = 0
class-attribute
instance-attribute
¶
provider_response_id = None
class-attribute
instance-attribute
¶
request_id = None
class-attribute
instance-attribute
¶
tool_call_ids = field(default_factory=list)
class-attribute
instance-attribute
¶
The tool calls the response issued.
type = 'USAGE'
class-attribute
¶
Artifacts¶
Artifact
¶
Bases: Parameterized
Something the agent produced, kept as a list of versions.
applied = param.Integer(default=None, allow_None=True, constant=True, doc='\n Number of the version the host document holds, counting from 1;\n None unless the artifact is a document. Changed by publishing an\n applied version or by ``RunState.apply_artifact_version``.')
class-attribute
instance-attribute
¶
applied_version
property
¶
The version the host document holds, or None if the artifact is not a document.
artifact_id = param.String(constant=True)
class-attribute
instance-attribute
¶
current = param.Integer(default=None, allow_None=True, bounds=(1, None), doc='\n Number of the version currently selected for display, counting\n from 1 like ``ArtifactVersion.version``. None while there are no versions.')
class-attribute
instance-attribute
¶
is_document
property
¶
Whether the artifact mirrors a document the host app owns, i.e. one of its versions was published as applied or applied by a person.
kind = param.String(default='object', doc="\n What the artifact holds, e.g. 'table', 'sql', 'code', 'text',\n 'json' or 'plot'. Used to select renderers and diff strategies.")
class-attribute
instance-attribute
¶
latest
property
¶
redo_run_version = param.Integer(default=None, allow_None=True, constant=True, doc='\n Number of the version redoing the whole last undo would apply,\n e.g. the version an undone run had left the host document at, or\n None if there is nothing to redo. See ``RunState.redo_run``.')
class-attribute
instance-attribute
¶
redo_version = param.Integer(default=None, allow_None=True, constant=True, doc='\n Number of the version redoing the last undo would apply, or None\n if there is nothing to redo. Publishing an applied version, or\n applying a version other than by undo or redo, ends redo;\n publishing a version that is not applied, a proposal, does not.')
class-attribute
instance-attribute
¶
title = param.String(default='')
class-attribute
instance-attribute
¶
undo_version = param.Integer(default=None, allow_None=True, constant=True, doc='\n Number of the version undoing the last change to the applied\n version would apply, or None if there is nothing to undo. Every\n change to the applied version can be undone: publishing an applied\n version, and applying an earlier or later one by hand. See\n ``RunState.undo``.')
class-attribute
instance-attribute
¶
value
property
¶
versions = param.List(default=[], item_type=ArtifactVersion)
class-attribute
instance-attribute
¶
add_version(value, tool_call_id=None, metadata=None, created_at=None, applied=False, *, run_id=None, actor=None, user=None)
¶
drop_versions(before)
¶
Drop the values of the versions numbered below before, except
the applied one, and return the numbers dropped. Their numbers and
authors stay; they leave the undo and redo history, so undo stops
at the oldest version kept. Raises ValueError for an artifact
that is not a document, which has no applied version to keep.
redo_run_target(run_id=None, runs=None)
¶
Number of the version redoing a whole undo would apply, or None if
there is nothing to redo. Without run_id this is the last undo,
redo_run_version. With it, it is the earliest undo still
redoable that undid a version of that run (resolved through
runs as for run_versions), so that afterwards none of the
run's versions is left to redo; undos after it are redone too,
since redo is linear, so it is None if that would also redo a
version made outside the run.
run_versions(run_id, runs=None)
¶
Numbers of the versions published in run_id. With runs,
e.g. RunState.runs, both ids are resolved to their top-level
run, so the versions of child runs count as part of it.
undo_run_blocked(run_id=None, runs=None)
¶
Whether undoing the run run_id is refused because a version
made outside the run, by a later run or with no run, came after the
run's first change: undoing the run would take that version back
too, so it has to be undone first. run_id and runs
work as for undo_run_target; False if the run cannot be undone
for another reason.
undo_run_target(run_id=None, runs=None)
¶
Number of the version undoing the run run_id would apply: the
one the host held before the run first changed the applied
version. run_id defaults to the run of the applied version and
runs works as for run_versions. None if the run is undone
already, i.e. that version is applied or can only be reached by
redo, or if a version made outside the run came after the run's
first change, which undoing the run would take back too (see
undo_run_blocked). Raises ValueError if the run never
changed the applied version, e.g. because it only proposed versions.
ArtifactStore
¶
Bases: Parameterized
Per-session collection of artifacts.
active = param.String(default=None, allow_None=True, doc='\n Id of the artifact currently in focus.')
class-attribute
instance-attribute
¶
artifacts = param.Dict(default={}, doc='\n Mapping from artifact id to Artifact, in publication order.')
class-attribute
instance-attribute
¶
drop_versions(artifact_id, before)
¶
Drop the values of older versions of an artifact, see Artifact.drop_versions.
mark_applied(artifact_id, version, action=None)
¶
Record that the host document now holds version (counting
from 1) of an artifact and show it as current; action is
"undo" or "redo" when it was applied by undoing or redoing.
publish(artifact_id, value, kind=None, title=None, tool_call_id=None, metadata=None, created_at=None, applied=False, *, run_id=None, actor=None, user=None)
¶
Create an artifact, or add a new version if the id exists.
applied marks the version as the one the host document now
holds, which makes the artifact a document. run_id, actor
and user record who made the version, see ArtifactVersion.
published_by(tool_call_id)
¶
Artifacts a tool call published, in publication order, each paired
with the latest version that call published. Looking a call up
does not scan the versions, so it stays cheap however many there
are. Versions are attributed to calls as publish adds them or
when artifacts is replaced; Artifact.add_version called
directly does not update the lookup.
ArtifactVersion
¶
Bases: Parameterized
actor = param.String(default=None, allow_None=True, constant=True, doc="\n Who made the version, e.g. 'agent' or 'user'. A free string, so\n hosts may add their own, such as 'import'. None in recordings\n made before versions recorded their actor.")
class-attribute
instance-attribute
¶
created_at = param.Number(constant=True)
class-attribute
instance-attribute
¶
dropped = param.Boolean(default=False, constant=True, doc="\n Whether the version's value was dropped to bound memory, see\n ``RunState.drop_artifact_versions``. It keeps its number and who\n made it, but its ``value`` is None and it cannot be applied.")
class-attribute
instance-attribute
¶
metadata = param.Dict(default={}, constant=True)
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True, constant=True, doc="\n Id of the run the version was published in: an agent run, or a\n run grouping a person's edits (``RunState.user_run``).")
class-attribute
instance-attribute
¶
tool_call_id = param.String(default=None, allow_None=True, constant=True, doc='\n Id of the tool call that published the version, if a tool did.')
class-attribute
instance-attribute
¶
user = param.String(default=None, allow_None=True, constant=True, doc='\n Name of the person who made the version, if a person did.')
class-attribute
instance-attribute
¶
value = param.Parameter(constant=True)
class-attribute
instance-attribute
¶
version = param.Integer(default=1, bounds=(1, None), constant=True)
class-attribute
instance-attribute
¶
Change
dataclass
¶
One semantic change between two versions of a structured value.
label = None
class-attribute
instance-attribute
¶
Human readable description shown instead of the path, e.g. "Node 'sales' added".
new = None
class-attribute
instance-attribute
¶
old = None
class-attribute
instance-attribute
¶
op
instance-attribute
¶
'add', 'remove' or 'change'.
path
instance-attribute
¶
Keys and list positions leading to the change, e.g. ("nodes", "sales", "config").
path_str
property
¶
The path for display, e.g. nodes.sales.config or edges[2]; not meant to be parsed.
Diff
dataclass
¶
StructuredDiff
dataclass
¶
Bases: Diff
A list of semantic changes, the result to return from a custom diff strategy for documents such as configurations or dashboards.
Set old_text and new_text to also offer a line diff of the
serialized versions.
TableDiff
dataclass
¶
Bases: Diff
alignment = None
class-attribute
instance-attribute
¶
cells_modified = field(default_factory=list)
class-attribute
instance-attribute
¶
columns_added = field(default_factory=list)
class-attribute
instance-attribute
¶
columns_removed = field(default_factory=list)
class-attribute
instance-attribute
¶
columns_reordered = False
class-attribute
instance-attribute
¶
dtype_changes = field(default_factory=dict)
class-attribute
instance-attribute
¶
kind = 'table'
class-attribute
instance-attribute
¶
new_shape = (0, 0)
class-attribute
instance-attribute
¶
old_shape = (0, 0)
class-attribute
instance-attribute
¶
rows_added = field(default_factory=list)
class-attribute
instance-attribute
¶
rows_modified = field(default_factory=list)
class-attribute
instance-attribute
¶
rows_removed = field(default_factory=list)
class-attribute
instance-attribute
¶
shape_changed
property
¶
summary
property
¶
TextDiff
dataclass
¶
Bases: Diff
added = 0
class-attribute
instance-attribute
¶
hunks = 0
class-attribute
instance-attribute
¶
kind = 'text'
class-attribute
instance-attribute
¶
new_text = ''
class-attribute
instance-attribute
¶
old_text = ''
class-attribute
instance-attribute
¶
removed = 0
class-attribute
instance-attribute
¶
similarity = 1.0
class-attribute
instance-attribute
¶
summary
property
¶
unified = ''
class-attribute
instance-attribute
¶
ValueDiff
dataclass
¶
diff_structured(old, new, **options)
¶
Diff two nested dict/list values into the changes needed to turn
old into new: keys added and removed, list items inserted and
deleted, and leaf values changed.
Custom strategies for structured documents can start from this and
relabel the changes, e.g. ("nodes", "sales") added as "Node 'sales' added".
diff_table(old, new, key=None, **options)
¶
Diff two DataFrames.
Rows are aligned on key columns if given, otherwise on the index
when it is unique in both frames, otherwise by position when the row
counts match. Values are compared on the shared columns only.
diff_text(old, new, kind='text', context=3, **options)
¶
diff_values(old, new, **options)
¶
infer_kind(value)
¶
register_diff(*kinds)
¶
Register a diff strategy func(old, new, **options) -> Diff for the given kinds.
root_run_id(runs, run_id)
¶
The top-level run that run_id belongs to, following each run's
parent_run_id through runs, e.g. RunState.runs.
Approval policies¶
Declarative rules deciding which tool calls need human approval and who may give it.
A policy is independent of any agent framework: an adapter asks
requires_approval before a tool runs and can_decide before it
acts on a decision, and approval components use can_approve as their
permission hook.
ApprovalPolicy
¶
An ordered list of ApprovalRules; the first matching rule decides.
Strings are shorthand for a rule requiring approval for every call to that tool. Calls matching no rule need no approval from the policy, though tools can still ask for it themselves.
policy = ApprovalPolicy([ ... "save_*", ... ApprovalRule("run_sql", when=lambda args: not args["sql"].lower().startswith("select")), ... ApprovalRule("publish", approvers={"admin"}), ... ]) policy.requires_approval("save_dashboard", {}) True
rules = [ApprovalRule(rule) if isinstance(rule, str) else rule for rule in rules]
instance-attribute
¶
can_approve(request, user)
¶
Whether user may decide request with its arguments; matches
the can_approve hook of ApprovalCard and ApprovalQueue.
Requests no rule matches, e.g. from tools asking for approval themselves, can be decided by anyone.
can_decide(request, user, args=None)
¶
Whether user may approve request with args, the final
arguments after any edits. Both the proposed and the final
arguments must allow the user, so editing a call cannot move it
out of the user's reach.
requires_approval(tool_name, args=None)
¶
Whether a call to tool_name with args must be approved before it runs.
rule_for(tool_name, args=None)
¶
The first rule matching the call, if any.
ApprovalRule
dataclass
¶
Requires approval for calls to the tools matching tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
str
|
Tool name, or a glob pattern such as |
required |
when
|
Callable[[dict[str, Any]], bool] | None
|
Predicate on the call arguments, with defaults filled in; the rule only applies to calls for which it returns True. None applies it to every call. A predicate that raises counts as True, so a broken predicate asks for approval rather than letting the call through. |
None
|
approvers
|
_Approvers | None
|
Who may decide: a collection of user names, or a callable
|
None
|
labels
|
Mapping[str, str] | None
|
Wording of the decision actions on the approval card, queue and
tool-call badge, e.g. |
None
|
approvers = None
class-attribute
instance-attribute
¶
labels = None
class-attribute
instance-attribute
¶
tool
instance-attribute
¶
when = None
class-attribute
instance-attribute
¶
matches(tool_name, args=None)
¶
Whether a call to tool_name with args needs approval under this rule.
permits(request, user)
¶
Whether user may approve or deny request.
Actions¶
Actions on the user interface that an agent can take on the user's behalf.
A host app registers the things a user can do in it, such as navigating,
selecting or filtering, as typed functions on an ActionRegistry. The
registry derives a JSON schema from each signature, so the same actions
can be listed in a command palette, exposed to an agent as tools or
served over MCP without the descriptions drifting apart. Actions always
run in the Panel session that created the registry.
Action
dataclass
¶
A named, typed function the user, a command palette or an agent can
invoke. parameters is the JSON schema of its arguments, derived
from the function's signature and docstring.
description
instance-attribute
¶
function
instance-attribute
¶
name
instance-attribute
¶
parameters = field(init=False, repr=False)
class-attribute
instance-attribute
¶
from_function(function, name=None, description=None)
classmethod
¶
An action named after function and described by its docstring unless given.
validate(args=None)
¶
Validate args against the signature, returning the keyword arguments to call with.
validate_json(data)
¶
ActionRegistry
¶
Bases: Parameterized
The actions a host app offers in one user session.
Create it inside the session, e.g. while building the page, so actions invoked from elsewhere (a tool running in another thread, an MCP request) still run in the user's session and update the page they are looking at. Calls from outside the session's event loop are handed to it through the document's next-tick callback, which also holds the document lock, so sync actions block that session while they run. Once the session is destroyed, invoking raises.
actions = ActionRegistry() @actions.action ... def open_page(path: str) -> str: ... '''Navigate to a page of the app.''' ... return f"Opened {path}"
actions = param.Dict(default={}, constant=True, doc='\n Mapping of action name to Action, in registration order.')
class-attribute
instance-attribute
¶
action(function=None, *, name=None, description=None)
¶
Decorator registering a function as an action, with or without arguments.
add(function, *, name=None, description=None)
¶
Register function as an action, replacing any action of the same name.
invoke(name, args=None)
async
¶
Validate args and run the action in the registry's session,
returning its result. Coroutine functions are awaited.
remove(name)
¶
Unregister an action.
Recording¶
Record runs as JSON Lines and load them back for replay.
Each line is one event. Values that are not JSON serializable are encoded by a registered codec so they round-trip, e.g. DataFrames come back as DataFrames and can be rendered by the same components.
Recorders write to a sink: a file path, a text stream, or a callable that receives each record as the JSON-ready dict a line would hold, so a host can store recordings in its own database. Loaders read a path or any iterable of those dicts.
FORMAT_VERSION = 1
module-attribute
¶
Codec
dataclass
¶
HistoryRecorder
¶
Bases: Recorder
Record the version history of artifacts, e.g. to keep a document's history across sessions.
Writes the ArtifactPublished, ArtifactApplied and
ArtifactVersionsDropped events of the
artifacts in artifact_ids (default: all) and, for each run that
published one of those versions, its RunStarted before the first
such version, after those of the runs it is a child of, and its
RunFinished or RunError, so the history keeps its grouping
by run and the runs' inputs. Messages, tool calls
and runs that published nothing are left out. sink and
on_error work as for Recorder; load_history restores
what it wrote.
artifact_ids = None if artifact_ids is None else set(artifact_ids)
instance-attribute
¶
Recorder
¶
Record every event applied to a RunState.
sink is a JSON Lines file to append to, a text stream, or a
callable receiving a copy of each record as the JSON-ready dict a line
would hold: first the format record, then one per event. A callable
runs synchronously on the event loop, so one that stores records
slowly blocks the app and should hand them to a queue or thread.
load_events and load_state read either back. path is a
deprecated name for sink.
A failing sink is logged with its traceback and the run goes on;
pass on_error="raise" to let the error propagate instead.
Usable as a context manager; close detaches it from the state.
dump_events(events, path)
¶
Write events to a JSON Lines recording, starting with the format version.
load_events(source=None, *, path=None)
¶
Read the events of a recording from a JSON Lines file or from the
records a callable sink received. Recordings without a format line,
written before it existed, are read as version 1. A recording from a
newer format version raises ValueError. path is a deprecated
name for source.
load_history(source, state=None)
¶
Restore a history written by HistoryRecorder (or any recording)
into state, or into a new RunState, and return the state.
The events are applied without notifying the state's subscribers, so
a recorder attached to it does not write them again and an
AgentRunner does not report them to the model as new versions. A
run that the stored session never finished is finished, since it can
no longer continue.
load_state(source=None, *, path=None, **params)
¶
Replay a recording into a new RunState. path is a deprecated name for source.
register_codec(codec, first=True)
¶
Register a codec; codecs registered later take precedence by default.
Audit log¶
Audit trail of human approval decisions.
AuditLog subscribes to a RunState and writes one record per
ApprovalResolved event to a sink: a JSON Lines file or any callable.
It depends on neither Panel nor an agent framework.
AuditLog
¶
Records every approval decision made on one or more RunStates.
Each record holds the timestamp (epoch seconds and ISO 8601 UTC),
run id, tool call id, tool name, the original and final arguments,
the decision, whether the arguments were edited, the reason and the
user. Records are also kept in memory on records.
include_existing records the decisions among state.events; on
a state whose max_events dropped earlier events it warns that
decisions may be missing.
log = AuditLog(state, "approvals.jsonl")
close = detach
class-attribute
instance-attribute
¶
records = []
instance-attribute
¶
sink = sink
instance-attribute
¶
attach(state, include_existing=False)
¶
Start recording decisions on state. With include_existing,
decisions already applied (e.g. from a loaded recording) are
recorded too, and a warning says when max_events dropped some.
detach(state=None)
¶
Stop recording state, or every attached state.
read(path)
staticmethod
¶
Read the records of a JSON Lines audit file.
write(record)
¶
Security¶
Rendering untrusted text safely.
Model replies, thinking, tool results, artifacts, tool descriptions and decision reasons can contain text an attacker controls, e.g. through a prompt injected into a document the agent read. Rendered as ordinary Markdown, such text can load remote images (sending data out in their URL with no click), run script through raw HTML, or abuse MathJax.
inert_markdown is a markdown-it plugin that works on the parsed
tokens, the same ones that are rendered, so nothing in the source can
sneak past it: raw HTML is shown as text, images become links unless
their origin is trusted, links are limited to http, https and mailto and
show their full URL. untrusted_markdown builds a Markdown pane with
the plugin and with math disabled.
inert_markdown(md)
¶
markdown-it plugin making untrusted Markdown inert: raw HTML renders as text, images not from a trusted origin become links labelled "image: ...", links other than http, https, mailto or relative ones are dropped, and every link shows its full URL after its text. Code blocks are escaped even when the highlighter fails.
Use it with math disabled, e.g. pn.pane.Markdown(text,
plugins=[inert_markdown], disable_math=True), or through
untrusted_markdown.
set_trusted_image_origins(origins)
¶
Allow images in rendered agent output to load from origins, e.g.
["https://tiles.example.com"]. "*" allows every origin. Every
other image is shown as a link. Applies to the whole process.
trusted_image_origins()
¶
The origins images in agent output may load from.
untrusted_markdown(text='', **params)
¶
A Markdown pane rendering text with inert_markdown and without math.
pydantic-ai adapter¶
Drive a pydantic-ai agent and translate its run into panel-agents events.
AgentRunner streams a run through _PanelEventStream, a
pydantic_ai.ui.UIEventStream subclass, and applies every resulting
event to a RunState. A run-scoped capability reports per-response
usage and resolves tool approvals inline, so a run that pauses for a
human decision stays one run in the UI.
Tools publish artifacts either by awaiting publish_artifact(ctx, ...)
or by returning artifact_return(...), which shows the model a short
summary while the UI receives the full value.
ActionToolset
¶
Bases: AbstractToolset[Any]
Exposes the actions of an ActionRegistry as pydantic-ai tools.
Each tool has the action's name, description and JSON schema, and runs the action in the registry's Panel session. Actions registered or removed during a session are picked up on the next model request. An exception raised by an action is reported to the model as a failed tool call instead of ending the run.
AgentRunner
¶
Bases: Parameterized
Run a pydantic-ai agent and mirror the run into a RunState.
Each call to run adds the prompt as a user message, streams the
run into the state and keeps the message history so the next call
continues the conversation. Tool calls that need approval pause
the run until every pending request is resolved through
RunState.resolve_approval; the run then continues as the same
run. Tool calls deferred for external execution (CallDeferred)
end the run with DeferredToolRequests as its output, which
requires the agent's output_type to include it; continue with
run(deferred_tool_results=...).
Must be awaited on the event loop that owns the state, e.g. from a Panel callback.
agent = param.Parameter(doc='The pydantic-ai Agent to run.')
class-attribute
instance-attribute
¶
approval_policy = param.ClassSelector(class_=ApprovalPolicy, default=None, allow_None=True, doc='\n Rules deciding which tool calls need approval and who may give\n it. Applies to every tool the agent can call during a run.')
class-attribute
instance-attribute
¶
deferred = param.Parameter(default=None, constant=True, doc='\n DeferredToolRequests the last run ended with, if any.')
class-attribute
instance-attribute
¶
deps = param.Parameter(default=None, doc='Dependencies passed to every run.')
class-attribute
instance-attribute
¶
error = param.Parameter(default=None, constant=True, doc='Exception raised by the last run, if any.')
class-attribute
instance-attribute
¶
messages = param.List(default=[], doc='Message history carried across runs.')
class-attribute
instance-attribute
¶
model = param.Parameter(default=None, doc='\n The model the next run uses instead of the agent\'s own: a\n pydantic-ai model string such as ``"openai:gpt-5"`` or a model\n object, or None for the agent\'s model. It is read when a run\n starts, so changing it never affects a run in progress. A ``model``\n given in ``run_kwargs`` or to ``run``, e.g. a ``Cassette``, takes\n precedence. A run that pauses for an approval keeps its model; one\n continued with ``deferred_tool_results`` is a new call to ``run`` and\n uses the model set by then. ``ModelPicker`` sets it.')
class-attribute
instance-attribute
¶
raise_errors = param.Boolean(default=False, doc='\n Whether exceptions raised by a run propagate out of ``run`` after\n the RunError event is applied. When False, ``run`` returns None\n and the exception is available as ``error``. Either way a failed\n run is logged with its traceback and shows as an error message in\n the timeline.')
class-attribute
instance-attribute
¶
run_id = param.String(default=None, allow_None=True, constant=True, doc='Id of the current or last run.')
class-attribute
instance-attribute
¶
run_kwargs = param.Dict(default={}, doc='Extra keyword arguments passed to ``Agent.run_stream_events``.')
class-attribute
instance-attribute
¶
running = param.Boolean(default=False, constant=True)
class-attribute
instance-attribute
¶
state = param.ClassSelector(class_=RunState, doc='RunState the run is applied to.')
class-attribute
instance-attribute
¶
thread_id = param.String(default=None, allow_None=True, doc='Thread id recorded on each run.')
class-attribute
instance-attribute
¶
cancel()
¶
Cancel the current run; it ends with a RunError coded cancelled.
clear()
¶
Forget the message history so the next run starts a new conversation.
close()
¶
run(prompt=None, *, deferred_tool_results=None, **kwargs)
async
¶
Run the agent on prompt and return its output.
Keyword arguments are passed to Agent.run_stream_events. A
run_id given here becomes the id of the run in the state as well
as in pydantic-ai's messages; by default a new one is generated.
unavailable_reason(model)
¶
Why model cannot be used, or None if it can.
A model string is resolved the way pydantic-ai resolves it when a run starts, which fails when the provider's package or API key is missing or the model is unknown. A missing key is named in a short sentence, e.g. "Set OPENAI_API_KEY to use this model"; otherwise the reason is the error's first line without an installation hint after a dash. It never holds a key's value; the full error is logged at debug level. Model objects are assumed usable.
Cassette
¶
Bases: FunctionModel
A model that answers with the responses of a recorded message history, in order.
Pass it as the agent's model, e.g. AgentRunner(agent, run_kwargs={"model":
Cassette.from_trace(path)}), or with agent.override(model=...).
Streamed and non-streamed runs are both supported. Played responses
keep their recorded parts, model name and usage, but take the run and
conversation ids of the playback.
Every tool result, user prompt and output retry the agent sends is
compared with the recording; differences are collected in
divergences, or raised as CassetteError with strict=True.
check_fingerprint compares the instructions and tools offered with
the fingerprint stored on each recorded response by AgentRunner, so
a cassette recorded against another version of the agent fails instead
of passing silently; turn it off for agents whose instructions change
from run to run.
check_fingerprint = check_fingerprint
instance-attribute
¶
divergences = []
instance-attribute
¶
messages = list(messages)
instance-attribute
¶
played = 0
instance-attribute
¶
remaining
property
¶
How many recorded calls, responses and failures, have not been played yet.
responses
property
¶
The recorded responses, in the order they are played; a recorded failure is not one.
strict = strict
instance-attribute
¶
from_trace(source, **kwargs)
classmethod
¶
Play back every model call a trace written by ModelTraceRecorder
recorded, once each and in the order they were made, each with its
response as first written and compared with the requests as first
sent. That holds when the recorded agent rewrote its history, e.g.
with a history processor that shortens earlier tool results,
rewrites earlier responses or keeps only the last messages, and
after AgentRunner.clear(). messages is the history the trace
ends with.
A request that failed, e.g. because the provider refused it, raises
RecordedFailure with the recorded error where playback reaches
it, so the run fails as it did; a tool that raised does so again on
its own. A trace whose responses carry no request id, written by an
earlier panel-agents, is played as the history it ends with.
request(messages, model_settings, model_request_parameters)
async
¶
request_stream(messages, model_settings, model_request_parameters, run_context=None)
async
¶
CassetteError
¶
Bases: RuntimeError
Playback cannot continue: the agent no longer matches the recording.
Divergence
dataclass
¶
A difference between what the agent sent the model and what was recorded.
actual
instance-attribute
¶
expected
instance-attribute
¶
kind
instance-attribute
¶
"tool_return", "prompt", "retry" or "fingerprint".
request
instance-attribute
¶
The 1-based number of the model request it was found in.
tool_call_id = None
class-attribute
instance-attribute
¶
tool_name = None
class-attribute
instance-attribute
¶
ModelRequestSummary
dataclass
¶
One request to a model, as summarized by load_model_calls.
attempt_of = None
class-attribute
instance-attribute
¶
For a failed attempt that a retry or fallback recovered from, the request id of its request.
cached_tokens = 0
class-attribute
instance-attribute
¶
cost_usd = None
class-attribute
instance-attribute
¶
duration = None
class-attribute
instance-attribute
¶
Wall-clock seconds the request took, if recorded.
error = None
class-attribute
instance-attribute
¶
Why the request failed, "Interrupted" for a response cut off by a cancelled run, None if it succeeded.
finish_reason = None
class-attribute
instance-attribute
¶
input_tokens = 0
class-attribute
instance-attribute
¶
model
instance-attribute
¶
output_tokens = 0
class-attribute
instance-attribute
¶
provider_response_id = None
class-attribute
instance-attribute
¶
request_id = None
class-attribute
instance-attribute
¶
The id AgentRunner gave the request, as on its ModelRequestStarted and Usage events.
run_id
instance-attribute
¶
timestamp = None
class-attribute
instance-attribute
¶
tool_calls = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
The (tool_name, tool_call_id) of each tool call in the response.
ModelTraceRecorder
¶
Record the message history of an AgentRunner.
sink is a JSON Lines file to append to, a text stream, or a
callable receiving a copy of each record as the JSON-ready dict a line
would hold, with redaction already applied. A callable runs
synchronously on the event loop, so one that stores records slowly
blocks the app and should hand them to a queue or thread.
The history is synchronized with the file at the start of every model
request, before the tools of a response run and when a run ends, so a
response is on disk before the tools it called run. Runs of the same
conversation append to the same file. When the runner's history no
longer extends what the file holds, e.g. after a history processor
rewrote it, AgentRunner.clear() or a run that failed, the
recorder writes a rewind record and the history from there on,
so load_messages always returns what the runner holds.
Attaching writes the runner's current history: to an existing file
only where it differs from the conversation the file ends with, so
runner.messages = load_messages(path) followed by a recorder on
the same file only appends. A stream or callable cannot be read back,
so the recorder starts it over with a rewind to 0 and the full
history.
A failing sink is logged with its traceback and the agent run goes
on. The recorder then forgets what it wrote and, at the next sync the
sink accepts, starts over with a rewind to 0 and the full history,
so the store heals itself. Pass on_error="raise" to let the error
propagate into the run instead.
Pass include_content=False to drop prompts, instructions, text,
thinking, tool arguments and results and error messages, keeping the
parts, tool names, ids and outcomes, the usage and the timing.
Usable as a context manager; close detaches it from the runner.
RecordedFailure
¶
Bases: RuntimeError
A recorded model request that failed, raised again where playback
reaches it. Its message is the error as the trace holds it, prefixed
with the exception type, e.g. "RuntimeError: provider refused".
It is not a CassetteError: the playback reproduced the recording.
artifact_return(return_value, artifact_id, value, *, title=None, kind=None, metadata=None, applied=False)
¶
Return return_value to the model and publish value as an artifact.
Works from sync and async tools. The artifact travels in the tool
return's metadata, which pydantic-ai never sends to the model. See
publish_artifact for applied.
fingerprint(model_request_parameters, messages=())
¶
A short hash of what the model was offered: the instructions, any
system prompts in messages and the name, description and JSON
schema of each function tool.
AgentRunner stores it on every response it records, and a
Cassette compares it with the agent it plays back to, so a
recording made against other instructions or tools is detected.
Instructions that change from run to run, e.g. ones including the
date, change the fingerprint too.
load_messages(source, *, include_failed=False)
¶
Read the message history of a model trace as pydantic-ai messages, from a JSON Lines file or the records a callable sink received.
The result is the history the recorded AgentRunner held, so
assigning it to AgentRunner.messages continues the conversation
where it was. With include_failed, the messages of a failed run,
which the runner does not keep, are kept. A trace recorded with
include_content=False loads, but has no content to continue from.
load_model_calls(source)
¶
Summarize every model request in a model trace, in order: the model, run, tool calls, tokens, cost, duration and, for failed requests, the error. Failed attempts that a later attempt recovered from come before the response they belong to, and requests that ended a run follow the run's last response. Responses that a rewind dropped from the history are still counted, once.
merge_model_calls(events, calls)
¶
Add the model calls of a model trace to the events of a conversation
recording, e.g. merge_model_calls(load_events(path), load_model_calls(trace)).
Each call becomes a ModelRequestStarted and a Usage event,
placed in its run where AgentRunner emits them today, so
RunState.from_events on the result shows every request in the
timeline with its tool calls, including failed ones; failed attempts
that a retry recovered from are attached to their request. Calls are
matched to runs by run_id. Runs the recording does not hold, and
runs it already holds model calls for, are left alone. The
recording's own Usage events without a request id are replaced by
the calls they report, so run totals are not counted twice.
publish_artifact(ctx, artifact_id, value, *, title=None, kind=None, metadata=None, applied=False)
async
¶
Publish a new version of an artifact from inside an async tool.
The event is stamped with the calling tool's tool_call_id and
reaches the UI in stream order, before the tool's result. Pass
applied=True when the tool edited a host document in place and
value is what the document now holds.
Model traces¶
Record the model calls of an AgentRunner as JSON Lines and load them back.
The model trace is pydantic-ai's own message history. After a header
line, each line is one ModelMessage in the format of
ModelMessagesTypeAdapter, or one of two kinds of record:
{"rewind": n}says the history was rewritten, e.g. by a history processor,AgentRunner.clear()or a failed run whose messages do not join the conversation, and keeps only its firstnmessages; the messages that follow continue from there.{"failed_run": run_id, "error": ..., "request": ...}says a run failed, with the model request that was in flight, if any.
AgentRunner stamps every ModelResponse with the wall-clock
duration of its request and a fingerprint of the instructions and tools
the model was offered, under metadata["panel_agents"].
load_messages applies the rewinds and returns the history the
runner holds, e.g. to continue the conversation with
runner.messages = load_messages(path). load_model_calls
summarizes every model request that was ever recorded.
Like the event Recorder, ModelTraceRecorder writes to a file, a
text stream or a callable receiving each record as a dict, and the
loaders read a file or an iterable of those dicts.
FORMAT_VERSION = 1
module-attribute
¶
ModelRequestSummary
dataclass
¶
One request to a model, as summarized by load_model_calls.
attempt_of = None
class-attribute
instance-attribute
¶
For a failed attempt that a retry or fallback recovered from, the request id of its request.
cached_tokens = 0
class-attribute
instance-attribute
¶
cost_usd = None
class-attribute
instance-attribute
¶
duration = None
class-attribute
instance-attribute
¶
Wall-clock seconds the request took, if recorded.
error = None
class-attribute
instance-attribute
¶
Why the request failed, "Interrupted" for a response cut off by a cancelled run, None if it succeeded.
finish_reason = None
class-attribute
instance-attribute
¶
input_tokens = 0
class-attribute
instance-attribute
¶
model
instance-attribute
¶
output_tokens = 0
class-attribute
instance-attribute
¶
provider_response_id = None
class-attribute
instance-attribute
¶
request_id = None
class-attribute
instance-attribute
¶
The id AgentRunner gave the request, as on its ModelRequestStarted and Usage events.
run_id
instance-attribute
¶
timestamp = None
class-attribute
instance-attribute
¶
tool_calls = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
The (tool_name, tool_call_id) of each tool call in the response.
ModelTraceRecorder
¶
Record the message history of an AgentRunner.
sink is a JSON Lines file to append to, a text stream, or a
callable receiving a copy of each record as the JSON-ready dict a line
would hold, with redaction already applied. A callable runs
synchronously on the event loop, so one that stores records slowly
blocks the app and should hand them to a queue or thread.
The history is synchronized with the file at the start of every model
request, before the tools of a response run and when a run ends, so a
response is on disk before the tools it called run. Runs of the same
conversation append to the same file. When the runner's history no
longer extends what the file holds, e.g. after a history processor
rewrote it, AgentRunner.clear() or a run that failed, the
recorder writes a rewind record and the history from there on,
so load_messages always returns what the runner holds.
Attaching writes the runner's current history: to an existing file
only where it differs from the conversation the file ends with, so
runner.messages = load_messages(path) followed by a recorder on
the same file only appends. A stream or callable cannot be read back,
so the recorder starts it over with a rewind to 0 and the full
history.
A failing sink is logged with its traceback and the agent run goes
on. The recorder then forgets what it wrote and, at the next sync the
sink accepts, starts over with a rewind to 0 and the full history,
so the store heals itself. Pass on_error="raise" to let the error
propagate into the run instead.
Pass include_content=False to drop prompts, instructions, text,
thinking, tool arguments and results and error messages, keeping the
parts, tool names, ids and outcomes, the usage and the timing.
Usable as a context manager; close detaches it from the runner.
fingerprint(model_request_parameters, messages=())
¶
A short hash of what the model was offered: the instructions, any
system prompts in messages and the name, description and JSON
schema of each function tool.
AgentRunner stores it on every response it records, and a
Cassette compares it with the agent it plays back to, so a
recording made against other instructions or tools is detected.
Instructions that change from run to run, e.g. ones including the
date, change the fingerprint too.
load_messages(source, *, include_failed=False)
¶
Read the message history of a model trace as pydantic-ai messages, from a JSON Lines file or the records a callable sink received.
The result is the history the recorded AgentRunner held, so
assigning it to AgentRunner.messages continues the conversation
where it was. With include_failed, the messages of a failed run,
which the runner does not keep, are kept. A trace recorded with
include_content=False loads, but has no content to continue from.
load_model_calls(source)
¶
Summarize every model request in a model trace, in order: the model, run, tool calls, tokens, cost, duration and, for failed requests, the error. Failed attempts that a later attempt recovered from come before the response they belong to, and requests that ended a run follow the run's last response. Responses that a rewind dropped from the history are still counted, once.
merge_model_calls(events, calls)
¶
Add the model calls of a model trace to the events of a conversation
recording, e.g. merge_model_calls(load_events(path), load_model_calls(trace)).
Each call becomes a ModelRequestStarted and a Usage event,
placed in its run where AgentRunner emits them today, so
RunState.from_events on the result shows every request in the
timeline with its tool calls, including failed ones; failed attempts
that a retry recovered from are attached to their request. Calls are
matched to runs by run_id. Runs the recording does not hold, and
runs it already holds model calls for, are left alone. The
recording's own Usage events without a request id are replaced by
the calls they report, so run totals are not counted twice.
Cassettes¶
Play a recorded model trace back to an agent instead of calling a model.
A Cassette is a pydantic-ai FunctionModel that answers each
model request with the next recorded ModelResponse. The agent loop,
its tools, approvals and the UI run for real with no provider call,
which makes recorded sessions usable as fast, offline tests: a tool
refactor must produce the same tool results, and a UI change can be
driven through a full agent run without an API key.
The cassette compares what the agent sends back with the recording and
collects every difference as a Divergence. It raises
CassetteError when a recorded response calls a tool the agent no
longer offers, when the agent asks for more responses than were
recorded and, by default, when the instructions or tools differ from
the ones the recording was made with.
Cassette
¶
Bases: FunctionModel
A model that answers with the responses of a recorded message history, in order.
Pass it as the agent's model, e.g. AgentRunner(agent, run_kwargs={"model":
Cassette.from_trace(path)}), or with agent.override(model=...).
Streamed and non-streamed runs are both supported. Played responses
keep their recorded parts, model name and usage, but take the run and
conversation ids of the playback.
Every tool result, user prompt and output retry the agent sends is
compared with the recording; differences are collected in
divergences, or raised as CassetteError with strict=True.
check_fingerprint compares the instructions and tools offered with
the fingerprint stored on each recorded response by AgentRunner, so
a cassette recorded against another version of the agent fails instead
of passing silently; turn it off for agents whose instructions change
from run to run.
check_fingerprint = check_fingerprint
instance-attribute
¶
divergences = []
instance-attribute
¶
messages = list(messages)
instance-attribute
¶
played = 0
instance-attribute
¶
remaining
property
¶
How many recorded calls, responses and failures, have not been played yet.
responses
property
¶
The recorded responses, in the order they are played; a recorded failure is not one.
strict = strict
instance-attribute
¶
from_trace(source, **kwargs)
classmethod
¶
Play back every model call a trace written by ModelTraceRecorder
recorded, once each and in the order they were made, each with its
response as first written and compared with the requests as first
sent. That holds when the recorded agent rewrote its history, e.g.
with a history processor that shortens earlier tool results,
rewrites earlier responses or keeps only the last messages, and
after AgentRunner.clear(). messages is the history the trace
ends with.
A request that failed, e.g. because the provider refused it, raises
RecordedFailure with the recorded error where playback reaches
it, so the run fails as it did; a tool that raised does so again on
its own. A trace whose responses carry no request id, written by an
earlier panel-agents, is played as the history it ends with.
request(messages, model_settings, model_request_parameters)
async
¶
request_stream(messages, model_settings, model_request_parameters, run_context=None)
async
¶
CassetteError
¶
Bases: RuntimeError
Playback cannot continue: the agent no longer matches the recording.
Divergence
dataclass
¶
A difference between what the agent sent the model and what was recorded.
actual
instance-attribute
¶
expected
instance-attribute
¶
kind
instance-attribute
¶
"tool_return", "prompt", "retry" or "fingerprint".
request
instance-attribute
¶
The 1-based number of the model request it was found in.
tool_call_id = None
class-attribute
instance-attribute
¶
tool_name = None
class-attribute
instance-attribute
¶
RecordedFailure
¶
Bases: RuntimeError
A recorded model request that failed, raised again where playback
reaches it. Its message is the error as the trace holds it, prefixed
with the exception type, e.g. "RuntimeError: provider refused".
It is not a CassetteError: the playback reproduced the recording.
MCP¶
Serve an agent's tools over the Model Context Protocol.
create_server turns a pydantic-ai agent, toolset or an
ActionRegistry into a FastMCP server whose tools have the same names,
descriptions and argument schemas the agent sees. Each call runs through
pydantic-ai, so arguments are validated and the approval policy applies;
approvals are requested from the MCP client through elicitation, and
rules that restrict approvers need an authenticated caller.
Requires the mcp extra: pip install panel-agents[mcp].
create_server(source, *, deps=None, deps_factory=None, name=None, instructions=None, approval_policy=None, user=None, approval_secret=None)
async
¶
Create a FastMCP server exposing the tools of source.
The tools are listed when the server is created. Run the server with
server.run() (stdio) or server.run(transport="http"), or
mount server.http_app() in an ASGI app, behind authentication if
it is reachable by anyone but the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Agent[Any, Any] | AbstractToolset[Any] | ActionRegistry | Any
|
An |
required |
deps
|
Any
|
Dependencies passed to tools as |
None
|
deps_factory
|
Callable[[Context | None], Any] | None
|
Callable building the dependencies for each request from the
FastMCP |
None
|
name
|
str | None
|
Server name and instructions shown to MCP clients. The name defaults to the agent's name. |
None
|
instructions
|
str | None
|
Server name and instructions shown to MCP clients. The name defaults to the agent's name. |
None
|
approval_policy
|
ApprovalPolicy | None
|
Rules deciding which calls need approval, which is requested from the client through MCP elicitation. Tools that ask for approval themselves are covered too. A declined or impossible approval returns an error to the client. |
None
|
user
|
Callable[[Context | None], str | None] | None
|
Callable resolving the caller's user name from the FastMCP
|
None
|
approval_secret
|
bytes | None
|
Key signing the request state that binds an approval to its call,
caller and time. Defaults to the |
None
|