Learning resourcesReviewed · Pydantic

Pydantic AI AG-UI Integration Guide

Pydantic AI's AG-UI guide helps Python and frontend developers connect AI agents to interactive apps, with authorization and conversation history requiring careful setup. It covers streamed responses, shared state, frontend tools, approval pauses and protocol compatibility through AGUIAdapter.

Researched 15 Nov 2026

In short.

This AG-UI integration guide teaches Python and frontend developers how to connect Pydantic AI agents to user interfaces, with compatibility, authorization and saved conversations requiring care. It explains three integration approaches, streamed events, validated shared state, tool approvals and optional messaging-platform connections. A particularly important limitation is that the documented JavaScript client omits activity messages from subsequent requests, potentially losing compaction, file and capability records unless the application preserves them. Protocol versions also change approval, cancellation and media behavior. The examples and compatibility claims were not executed or independently verified.

Researched and written by an AI model and checked by a second AI model. How it works

Covers the complete supplied page at [https://pydantic.dev/docs/ai/integrations/ui/ag-ui/index.md], including installation, all three request-handling approaches, shared state, tools, context, interrupts, events, compatibility, trust boundaries, history records, compaction, injected messages, MCP Apps, message identity, retry and failure preservation, files, structured content, system prompts, channels and example references. Compatibility, security, cancellation, file-behavior and persistence notices are included. Linked pages and repositories are excluded. Runtime behavior, deployment outcomes, performance, prices and licensing terms beyond the page are not established.

The overview

Identity

The resource is Pydantic AI's documentation page for its Agent-User Interaction integration at [https://pydantic.dev/docs/ai/integrations/ui/ag-ui/index.md]. It teaches developers to expose a Python agent through AGUIAdapter so a compatible frontend can exchange messages, tools, state and events with it.

The page describes AG-UI as an open standard introduced by CopilotKit. It credits the team at Rocket Science with originally building the integration, which was contributed in collaboration with the Pydantic AI and CopilotKit teams. The resource itself is an implementation guide rather than a complete application.

Assessment

The guide provides useful implementation detail for teams adding an interactive interface to a Pydantic AI agent. Its practical strengths are concrete FastAPI and Starlette examples, guidance that the lower-level run_stream() approach can be adapted to frameworks not based on Starlette, such as Django or Flask, though no Django or Flask code is shown, and explicit treatment of approval failures, client disconnects and conversation continuity.

The shortest example exposes an agent through one endpoint, but a dependable application also needs authenticated permissions, appropriate history storage and compatible frontend behavior. The page does not establish performance, deployment reliability or successful operation of any particular application.

Users

The main audience is Python developers building agent backends and frontend developers implementing AG-UI interfaces. FastAPI and Starlette users receive the most direct request-handling examples. Django and Flask users are directed toward the lower-level streaming interface, where they handle framework-specific parsing and responses themselves.

Beginners receive installation commands and small server examples, but still need to understand asynchronous request handling, streaming responses and the division between browser and server responsibilities. Developers connecting an agent to Slack also need a separate Node channel process and platform setup.

Capabilities

The documented integration streams agent events, exposes frontend tools to the agent, synchronizes shared state and supports approval pauses followed by resumed runs. Client context can be exposed to the model as data, while forwardedProps carries application-specific values without automatic interpretation by the adapter.

CustomEvent values emitted through ctx.emit() can report progress while a tool runs. Events attached to ToolReturn metadata arrive when the tool returns and can survive a history round trip. The guide also covers files, structured content, compaction records, injected messages and preservation of failed tool outcomes, subject to version and history-handling constraints.

Additional sections describe MCP Apps rendering and Slack connections through CopilotKit Channels. MCP Apps relay requests require explicit handling in the application's route before ordinary agent dispatch.

Using it

Requirements

The guide identifies ag-ui-protocol for protocol types and encoding, and Starlette for ASGI request handling. Its installation command is pip install 'pydantic-ai-slim[ag-ui]', with uv add 'pydantic-ai-slim[ag-ui]' as an alternative. Running the examples also requires Uvicorn or another ASGI-compatible server.

An end-to-end application needs a configured Pydantic AI agent and a compatible frontend. The page does not provide a complete provider-credential setup, frontend implementation or minimum Python version. Features have separate protocol requirements: baseline support starts at ag-ui-protocol 0.1.10, metadata preservation uses 0.1.11 or later, and interrupts require 0.1.19 or later.

For shared state, use StateDeps with a Pydantic model or a StateHandler dataclass with a non-optional state field. Unsupported dependency types cause incoming state to be ignored with a warning. The documented channel process requires a long-running host for its persistent gateway connection.

Mechanism

A frontend submits RunAgentInput containing the requested run's messages, state and tools. The adapter converts these into Pydantic AI types, runs the agent, converts resulting events into AG-UI events and streams them back through Server-Sent Events. Frontend tool execution and approvals can require additional requests.

AGUIAdapter.run_stream() gives applications direct control over input and output. AGUIAdapter.dispatch_request() combines request parsing, agent execution and a streaming Starlette response. The third approach places that convenience method inside a minimal standalone Starlette application. Applications can also transform native Pydantic AI events and encode the resulting stream separately.

Streamed tool calls identify their owning assistant message through parentMessageId. The guide says that message is announced first even when it contains only tool calls, allowing a frontend to reconstruct the conversation from events.

Setup

The simplest documented FastAPI route accepts POST requests and returns await AGUIAdapter.dispatch_request(request, agent=agent). The standalone Starlette example puts equivalent handling at its root route. The guide serves that example with uvicorn ag_ui_app:app, after which an AG-UI frontend can send requests.

For shared state, declare a state model and provide a separate dependencies object for each request. The examples use dataclasses.replace(deps), because dispatch_request updates deps.state from the incoming request. Pydantic model state is validated automatically; other state types require application validation.

For approval pauses, declare the tool with requires_approval=True and include DeferredToolRequests in the agent's output_type. For persistent conversations, the documented server-owned approach supplies message_history and manage_message_history='server', or uses a conversation store described on a linked page.

Example

The document-state example models a shared document as a Pydantic object with a document string. The request handler supplies request-specific StateDeps, and a separate tool example returns a StateSnapshotEvent through ToolReturn metadata. This illustrates how an agent-backed editor could send a state update to its interface.

The progress example emits done and total values while an indexing tool runs. The approval example declares a delete_file tool that pauses for approval, but its function only returns a status string; it does not implement filesystem deletion. These are documented examples, and none was executed.

Assessment & evidence

Limitations

Protocol compatibility can change behavior without stopping the whole request. Before ag-ui-protocol 0.1.19, approval interrupts fall back to a bare RUN_FINISHED and resume entries are ignored. Cancellation markers and pendingToolCallIds require both an installed protocol version supporting 1.0 and a request declaring protocolVersion 1.0 or newer. Unknown message or content tags can be skipped with warnings; malformed content under a recognized type is rejected with HTTP 422.

The documented @ag-ui/client behavior omits activity messages from subsequent requests. With client-held history, this can lose records of deferred tools that became available, on-demand capabilities loaded from code, mid-conversation model-settings changes, compaction, injected messages and preserved files. The guide also warns of prompt-cache misses. Server-owned history or explicit client middleware is needed to retain those records.

First-party cancellation closes open events, emits RUN_FINISHED and can invoke on_cancel to preserve resumable history. A disconnected client instead causes external asyncio cancellation, so those completion and callback behaviors do not occur. A stop control needing that behavior must cancel the run while keeping its stream connected.

Files require separate representation and security choices: preserve_file_data retains file records, while allow_uploaded_files controls whether uploaded-file references reach the agent. Failed tool outcomes can survive through metadata without being visibly rendered as errors. Message identifiers also have limits: merged messages retain only one incoming identifier, and newly generated messages receive fresh identifiers on each dump.

Design tradeoffs

The adapter reduces protocol conversion work while leaving trust decisions with the application. Messages, frontend tool schemas, context and forwarded properties originate from the client. Structural validation cannot establish a user's identity or permission. The guide recommends filtering offered frontend tools, establishing identity through server authentication and authorizing side effects from trusted dependencies.

Approval payload validation catches malformed responses and invalid interrupt identifiers before execution resumes. One invalid resume entry fails the run, so sibling approvals are not applied. These checks establish protocol consistency rather than authorization; server-owned history is recommended for approval-gated tools, and application-supplied deferred_tool_results overrides client resume entries.

History metadata preserves richer semantics, but the client can forge it. In particular, structured content can carry different displayed text and machine-readable values, while retry metadata can claim a particular origin. Server-owned system prompts strip client system messages by default. The guide recommends instructions for fresh server-controlled guidance, and reserves client-owned system prompts for frontends trusted as fully as the server.

Alternatives

Within the guide, dispatch_request is the convenient choice for Starlette-based applications, run_stream gives more control for other frameworks or custom transformations, and a minimal Starlette application supplies a standalone endpoint. For conversation continuity, the alternatives are server-owned history, a conversation store, or client middleware that returns the required activity records.

The page also links a community WebSocket example, pydantic-ai-ws-agent, at [https://github.com/huynguyengl99/pydantic-ai-ws-agent]. It describes a persistent bidirectional connection with server-held history, multiple browser tabs receiving one run and cross-tab tool approvals, using chanx and a copied chanx-kit component. That implementation was not assessed, and the page provides no measured comparison with SSE.

Evidence

The evidence is the complete documentation page at [https://pydantic.dev/docs/ai/integrations/ui/ag-ui/index.md], captured on 2026-11-15 at 14:43:34.399 UTC. Its supplied source revision is sha256:6ab5a54cae3e51643155b90f18cb85be2d8f1ea344fead73a0f1d7c98d2d484d.

The findings describe that page's explanations and examples. Linked specifications, API references, package metadata, repositories and platform guides were not examined. No installation, agent run, browser interaction, Slack journey, benchmark or failure-recovery exercise was performed.

Access & freshness

Costs

The page supplies no prices for the integration, model calls, hosting or CopilotKit Intelligence. Total operating cost is unknown. The examples do not establish token consumption, infrastructure sizing or cost per conversation.

With ag-ui-protocol 1.0 or later, include_usage can attach token usage by provider and model to RUN_FINISHED. It is disabled by default because it reveals those provider and model identities to the client. Token counts alone do not establish monetary cost.

Rights

The supplied page describes AG-UI as an open standard but provides no explicit licence terms for the documentation, sample code or integration dependencies. Permission for commercial reuse, modification or redistribution is unknown from this evidence. The linked repositories and their licence files are outside the supplied scope.

Freshness

The capture date establishes when this documentation snapshot was obtained, not when the integration was released or last maintained. The page does not identify a specific Pydantic AI release or publication date. Its statements about current JavaScript client behavior are limited to this snapshot.

The page flags a behavior change: preserve_file_data now controls representation only, so applications previously using it to accept uploaded files also need allow_uploaded_files=True. Developers upgrading an existing application should check this change and the documented protocol thresholds against their actual installed packages.

Next steps

Start with the request-handling example matching your framework and connect a compatible AG-UI frontend. Confirm the installed version of the ag-ui-protocol Python package. Also confirm the client's declared protocol version before depending on approvals, cancellation markers, media handling or metadata preservation.

Choose who stores conversation history before adding compaction, files or dynamically available capabilities. For server-owned history, persist messages by thread and use manage_message_history='server'. Establish user and workspace permissions on the server, filter client-offered tools and keep client context as data.

Before relying on the integration, exercise approval, denial, malformed resume payloads, first-party cancellation, client disconnects and a subsequent conversation turn that restores required records. Check file flags and visible error rendering explicitly. For managed messaging connections, assess durable state, restart behavior, hosting requirements and unknown service costs.

Evidence for this report

selected-page.txtselected · checked 2026-11-15