API reference¶
This page lists the public API of panel-agents. Every name below is covered by semantic versioning. Every public version reference is a version number counting from 1, as in the v1, v2 labels users see. Anything else, including names and modules that start with an underscore, is private. Classes built on param expose their configuration as parameters, documented in their docstrings and listed with Class.param.
panel_agents¶
Components¶
| Name | Purpose |
|---|---|
AgentChat(state=None, *, runner, callback, readonly, add_user_message, approval_factory, can_approve, user, assistant, placeholder, avatars, tool_labels, group_tool_calls, show_model_calls, show_usage, on_show_run, layout, user_placement, message_params, inline_artifacts, cell_renderer, action_registry, artifact_actions, max_cells, feed_params, models, model_id, remember_model, mentions) |
Chat feed of a RunState with streaming messages, thinking steps, model-call and tool-call cards and an error alert for a failed run; tool_labels names calls in the user's words and group_tool_calls folds runs of finished calls and model requests into one row. show_model_calls shows model requests as steps and show_usage a finished run's requests, tokens, cost and wall time under its last message, with a "Details" link calling on_show_run(run_id) when that is set. submit(text) sends text as the user would, feed is the panel-material-ui ChatFeed (a ChatInterface unless readonly) and view_for(item) the component showing a timeline item. models adds a ModelPicker below the input (model_picker). mentions shows Mentions as removable chips in the input, which sending a message writes at its start and clears. avatars maps a name shown in the feed to its avatar. user_placement puts the user's messages on the left or right, and message_params are given to every ChatMessage (the chat keeps deciding visible); changing either builds the messages again. With layout="document" every message sits on the left and the artifacts a run published render inline as ArtifactCells in a row after the run's messages, where they stay as more are appended; past max_cells the rest wait behind a "Show more" button. inline_artifacts(artifact) chooses them (default: those that are not documents; their calls then need no chip and fold into step groups), cell_renderer(artifact) renders their body, and artifact_actions run through action_registry. cells maps artifact ids to the cells built and refresh_actions() re-evaluates their actions. |
ArtifactCell(artifact, *, renderer, actions, artifact_actions) |
A card with an artifact's kind, title (as plain text, in monospace when it is a name), actions that wrap below the title on a narrow card, and latest value, rendered again when a version is published; a renderer that raises shows its error in the card. refresh() re-evaluates the actions and release() stops following the artifact. |
ArtifactAction(action, label, icon=None, arguments=..., done=None) |
A button on artifact cells that runs action from an ActionRegistry with arguments(artifact), hidden when that returns None and evaluated again at the click; done(artifact) returns a label shown instead once there is nothing left to do. |
AgentDrawer(runner=None, *, state, main, open, width, resizable, min_resize_width, max_resize_ratio, title, variant, overlay_below, tab, show_artifacts, show_approvals, open_on_approval, can_approve, on_apply, chat_params, redact_runs) |
A right-hand drawer with the chat, artifacts and approvals, docked beside main. toggle (with aria-expanded and the pending count in its accessible name), content, chat, artifacts, approvals, new_conversation(), show_run(run_id, *, redacted=None) (a dialog with the run's SpanView, also opened from the chat's "Details" links and the history's "How was this made?"). redact_runs, a boolean or a callable of the run id, decides which runs it shows redacted. |
Mention(label, icon=None, text=None) |
Something a person's next message is about, set in AgentChat.mentions: a chip with label and icon in the input, written into the sent message as text, by default @ and the label, quoted unless it is made of letters, digits and _ . - / : only (written); mentions writing the same name show as one chip, and an empty label raises ValueError. |
ModelPicker(*, models, value, runner, remember, label) / ModelChoice(id, label=None, description=None, model=None) |
A compact menu button of the models a runner may use; with a single model it shows that model's name as read-only text with its id as a tooltip, and with none it is hidden. It sets runner.model, lists each model's description and, for models runner.unavailable_reason refuses, the reason under its label (unavailable holds them), tells models that share a label apart by id, and with remember keeps the pick in the browser's localStorage. Its accessible name is label ("Model"), and choices holds the ModelChoices it offers. ModelChoice.coerce(spec) makes one from an id, a dict or a ModelChoice; name is the label or the id, and target what the runner is given (model if set, else id). |
ApprovalCard(request=None, state=None, *, can_approve, policy_message, require_reason, user, editing, labels) |
Review card for one tool call: edit arguments, approve or deny. labels changes the wording of the actions, e.g. {"deny": "Remove", "denied": "Removed"}; a changed verb needs its past tense, and a request's own labels take precedence. approve(), deny(), form, permitted, is_edited, resolved_labels. |
ApprovalQueue(state, *, can_approve, require_reason, user, show_resolved, title, card_factory, labels) |
The pending approvals of a state as cards. labels is passed to each card and names the batch actions, unless all pending requests share labels of their own. approve_all(), deny_all(), cards, batch_labels. |
ArtifactPane(store=None, *, state, on_apply, on_show_run, show_list, list_width, empty_message, view_options) |
Lists a store's artifacts and shows the active one. views, active_view. |
ArtifactView(artifact, *, mode, base, target, diff_layout, diff_options, show_header, on_apply, on_show_run, state, user, history) |
One artifact with a version history grouped by run, compare, metadata and apply/revert for documents; with on_show_run the history's runs offer "How was this made?". show_version(number) opens the history at a version. base and target are version numbers; history opens the history (None: open for documents). await apply_version(version=None, *, action=None), await undo(), await redo(), await undo_run(run_id=None), await redo_run(run_id=None), can_undo, can_redo, compute_diff(). |
ModelCallCard(call, *, state, collapsed, show_tool_count, redacted) |
Card for one model request: model, input and output tokens, cost and latency in the header, the cached tokens and their share, finish reason, response, request and run ids, the tool calls it issued and any error in the body. |
RunTrace(state, *, run_id, show_totals, include_children, redacted, row_limit) |
Every step of one run, unfolded: model requests with the tool calls they issued nested under them, a bar per step on the run's time axis, and the run's totals on top. Readonly; follows a run in progress until release(). include_children adds the steps and totals of child runs under a label naming each; row_limit builds that many steps with a button for more. |
SpanView(state, *, run_id, redacted, row_limit, on_artifact) |
How one run was made: its question, totals with the cached share, steps (a RunTrace including child runs), the artifact versions it published and its problems. redacted=True hides the content and keeps the shape. Readonly; follows a run in progress until release(). |
SchemaForm(*, schema, value, live_validation, boolean_widget, disabled) |
A form of panel-material-ui widgets for a JSON Schema, with value kept in sync both ways: text, enums as selects, numbers with their bounds, switches, date and date-time pickers, enum arrays as multi-choice and nested objects as groups; anything else falls back to a JSON editor. validate() shows and returns the errors, valid, errors, field(path). It is the form ApprovalCard edits arguments with. |
ToolCallCard(call, *, state, approval_factory, show_artifact, max_chars, max_items, max_lines, collapsed, label, redacted) |
Card for one tool call with arguments, status, result and published artifacts (show_artifact(artifact) chooses which get a chip) (redacted=True leaves out the arguments, result, approval description and error message); label (a string or a callable of the arguments) replaces the tool name in the header. Structured and code-like results are shown as highlighted code blocks, cut to max_lines until expanded. |
register_renderer(func=None, *, kind=None, type=None, applies=None, priority=0) |
Register how values of an artifact kind, a type or a predicate are rendered; usable as a decorator. |
render_output(value, max_lines=30, **options), output_format(value) |
Render a tool result the way ToolCallCard does, and the classification behind it: output_format returns (format, content) with format "json", "yaml", "python", "pytb", "sql", "xml", "text", "table" or "object". Both live in panel_agents.components.renderers. |
State and events¶
| Name | Purpose |
|---|---|
RunState(*, max_events=None, flush_interval=0.05) |
Reactive store built from events; streamed deltas arriving within flush_interval seconds update the UI once. apply(event), apply_many(events, notify=True), subscribe(callback), reset(), flush(), from_events(events), events (the latest max_events of them when that is set; dropped_events counts the rest), add_user_message(content, run_id=None), resolve_approval(tool_call_id, approved, args=None, reason=None, user=None) (raises ValueError if already decided and PermissionError if the runner's policy does not allow user), publish_artifact(artifact_id, value, *, kind, title, metadata, applied=False, run_id=None, tool_call_id=None, actor=None, user=None) (who made the version defaults to the current run and tool call, or to the user), user_run(input=None, *, user=None, run_id=None) (a context manager grouping a person's edits into a run, yielding its id), apply_artifact_version(artifact_id, version, user=None, action=None) (action is "undo" or "redo" when applying undoes or redoes), undo(artifact_id, *, user=None, on_apply=None), redo(...), undo_run(artifact_id, run_id=None, *, user=None, on_apply=None) and redo_run(artifact_id, run_id=None, ...) (record the step as ArtifactApplied after a synchronous on_apply(artifact, version) agrees, and return the applied version or None), drop_artifact_versions(artifact_id, before) (drops the values of the versions numbered below before, except the applied one, keeping their numbers; returns the numbers dropped), span(run_id) (a RunSpan of everything the run and its child runs did; KeyError for an unknown run). |
current_run_id(), current_tool_call_id() |
The run and tool call the calling code executes in, set by AgentRunner and RunState.user_run; None outside them. Also in panel_agents.context. |
RunSpan, SpanError |
What RunState.span returns: run, runs (with child runs), question, steps ((item, depth) pairs, tool calls under the request that issued them), messages, model_calls, tool_calls, published ((artifact, version) pairs), errors (SpanError(kind, message, item), kind one of run, cancelled, model_call, attempt, tool_call, guardrail) and totals over the run and its child runs usage, requests, input_tokens, output_tokens, cached_tokens, cached_share, cost_usd, model_duration, models, and the run's wall time duration. A snapshot; call span again for later events. |
MessageState, ModelCallState, ToolCallState, ApprovalRequest, RunInfo |
The entities in a RunState, as parameterized objects components watch. RunState.items holds messages, model calls and tool calls in timeline order and RunState.model_calls maps request ids to ModelCallState. RunInfo.status is running, finished, error or cancelled (with the reason in error), and RunInfo totals its Usage events: requests, input_tokens, output_tokens, cached_tokens, cost_usd, model_duration, models and the wall-clock duration. |
events |
The event classes, see below. |
Recorder(state, sink, *, on_error="log"), dump_events(events, path), load_events(source), load_state(source) |
Record runs as JSON Lines, starting with a format version line, and load them back for replay. Recorder.close() stops recording, and a Recorder is also a context manager. A sink is a file path, a text stream or a callable receiving each record as a dict; a source is a file path or an iterable of those dicts. |
HistoryRecorder(state, sink, *, artifact_ids=None, on_error="log"), load_history(source, state=None) |
Record the versions of document artifacts with the runs that made them, and restore them into a state without notifying its subscribers. |
AuditLog(state=None, sink=None, include_existing=False) |
Writes one record per approval decision to a file or callable and keeps them in records. attach(state, include_existing=False), detach(state=None), close(), AuditLog.read(path). |
Artifacts, approvals and actions¶
| Name | Purpose |
|---|---|
Artifact, ArtifactVersion, ArtifactStore |
Versioned artifacts. ArtifactVersion records who made it as run_id, tool_call_id, actor ("agent", "user" or a host's own string) and user, and dropped once its value was dropped. Artifact.current is the number of the version shown, Artifact.undo_version, redo_version and redo_run_version the versions undo, redo and redo of a whole undo would apply, run_versions(run_id, runs=None), undo_run_target(run_id=None, runs=None) and redo_run_target(run_id=None, runs=None) resolve runs to versions and undo_run_blocked(run_id=None, runs=None) says whether a run is not undone because later edits outside it came after it, Artifact.is_document and Artifact.applied_version describe documents; ArtifactStore.publish(...), mark_applied(artifact_id, version) and published_by(tool_call_id), the artifacts a tool call published with the latest version it published of each. |
register_diff(*kinds) |
Register a diff strategy func(old, new, **options) -> Diff for artifact kinds. |
ApprovalPolicy(rules), ApprovalRule(tool, when=None, approvers=None, labels=None) |
Which tool calls need approval and who may give it. approvers is a collection of user names or a callable (request, user) -> bool. labels names the decision actions for the matching calls and is recorded on ApprovalRequested.labels and ApprovalRequest.labels. requires_approval(tool, args), can_approve(request, user), can_decide(request, user, args=None), rule_for(tool, args). |
ActionRegistry(), Action |
Typed front-end actions run in the user's session. action(...), add(func, *, name, description), remove(name), await invoke(name, args); Action(name, description, function), Action.from_function(function, name=None, description=None), parameters, validate(args). |
panel_agents.events¶
Event and its subclasses, mirroring AG-UI: RunStarted, RunFinished, RunError, StepStarted, StepFinished, TextMessageStart, TextMessageContent, TextMessageEnd, ThinkingStart, ThinkingContent, ThinkingEnd, ToolCallStart, ToolCallArgs, ToolCallEnd, ToolCallResult, StateSnapshot, StateDelta, Custom. The kit-specific events map onto AG-UI CUSTOM events: ArtifactPublished (with actor and user next to run_id and tool_call_id), ArtifactApplied (with action, "undo", "redo" or None), ArtifactVersionsDropped (with before), ApprovalRequested, ApprovalResolved, ModelRequestStarted, Usage and GuardrailFired. ModelRequestStarted(request_id, model) begins a model request and the Usage event with the same request_id completes it with its tokens, cost, duration, tool_call_ids, error, finish_reason and provider_response_id. A failed attempt that a retry recovered from is a Usage with attempt_of set to its request's id, listed in that request's ModelCallState.attempts. Each has to_dict() and Event.from_dict(data).
panel_agents.artifacts¶
The artifact model above, plus the diff API: diff(old, new, kind=None, **options), register_diff, the strategies diff_values, diff_text, diff_table and diff_structured, the results Diff, ValueDiff, TextDiff, TableDiff and StructuredDiff, Change(op, path, old=None, new=None, label=None) with path a tuple of keys and list positions and path_str for display, infer_kind(value) and root_run_id(runs, run_id), the top-level run a run belongs to.
panel_agents.components¶
The components above, plus render(value, kind=None, **options), which renders a value with the registered renderers, and approval_factory(request, state), the default AgentChat.approval_factory. panel_agents.components.approval.approval_labels(*layers) returns the full action wording (approve, deny, approved, denied, edit, approve_edited, approved_edited, approve_all, deny_all), resolving each layer over the previous one, so a layer that sets deny also resets deny_all, one that sets approve resets approve_all and both "with edits" labels, and one that sets only approved resets approved_edited, and APPROVAL_LABELS lists the keys.
panel_agents.recording¶
Recorder, HistoryRecorder, dump_events, load_events, load_history, load_state and FORMAT_VERSION, plus Codec(name, applies, encode, decode) and register_codec(codec, first=True) to round-trip values that are not JSON serializable.
panel_agents.security¶
inert_markdown is a markdown-it plugin that makes untrusted Markdown inert on the parsed tokens: raw HTML renders as text, images become links unless their origin is trusted, links are limited to http, https, mailto and relative ones and show their full URL. untrusted_markdown(text, **params) returns a Markdown pane using it with math disabled, in the page as well as on the server. Chat messages, thinking, text tool results and text or markdown artifacts are rendered with it, and titles, tool names and descriptions, reasons and error messages are shown as plain text. set_trusted_image_origins(origins) and trusted_image_origins() set and read the origins images may load from ("*" for all).
panel_agents.adapters.pydantic_ai¶
Requires the pydantic-ai extra.
| Name | Purpose |
|---|---|
AgentRunner(agent=None, state=None, deps=None, *, approval_policy, thread_id, run_kwargs, raise_errors, model) |
Runs a pydantic-ai agent into a RunState, keeping the conversation. model overrides the agent's model from the next run on, unless run_kwargs or run pass one; a run paused for an approval keeps its model, while run(deferred_tool_results=...) is a new run with the model set by then. await run(prompt, *, deferred_tool_results=None, **kwargs), unavailable_reason(model) (why a model cannot be used, or None), cancel(), clear(), close(); running, run_id, error, deferred, messages. A failed run, unless cancelled, is logged with its traceback on the panel_agents logger and adds an error message to the timeline. |
publish_artifact(ctx, artifact_id, value, *, title, kind, metadata, applied=False) |
Publish an artifact version from an async tool, stamped with the run, the tool call and the actor "agent". |
artifact_return(return_value, artifact_id, value, *, title, kind, metadata, applied=False) |
Return a value to the model and publish an artifact, from any tool. |
ActionToolset(registry, *, id=None, max_retries=1) |
An ActionRegistry as a pydantic-ai toolset. |
ModelTraceRecorder(runner, sink, *, include_content=True, on_error="log") |
Keeps a JSON Lines model trace in sync with a runner's pydantic-ai message history while it runs, with rewind records where the history was rewritten and failed_run records for runs that fail. close(). |
load_messages(source, *, include_failed=False) |
The history a model trace ends with, as pydantic-ai ModelMessages; assign it to AgentRunner.messages to continue the conversation. |
load_model_calls(source) |
One ModelRequestSummary(run_id, model, timestamp, duration, tool_calls, input_tokens, output_tokens, cached_tokens, cost_usd, error, provider_response_id, request_id, finish_reason, attempt_of) per model request, including failed ones. |
merge_model_calls(events, calls) |
The events of a conversation recording with a ModelRequestStarted and Usage event added for each model call of a model trace, so a session recorded without them replays with its model calls. |
Cassette(messages, *, strict=False, check_fingerprint=True), Cassette.from_trace(source, **kwargs) |
A pydantic-ai FunctionModel that plays recorded responses back in order, streamed or not. divergences, played, remaining, responses. |
Divergence(request, kind, expected, actual, tool_name=None, tool_call_id=None), CassetteError |
A difference between playback and the recording (kind is "tool_return", "prompt", "retry" or "fingerprint"), and the error raised when playback cannot continue. |
RecordedFailure |
Raised where playback reaches a request that failed when it was recorded, with the recorded error as its message, e.g. "RuntimeError: provider refused". |
fingerprint(model_request_parameters, messages=()) |
A short hash of the instructions, system prompts and function tools offered to the model, stored on every recorded response. |
AgentRunner passes its run_id to pydantic-ai (run(..., run_id=...) chooses it) and stores the request's duration, fingerprint and request_id on each ModelResponse under metadata["panel_agents"]. It emits a ModelRequestStarted event when a request begins and a Usage event when it ends, failed requests included. The trace names also live in panel_agents.adapters.model_trace, together with its FORMAT_VERSION, and the cassette names in panel_agents.adapters.cassette.
panel_agents.mcp¶
Requires the mcp extra. await create_server(source, *, deps=None, deps_factory=None, name=None, instructions=None, approval_policy=None, user=None, approval_secret=None) -> fastmcp.FastMCP serves an AgentRunner, agent, toolset or ActionRegistry over MCP. approval_secret signs the approval state a client sends back, see Serve an agent's tools over MCP.