* Python: A2UI (Agent-to-UI) support for the AG-UI adapter Adds an in-package _a2ui module to agent-framework-ag-ui delivering progressive-streaming, error-recovery, and sub-agent-based A2UI surface generation, reusing the shared ag-ui-a2ui-toolkit. Includes example agents, a unit suite, and two bridge fixes (strip unanswered tool calls from replayed history; suppress the terminal MESSAGES_SNAPSHOT for A2UI runs to keep streamed order stable). Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review feedback — declarative wiring, no agent swap Reworks A2UI so it no longer swaps the agent object mid-run, and fixes the issues that swap caused. - Drive A2UI through a dedicated runner used only for the stream call; keep the original agent bound so protected-state-key computation, approval resolution, and continuation serialization still read its real context_providers and client (no more provider-namespace or approval middleware loss). - Hand the forwarded AG-UI context to the runner directly instead of stamping it onto run-option additional_properties. That channel leaked the slice to the provider SDK on any run carrying AG-UI context, including non-A2UI runs where nothing stripped it back. Removes the stamp/strip/read helpers and the dead .NET-shaped path. - Suppress the terminal MESSAGES_SNAPSHOT off whether A2UI actually drove the run, not the literal tool names, so an unrelated user tool named "generate_a2ui" keeps its snapshot. - Fail loud with an install hint when A2UI is requested but the toolkit isn't installed, instead of advertising render_a2ui with no executor. - Include the agent's own default tools in the no-double-injection check so an already-wired agent doesn't crash on a duplicate tool name. - Execute ordinary developer tools called in the same turn as generate_a2ui (the declaration-only tool poisons the inner batch invocation), so a "look up data then render it" turn no longer skips the backend call. - Attribute nameless streaming argument deltas by the provider tool-call index so interleaved parallel calls don't cross-contaminate; the OpenAI chat client preserves that index on the content. Adds tests for the mixed-batch execution, index-based fragment attribution, and the default-tool duplicate check. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 2 — mixed-batch pipeline, client tools, snapshot - Mixed-batch (a tool called in the same turn as generate_a2ui): execute server tools through the agent's real function-invocation pipeline (client function_middleware + config), the same path approval-resume uses, instead of a direct tool.invoke() that bypassed middleware/context/session. - Look up mixed-batch tools across incoming AND the agent's own default tools, so a server tool wired only on the agent (no runtime tools=) still executes. - Leave declaration-only client tools (func=None) as user-input requests instead of synthesizing a local result, preserving the resumable client-tool flow. - Recognize a manually enable_a2ui()-wrapped agent when deciding to suppress the terminal MESSAGES_SNAPSHOT, so the ordering fix also covers that path. - Remove .NET-specific comments from the Python module. Adds tests: server-tool execution runs through middleware, default-tool execution, client declaration-only tool left as user-input. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 2 — fold context wrapper, typed runner Consolidates A2UI wiring into one owner, per review: - Fold the context-prepend (former AGUIContextAgent) into A2UIAgent, which now prepends the forwarded catalog + guidelines as a system message itself. Removes the extra agent type (matching the langgraph/strands adapters, which have no separate context agent). - Make A2UIAgent the typed runner interface: it carries the render tool(s) to strip (drop_tool_names) and is recognized via is_a2ui_runner(). plan_a2ui_injection now returns the runner (or None) instead of a bare dict, so no private plan keys leak into the host and the host no longer tracks activation separately — is_a2ui_runner() covers both the auto-injected and manual enable_a2ui() paths. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI — bridge test for client tool + generate_a2ui in one turn End-to-end through run_agent_stream: a turn that calls a declaration-only client tool alongside generate_a2ui surfaces the client tool as a resumable frontend tool call (START/ARGS/END, no server-synthesized result) so the frontend executes and resumes it, the A2UI surface still renders, the run finishes, and no terminal MESSAGES_SNAPSHOT is emitted (manual enable_a2ui path). Confirms the mixed-batch client-tool contract on the AG-UI wire, not just at the agent level. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 3 — manual-path delegation, per-request context, facade - A2UIAgent delegates client / default_options / context_providers to the wrapped agent, so a manually enable_a2ui()-wrapped runner keeps the inner agent's configured tools, provider-owned state protection, and approval middleware that the auto-injected path already preserves. - Take the AG-UI context slice per run (a2ui_context kwarg the host passes each request) instead of only at construction, so a reused runner never serves stale catalog/guidelines. - Remove the deleted AGUIContextAgent from the package facade's __all__ and lazy exports (it no longer resolves) and drop the remaining doc references to it. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 3 — mixed-batch reuses the core invocation controls Reworks server-tool execution batched with generate_a2ui so it goes through the shared function-invocation owner faithfully instead of a partial re-implementation: - Pass the run's invocation session and the full function-middleware pipeline (static client middleware plus runtime middleware) into the execution. - Honor function_invocation_configuration["enabled"] and the shared per-request max_function_calls budget, tracked cumulatively across A2UI planner rounds, so a side-effecting tool cannot run once per round or run while invocation is disabled. - Preserve non-result control contents (e.g. a function_approval_request for an always_require tool) and the executor's termination signal instead of filtering to function_result, and surface them on the wire. - Stop the run instead of re-entering the planner whenever the turn carries calls it cannot safely replay — client tools awaiting the frontend, deferred/over-budget or approval-pending server tools, or a termination request — so an unanswered assistant tool_call is never replayed as unbalanced history. Tests: cumulative budget cap across rounds, invocation-disabled skip, approval request surfaced + run stops, and the bridge test now asserts the planner is not re-entered. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 4 — core batch executor, budget/iteration parity - Add a core-owned execute_function_call_batch() to agent_framework._tools that builds the function-middleware pipeline (static + runtime, normalizing bare objects and expanding MiddlewareBundles via categorize_middleware), normalizes config, threads the invocation session, and returns a structured result (results / control / should_terminate). A2UI's mixed-batch server execution now delegates to it instead of reproducing the pipeline/session/result handling, so a runtime `middleware=<bare>` or a bundle no longer raises or is silently skipped, and future core policy changes stay in one place. - Charge generate_a2ui against the per-request max_function_calls budget (each is a render-subagent invocation) and cap the planner rounds by max_iterations, so a generate-only planner can no longer run more render calls than the configured limits. Tests: generate-only planner honors the call budget and max_iterations; the mixed-batch budget test accounts for generate also charging. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 5 — force tools off on the final narration turn The final narration turn started a fresh inner_agent.run() with tools still enabled, so after the planner rounds/budget were spent it could execute another full batch of server/default tools and exceed max_function_calls / max_iterations. Set tool_choice="none" on that turn so it is a pure narration with no tool execution, matching the core loop's budget-exhausted final response. Test: the final narration turn's options carry tool_choice="none". Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 5 — move the budget lifecycle into a core owner Add a core-owned FunctionCallBudget to agent_framework._tools that owns the per-request accounting the core loop enforces: the invocation toggle, the cumulative max_function_calls budget, the max_iterations round cap, and the tools-off final-response options. execute_function_call_batch now takes a budget and returns the deferred (unrun) calls. A2UIAgent's planner loop no longer reimplements any of this — it holds one budget object and asks it (rounds_remaining / take / exhausted / final_response_options), so server tools, generate_a2ui, the round cap, and the final tools-off turn all go through the single core owner. This removes the split that let the final turn start a fresh budget, and keeps mixed A2UI turns aligned with core policy changes. Tests: core budget primitive (take/exhausted/rounds/final-options); invocation disabled now runs no server tool AND no surface (matches the core loop). Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI review round 5 follow-up — keep budgeting local, narrate on budget exhaustion Per review, the core is not the place for a second budget abstraction: remove the FunctionCallBudget class from agent_framework._tools (execute_function_call_batch, which was the requested shared executor, stays). A2UIAgent honors the inner agent's function-invocation configuration locally again — the invocation toggle, the cumulative max_function_calls budget (charged by server tools and generate_a2ui), and the max_iterations round cap. Also fix the reported gap: when the call budget is exhausted (e.g. max_function_calls=1 spent on the first generate_a2ui), the run now breaks to the tools-off final narration turn instead of returning after the surface, so it produces a closing assistant response — matching the iteration-cap path and the core loop. Calls awaiting external resolution (client tools, deferred, approval, termination) still end the run without that final turn, since a follow-up run resumes them. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI — feed the current surface to the budget-exhausted final narration On budget exhaustion the loop broke before appending this round's assistant tool_call(s) and results to history, so the tools-off final narration turn saw only the original user messages and could not narrate the generate_a2ui result it had just produced. Append the round's assistant/tool pair before breaking so the final turn receives it. The test now asserts the final turn's messages include the just-produced surface. Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI — keep batch execution in the adapter; fix CI typing Per review, don't add A2UI-specific abstractions to core: remove execute_function_call_batch / FunctionCallBatchExecution from agent_framework._tools. A2UIAgent's _execute_server_tools now runs the mixed batch inline using the framework's existing helpers (_try_execute_function_call_groups plus categorize_middleware for bare/bundle middleware normalization) with the run's session, config, and middleware — the same helpers the AG-UI approval path uses — so nothing adapter-specific lives in core. Also fix the CI typing check: annotate the A2UI test doubles and helpers so mypy, pyrefly, and ty pass over the test module (mixed-shape result tuples, a nullable envelope helper, and duck-typed fakes passed where protocols are expected). Signed-off-by: ran <ran@copilotkit.ai> * Python: A2UI — propagate MiddlewareFailure through the inline server-tool path; generic non-leaking error results; fix ty test typing - _execute_server_tools now re-raises MiddlewareFailure so a fail-closed authorization/guardrail abort stops the run instead of being folded into an error result that would still render a surface (matches the core loop). - Ordinary execution failures return core's generic 'Error: Function failed.' message; the raw exception text rides the non-model-visible exception field and is only exposed when include_detailed_errors is enabled, so credentials/ provider payloads/tenant data cannot leak to the model. - Add ty suppressions on the two duck-typed test constructors (ty does not honor mypy-style '# type: ignore[arg-type]') to clear the Test Typing Checks gate. - Cover both behaviors with tests (MiddlewareFailure aborts without rendering; tool error result is generic and non-leaking). --------- Signed-off-by: ran <ran@copilotkit.ai> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
Agent Framework AG-UI Integration
AG-UI protocol integration for Agent Framework, enabling seamless integration with AG-UI's web interface and streaming protocol.
Installation
pip install agent-framework-ag-ui
Quick Start
Server (Host an AI Agent)
from fastapi import FastAPI
from agent_framework import Agent
from agent_framework.openai import OpenAIChatCompletionClient
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
# Create your agent
agent = Agent(
name="my_agent",
instructions="You are a helpful assistant.",
client=OpenAIChatCompletionClient(
azure_endpoint="https://your-resource.openai.azure.com/",
model="gpt-4o-mini",
api_key="your-api-key",
),
)
# Create FastAPI app and add AG-UI endpoint
app = FastAPI()
add_agent_framework_fastapi_endpoint(app, agent, "/")
# Run with: uvicorn main:app --reload
Server (Host a Workflow)
from fastapi import FastAPI
from agent_framework import WorkflowBuilder, WorkflowContext, executor
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
@executor(id="start")
async def start(message: str, ctx: WorkflowContext) -> None:
await ctx.yield_output(f"Workflow received: {message}")
workflow = WorkflowBuilder(start_executor=start).build()
app = FastAPI()
add_agent_framework_fastapi_endpoint(app, workflow, "/")
Server (Thread-Scoped WorkflowBuilder)
Use workflow_factory when your workflow keeps runtime state (for example pending request_info interrupts) and must be isolated per AG-UI thread:
from fastapi import FastAPI
from agent_framework import Workflow, WorkflowBuilder
from agent_framework.ag_ui import AgentFrameworkWorkflow, add_agent_framework_fastapi_endpoint
def build_workflow_for_thread(thread_id: str) -> Workflow:
# Build a fresh workflow instance for each thread id.
return WorkflowBuilder(start_executor=...).build()
app = FastAPI()
thread_scoped_workflow = AgentFrameworkWorkflow(
workflow_factory=build_workflow_for_thread,
name="my_workflow",
)
add_agent_framework_fastapi_endpoint(app, thread_scoped_workflow, "/")
Client (Connect to an AG-UI Server)
import asyncio
from agent_framework.ag_ui import AGUIChatClient
async def main():
async with AGUIChatClient(endpoint="http://localhost:8000/") as client:
# Stream responses
async for update in client.get_response("Hello!", stream=True):
for content in update.contents:
if content.type == "text" and content.text:
print(content.text, end="", flush=True)
print()
asyncio.run(main())
The AGUIChatClient supports:
- Streaming and non-streaming responses
- Hybrid tool execution (client-side + server-side tools)
- Automatic thread management for conversation continuity
- Integration with
Agentfor client-side history management - Canonical interrupt/resume passthrough (
availableInterruptsandresume)
Tool Return Helpers
Use state_update when a backend tool needs to send different payloads to the model, the UI, and shared state. The text value remains the LLM-bound tool result, tool_result becomes the AG-UI ToolCallResultEvent.content for frontend rendering, and state is merged into durable shared state.
from agent_framework import Content, tool
from agent_framework.ag_ui import state_update
@tool
async def get_weather(city: str) -> Content:
data = await fetch_weather(city)
return state_update(
text=f"{city}: {data['temp']}°C and {data['conditions']}",
tool_result={
"component": "weather-card",
"city": city,
"temperature": data["temp"],
"conditions": data["conditions"],
"humidity": data["humidity"],
},
state={"weather": {"city": city, **data}},
)
Documentation
- Getting Started Tutorial - Step-by-step guide to building AG-UI servers and clients
- Server setup with FastAPI
- Client examples using
AGUIChatClient - Hybrid tool execution (client-side + server-side)
- Thread management and conversation continuity
- Examples - Complete examples for AG-UI features
Interrupts and Resume
Agent Framework AG-UI uses the canonical AG-UI interrupt protocol. Paused agent approval and workflow
request_info runs finish with RUN_FINISHED.outcome.type == "interrupt" and a non-empty
RUN_FINISHED.outcome.interrupts array. Agent Framework does not define a separate interrupt model; use
ag_ui.core.Interrupt and ag_ui.core.ResumeEntry when constructing typed request data in Python.
Tool approval interrupts use reason: "tool_call" and include toolCallId when the pause is bound to a tool call.
Workflow request_info interrupts use reason: "input_required". Framework-specific details needed for resume
validation live in each interrupt's metadata, while generic clients can render the human-readable message and
responseSchema.
Interrupted terminal event shape:
{
"type": "RUN_FINISHED",
"outcome": {
"type": "interrupt",
"interrupts": [
{
"id": "approval_1",
"reason": "tool_call",
"message": "Approve tool call get_weather?",
"toolCallId": "tool_call_1",
"responseSchema": {
"type": "object",
"properties": {
"approved": { "type": "boolean" },
"accepted": { "type": "boolean" },
"city": { "type": "string" },
"editedArgs": {
"type": "object",
"description": "Full replacement of the tool arguments. Not merged.",
"properties": {
"city": { "type": "string" }
},
"required": ["city"],
"additionalProperties": false
}
},
"anyOf": [
{ "required": ["approved"] },
{ "required": ["accepted"] }
]
},
"metadata": {
"agent_framework": {
"type": "function_approval_request",
"function_call": {
"call_id": "tool_call_1",
"name": "get_weather",
"arguments": {
"city": "Seattle"
}
}
}
}
}
]
}
}
Resume the paused thread with a canonical resume array. Each entry addresses exactly one open interrupt by
interruptId; status is resolved or cancelled; resolved entries carry the approval or workflow response payload.
Tool approvals use the standard approved field and may provide editedArgs as a full replacement of the tool
arguments. For compatibility with existing MAF clients, accepted remains an alias for approved, and direct
argument fields remain supported as partial edits. Cancellation is a normal terminal decision: cancelled calls do
not execute, while resolved siblings in the same complete resume continue normally. The same tool-approval shape and
resume payloads apply when an agent approval is surfaced through a workflow request_info event.
{
"threadId": "thread-1",
"messages": [],
"resume": [
{
"interruptId": "approval_1",
"status": "resolved",
"payload": {
"approved": true
}
}
]
}
This is a clean release-candidate breaking change before 1.0.0: new interrupted runs use
RUN_FINISHED.outcome.interrupts and do not emit a stable top-level RUN_FINISHED.interrupt field. Normal
non-interrupted runs continue to finish with valid RUN_FINISHED terminal events.
Public API Review Notes
The Python package is currently in release candidate stage and is targeting the released 1.0.0 API surface. The preferred application import path is agent_framework.ag_ui; direct package imports from agent_framework_ag_ui are also supported.
Review focus: whether these names are the right stable contract for Python users, and whether the protocol interrupt fields below match AG-UI's expected pause/resume shape.
| Surface | Public exports |
|---|---|
agent_framework.ag_ui facade |
AgentFrameworkAgent, AgentFrameworkWorkflow, AGUIChatClient, AGUIEventConverter, AGUIHttpService, AGUIThreadSnapshot, AGUIThreadSnapshotStore, InMemoryAGUIThreadSnapshotStore, SnapshotScopeResolver, add_agent_framework_fastapi_endpoint, state_update, __version__ |
Direct agent_framework_ag_ui package |
Facade exports plus AGUIChatOptions, AGUIRequest, AGUIThreadID, AgentState, DEFAULT_MAX_THREAD_SNAPSHOTS, DEFAULT_TAGS, PredictStateConfig, RunMetadata, SnapshotScope, WorkflowFactory |
AG-UI protocol package (ag_ui.core) |
Interrupt, ResumeEntry, RunFinishedInterruptOutcome, and related run outcome models |
Interrupt support is protocol data rather than a separate Agent Framework Python class. Requests accept canonical availableInterrupts/available_interrupts and resume values; AGUIChatClient and AGUIHttpService.post_run(...) forward those fields with AG-UI wire aliases; agent approval and workflow request_info pauses emit RUN_FINISHED.outcome.interrupts; AGUIEventConverter preserves canonical interrupt outcome metadata on the final ChatResponseUpdate; and thread snapshot hydration replays the canonical interrupt outcome when a scoped snapshot stores an unresolved pause.
Features
This integration supports all 7 AG-UI features:
- Agentic Chat: Basic streaming chat with tool calling support
- Backend Tool Rendering: Tools executed on backend with results streamed to client
- Human in the Loop: Function approval requests for user confirmation before tool execution
- Agentic Generative UI: Async tools for long-running operations with progress updates
- Tool-based Generative UI: Custom UI components rendered on frontend based on tool calls
- Shared State: Bidirectional state sync between client and server
- Predictive State Updates: Stream tool arguments as optimistic state updates during execution
Additional compatibility and draft support:
- Native
Workflowendpoint registration viaadd_agent_framework_fastapi_endpoint(...) - Workflow-to-AG-UI event mapping (run/step/activity/tool/custom events)
- Custom event compatibility for inbound
CUSTOM,CUSTOM_EVENT, andcustom_event - Pragmatic multimodal input parsing for both legacy (
binary) and draft media-part shapes - Canonical interrupt/resume handling (
availableInterrupts,resume, andRUN_FINISHED.outcome.interrupts)
Security: Authentication & Authorization
The AG-UI endpoint does not enforce authentication by default. For production deployments, you should add authentication using FastAPI's dependency injection system via the dependencies parameter.
API Key Authentication Example
import os
from fastapi import Depends, FastAPI, HTTPException, Security
from fastapi.security import APIKeyHeader
from agent_framework import Agent
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
# Configure API key authentication
API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)
EXPECTED_API_KEY = os.environ.get("AG_UI_API_KEY")
async def verify_api_key(api_key: str | None = Security(API_KEY_HEADER)) -> None:
"""Verify the API key provided in the request header."""
if not api_key or api_key != EXPECTED_API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API key")
# Create agent and app
agent = Agent(name="my_agent", instructions="...", client=...)
app = FastAPI()
# Register endpoint WITH authentication
add_agent_framework_fastapi_endpoint(
app,
agent,
"/",
dependencies=[Depends(verify_api_key)], # Authentication enforced here
)
Other Authentication Options
The dependencies parameter accepts any FastAPI dependency, enabling integration with:
- OAuth 2.0 / OpenID Connect - Use
fastapi.security.OAuth2PasswordBearer - JWT Tokens - Validate tokens with libraries like
python-jose - Azure AD / Entra ID - Use
azure-identityfor Microsoft identity platform - Rate Limiting - Add request throttling dependencies
- Custom Authentication - Implement your organization's auth requirements
For a complete authentication example, see getting_started/server.py.
Conversation and Tool Result Trust
In the default stateless mode, the AG-UI client sends the conversation history for each run. Treat that history as
untrusted input, including client-supplied assistant tool calls and tool results. A historical tool result is not
proof that the server emitted the matching call or executed the named backend tool.
Do not use conversation history, tool results, or the model's decision to call a tool as an authorization, entitlement, approval, or policy signal. Enforce security decisions deterministically in authenticated server code, such as endpoint dependencies, tool middleware, or the server-validated human-in-the-loop approval flow. Tool implementations must also authorize the current principal before accessing protected data or performing sensitive actions.
For applications that need server-authoritative thread history, configure scoped AG-UI Thread Snapshots. Snapshot mode only accepts user turns and results for backend-issued tool calls when extending stored history. It complements endpoint authentication and authorization; it does not replace them.
AG-UI Thread Snapshots
AG-UI Thread Snapshot persistence is opt-in and disabled by default. Existing endpoints keep their current behavior
unless you provide a snapshot_store.
Thread snapshots let an AG-UI frontend recover replayable UI state after a refresh. When snapshot persistence is
enabled, the endpoint stores the latest replayable snapshot for an AG-UI Thread within an application-defined
Snapshot Scope. A Hydrate Request is an AG-UI request with a known threadId, messages: [], and no resume
payload. Hydration replays the stored Shared State, message snapshot, and canonical interrupt outcome when available,
then finishes without invoking the wrapped agent or workflow.
Use the built-in in-memory store for local development, demos, and tests:
from fastapi import FastAPI
from agent_framework.ag_ui import InMemoryAGUIThreadSnapshotStore, add_agent_framework_fastapi_endpoint
app = FastAPI()
agent = ...
snapshot_store = InMemoryAGUIThreadSnapshotStore(max_snapshots=500)
def resolve_snapshot_scope(request):
# Local demo scope. Production apps should derive the scope from authenticated user or tenant context.
del request
return "local-demo"
add_agent_framework_fastapi_endpoint(
app,
agent,
"/",
snapshot_store=snapshot_store,
snapshot_scope_resolver=resolve_snapshot_scope,
)
A frontend can then hydrate the latest stored snapshot for the scoped thread:
{
"threadId": "thread-1",
"messages": []
}
Endpoint configuration requires snapshot_scope_resolver whenever a snapshot store is configured, including when
the store is already set on a pre-wrapped AgentFrameworkAgent or AgentFrameworkWorkflow. The resolver returns
the application-defined Snapshot Scope used with the AG-UI Thread id as the storage key. When using
AgentFrameworkWorkflow(workflow_factory=...), the same resolver also scopes the in-memory workflow cache even
without a snapshot store; provide it in multi-user deployments so two users who submit the same threadId do not
share a live Workflow instance.
For hosted agents, request Shared State is also available through AgentSession.state during that run, whether or
not snapshot persistence is configured. Request values are untrusted per-run context: they overlay ordinary restored
values, are not passed through typed session restoration, and are excluded from private Session Continuation State.
Keys owned by configured context providers or reserved for approval and message-injection middleware are not copied
into AgentSession.state; their server-owned values take precedence over client Shared State.
When scoped snapshots are configured, each category has one State Authority:
| State category | State Authority |
|---|---|
| Conversation history | AG-UI Thread Snapshot messages |
| AG-UI Shared State and request context | The current AG-UI request and replayable snapshot state |
| Approval State | The Approval State Store |
| Other server-produced provider working state | Private Session Continuation State |
Session Continuation State is stored atomically in the optional AGUIThreadSnapshot.session_state field and restored
through the core AgentSession typed serialization contract. It is never accepted from an AG-UI request or emitted
during hydration. Deleting a scoped thread snapshot resets its replayable and private state together, and clearing a
Snapshot Scope removes all such records in that scope. Missing or empty request Shared State is not a reset command.
If private continuation cannot be restored or serialized, the endpoint logs the failure and continues without that
continuation so stale or unsupported provider state cannot permanently block the thread or suppress RUN_FINISHED.
AG-UI Thread ids identify AG-UI Threads; they do not authorize snapshot access. Do not treat a thread id as a bearer credential or tenant boundary. Production applications must authenticate and authorize every AG-UI endpoint request and choose a Snapshot Scope that represents the app's real access boundary, such as an authenticated user, tenant, or workspace. Do not rely on untrusted client-provided fields by themselves to choose that boundary.
Tool approval resumes are validated against server-owned Approval State. The default Approval State store is process-local and bounded, and stores only approval-specific state needed to validate and continue pending approvals. It is not an authentication, tenant authorization, or distributed durability mechanism; production applications remain responsible for endpoint authentication, tenant authorization, and deployment/storage architecture that matches their availability and worker topology requirements.
Snapshot storage is treated as trusted server-side storage because private continuation is eligible for typed core
restoration; applications are responsible for providing its integrity protection. Snapshots also have confidentiality
impact: they may contain sensitive user text, model output, tool results, function arguments, UI payloads, Shared State,
interrupt data, and private provider working state. The built-in InMemoryAGUIThreadSnapshotStore is in-memory only,
process-local, bounded, latest-only, and not durable production storage. It is cleared on process restart and is not
shared across workers.
No file-backed AG-UI snapshot store is provided by the package. Applications that need durable persistence should
provide an app-owned implementation of the AGUIThreadSnapshotStore protocol and own storage hardening, including
encryption, integrity protection, access control, retention, audit, data residency, and deletion behavior. Existing
custom stores remain source-compatible because session_state is optional, but they provide Session State Continuity
only when they round-trip that field unchanged with the rest of the snapshot.
The supported consistency model is one active run per (Snapshot Scope, threadId). Concurrent writes to the same
scoped thread remain last-writer-wins. Applications that require stronger consistency must serialize those runs using
coordination appropriate to their deployment; a process-local lock does not provide distributed consistency.
Architecture
The package uses a clean, orchestrator-based architecture:
- AgentFrameworkAgent: Lightweight wrapper that delegates to orchestrators
- Orchestrators: Handle different execution flows (default, human-in-the-loop, etc.)
- Confirmation Strategies: Domain-specific confirmation messages (extensible)
- AgentFrameworkEventBridge: Converts Agent Framework events to AG-UI events
- Message Adapters: Bidirectional conversion between AG-UI and Agent Framework message formats
- FastAPI Endpoint: Streaming HTTP endpoint with Server-Sent Events (SSE)
Next Steps
- New to AG-UI? Start with the Getting Started Tutorial
- Want to see examples? Check out the Examples for AG-UI features
License
MIT