pydantic_ai.ui
StateDeps
dataclass
Bases: Generic[StateT]
Dependency type that holds state.
This class is used to manage the state of an agent run. It allows setting
the state of the agent run with a specific type of state model, which must
be a subclass of BaseModel.
The state is set using the state setter by the Adapter when the run starts.
Implements the StateHandler protocol.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
StateHandler
Bases: Protocol
Protocol for state handlers in agent runs. Requires the class to be a dataclass with a state field.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
UIAdapter
dataclass
Bases: ABC, Generic[RunInputT, MessageT, EventT, AgentDepsT, OutputDataT]
Base class for UI adapters.
This class is responsible for transforming agent run input received from the frontend into arguments for Agent.run_stream_events(), running the agent, and then transforming Pydantic AI events into protocol-specific events.
The event stream transformation is handled by a protocol-specific UIEventStream subclass.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | |
agent
instance-attribute
agent: AbstractAgent[AgentDepsT, OutputDataT]
The Pydantic AI agent to run.
run_input
instance-attribute
run_input: RunInputT
The protocol-specific run input object.
accept
class-attribute
instance-attribute
accept: str | None = None
The Accept header value of the request, used to determine how to encode the protocol-specific events for the streaming response.
manage_system_prompt
class-attribute
instance-attribute
manage_system_prompt: Literal["server", "client"] = "server"
Who owns the system prompt.
Only affects system_prompt — [instructions][pydantic_ai.Agent.instructions]
are always injected by the agent on every request regardless of this setting.
'server' (default): the agent's configured system_prompt is authoritative.
Any SystemPromptPart sent by the frontend is stripped with a warning (since a
malicious client could otherwise inject arbitrary instructions via crafted API
requests), and the agent's own system prompt is reinjected at the head of the
first request via the
ReinjectSystemPrompt capability.
'client': the frontend owns the system prompt. Frontend SystemPromptParts
are preserved as-is, and the agent's configured system_prompt is not injected
— the caller is fully responsible for sending it on every turn if desired. To
opt into the same fallback-to-configured behavior as server mode, add the
ReinjectSystemPrompt capability
to your agent.
allowed_file_url_schemes
class-attribute
instance-attribute
URL schemes that are allowed for FileUrl parts
(ImageUrl, DocumentUrl,
VideoUrl, AudioUrl)
in client-submitted messages.
Defaults to {'http', 'https'}. Parts whose URL scheme is not in this set are
dropped with a warning before the messages are passed to the agent.
Non-HTTP schemes like s3:// (Bedrock) or gs:// (Google Cloud) cause the model
provider to fetch the object using the server-side IAM role or service account,
so a client that can supply arbitrary URLs can read anything that identity can
reach. HTTPS URLs are safe to forward because the provider fetches them with
its own public credentials, and the library's own [download_item][pydantic_ai.models.download_item]
path applies SSRF protection when it has to download them itself.
For uploads initiated in the browser, prefer pre-signed https:// URLs over
cloud-storage schemes. To opt into a cloud-storage scheme after auditing your
frontend, add it to this set, e.g. frozenset({'http', 'https', 's3'}).
from_request
async
classmethod
from_request(
request: Request,
*,
agent: AbstractAgent[AgentDepsT, OutputDataT],
manage_system_prompt: Literal[
"server", "client"
] = "server",
allowed_file_url_schemes: frozenset[str] = frozenset(
{"http", "https"}
),
**kwargs: Any
) -> Self
Create an adapter from a request.
Extra keyword arguments are forwarded to the adapter constructor, allowing subclasses to accept additional adapter-specific parameters.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
build_run_input
abstractmethod
classmethod
build_run_input(body: bytes) -> RunInputT
Build a protocol-specific run input object from the request body.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
207 208 209 210 211 | |
load_messages
abstractmethod
classmethod
load_messages(
messages: Sequence[MessageT],
) -> list[ModelMessage]
Transform protocol-specific messages into Pydantic AI messages.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
213 214 215 216 217 | |
dump_messages
classmethod
dump_messages(
messages: Sequence[ModelMessage],
) -> list[MessageT]
Transform Pydantic AI messages into protocol-specific messages.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
219 220 221 222 | |
build_event_stream
abstractmethod
build_event_stream() -> (
UIEventStream[
RunInputT, EventT, AgentDepsT, OutputDataT
]
)
Build a protocol-specific event stream transformer.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
224 225 226 227 | |
messages
abstractmethod
cached
property
messages: list[ModelMessage]
Pydantic AI messages from the protocol-specific run input.
toolset
cached
property
toolset: AbstractToolset[AgentDepsT] | None
Toolset representing frontend tools from the protocol-specific run input.
state
cached
property
Frontend state from the protocol-specific run input.
deferred_tool_results
cached
property
deferred_tool_results: DeferredToolResults | None
Deferred tool results extracted from the request, used for tool approval workflows.
conversation_id
cached
property
conversation_id: str | None
Conversation ID extracted from the protocol-specific run input.
Used to correlate multiple agent runs that share message history. Returned as
the gen_ai.conversation.id OpenTelemetry span attribute on each run.
Subclasses for protocols that carry a conversation/thread/chat ID should override this
(e.g. AG-UI's RunAgentInput.threadId, Vercel AI's top-level chat id).
sanitize_messages
sanitize_messages(
messages: Sequence[ModelMessage],
*,
deferred_tool_results: DeferredToolResults | None = None
) -> list[ModelMessage]
Strip parts of client-submitted messages that aren't trusted from the client.
Called on the messages produced from the protocol-specific run input before
they're passed to the agent. Caller-supplied message_history is not passed
through this method — it is trusted as coming from server-side persistence.
Currently strips:
SystemPromptParts whenmanage_system_promptis'server'. The agent's configuredsystem_promptis reinjected byReinjectSystemPrompton the next model request. If stripping leaves aModelRequestwith no parts, the request is dropped from history entirely.FileUrlparts whose URL scheme is not inallowed_file_url_schemes. Non-HTTP schemes likes3://orgs://cause the model provider to fetch the object using the server-side IAM role, so they should only be accepted from trusted frontends.ToolCallPartandNativeToolCallPartentries at the end of the history that don't have a matching entry indeferred_tool_results. Tool calls are produced by the model on the server side, so an unresolved tool call at the end of client-supplied history doesn't correspond to a paused agent run and shouldn't be executed. Tool calls that correspond to a resolution indeferred_tool_resultsare preserved so that human-in-the-loop resumption continues to work. If stripping leaves the final response with no parts, the response is dropped from history entirely.
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | |
transform_stream
transform_stream(
stream: AsyncIterator[NativeEvent],
on_complete: OnCompleteFunc[EventT] | None = None,
) -> AsyncIterator[EventT]
Transform a stream of Pydantic AI events into protocol-specific events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
AsyncIterator[NativeEvent]
|
The stream of Pydantic AI events to transform. |
required |
on_complete
|
OnCompleteFunc[EventT] | None
|
Optional callback function called when the agent run completes successfully.
The callback receives the completed |
None
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
429 430 431 432 433 434 435 436 437 438 439 440 441 | |
encode_stream
encode_stream(
stream: AsyncIterator[EventT],
) -> AsyncIterator[str]
Encode a stream of protocol-specific events as strings according to the Accept header value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
AsyncIterator[EventT]
|
The stream of protocol-specific events to encode. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
443 444 445 446 447 448 449 | |
streaming_response
streaming_response(
stream: AsyncIterator[EventT],
) -> StreamingResponse
Generate a streaming response from a stream of protocol-specific events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
AsyncIterator[EventT]
|
The stream of protocol-specific events to encode. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
451 452 453 454 455 456 457 | |
run_stream_native
run_stream_native(
*,
output_type: OutputSpec[Any] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
conversation_id: str | None = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
capabilities: (
Sequence[AbstractCapability[AgentDepsT]] | None
) = None
) -> AsyncIterator[NativeEvent]
Run the agent with the protocol-specific run input and stream Pydantic AI events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_type
|
OutputSpec[Any] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
conversation_id
|
str | None
|
ID of the conversation this run belongs to. Pass |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
capabilities
|
Sequence[AbstractCapability[AgentDepsT]] | None
|
Optional additional capabilities for this run, merged with the agent's configured capabilities.
Use |
None
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 | |
run_stream
run_stream(
*,
output_type: OutputSpec[Any] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
conversation_id: str | None = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
capabilities: (
Sequence[AbstractCapability[AgentDepsT]] | None
) = None,
on_complete: OnCompleteFunc[EventT] | None = None
) -> AsyncIterator[EventT]
Run the agent with the protocol-specific run input and stream protocol-specific events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_type
|
OutputSpec[Any] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
conversation_id
|
str | None
|
ID of the conversation this run belongs to. Pass |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
capabilities
|
Sequence[AbstractCapability[AgentDepsT]] | None
|
Optional additional capabilities for this run, merged with the agent's configured capabilities.
Use |
None
|
on_complete
|
OnCompleteFunc[EventT] | None
|
Optional callback function called when the agent run completes successfully.
The callback receives the completed |
None
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 | |
dispatch_request
async
classmethod
dispatch_request(
request: Request,
*,
agent: AbstractAgent[
DispatchDepsT, DispatchOutputDataT
],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
conversation_id: str | None = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[DispatchDepsT] = None,
deps: DispatchDepsT = None,
output_type: OutputSpec[Any] | None = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[DispatchDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[DispatchDepsT]] | None
) = None,
capabilities: (
Sequence[AbstractCapability[DispatchDepsT]] | None
) = None,
on_complete: OnCompleteFunc[EventT] | None = None,
manage_system_prompt: Literal[
"server", "client"
] = "server",
allowed_file_url_schemes: frozenset[str] = frozenset(
{"http", "https"}
),
**kwargs: Any
) -> Response
Handle a protocol-specific HTTP request by running the agent and returning a streaming response of protocol-specific events.
Extra keyword arguments are forwarded to from_request,
allowing subclasses to accept additional adapter-specific parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The incoming Starlette/FastAPI request. |
required |
agent
|
AbstractAgent[DispatchDepsT, DispatchOutputDataT]
|
The agent to run. |
required |
output_type
|
OutputSpec[Any] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
conversation_id
|
str | None
|
ID of the conversation this run belongs to. Pass |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[DispatchDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
DispatchDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[DispatchDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[DispatchDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
capabilities
|
Sequence[AbstractCapability[DispatchDepsT]] | None
|
Optional additional capabilities for this run, merged with the agent's configured capabilities.
Use |
None
|
on_complete
|
OnCompleteFunc[EventT] | None
|
Optional callback function called when the agent run completes successfully.
The callback receives the completed |
None
|
manage_system_prompt
|
Literal['server', 'client']
|
Who owns the system prompt. See
|
'server'
|
allowed_file_url_schemes
|
frozenset[str]
|
URL schemes allowed for file URL parts from the client. See
|
frozenset({'http', 'https'})
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
A streaming Starlette response with protocol-specific events encoded per the request's |
Source code in pydantic_ai_slim/pydantic_ai/ui/_adapter.py
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | |
SSE_CONTENT_TYPE
module-attribute
SSE_CONTENT_TYPE = 'text/event-stream'
Content type header value for Server-Sent Events (SSE).
NativeEvent
module-attribute
NativeEvent: TypeAlias = (
AgentStreamEvent | AgentRunResultEvent[Any]
)
Type alias for the native event type, which is either an AgentStreamEvent or an AgentRunResultEvent.
OnCompleteFunc
module-attribute
OnCompleteFunc: TypeAlias = (
Callable[[AgentRunResult[Any]], None]
| Callable[[AgentRunResult[Any]], Awaitable[None]]
| Callable[[AgentRunResult[Any]], AsyncIterator[EventT]]
)
Callback function type that receives the AgentRunResult of the completed run. Can be sync, async, or an async generator of protocol-specific events.
UIEventStream
dataclass
Bases: ABC, Generic[RunInputT, EventT, AgentDepsT, OutputDataT]
Base class for UI event stream transformers.
This class is responsible for transforming Pydantic AI events into protocol-specific events.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
accept
class-attribute
instance-attribute
accept: str | None = None
The Accept header value of the request, used to determine how to encode the protocol-specific events for the streaming response.
message_id
class-attribute
instance-attribute
The message ID to use for the next event.
new_message_id
new_message_id() -> str
Generate and store a new message ID.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
100 101 102 103 | |
response_headers
property
Response headers to return to the frontend.
content_type
property
content_type: str
Get the content type for the event stream, compatible with the Accept header value.
By default, this returns the Server-Sent Events content type (text/event-stream).
If a subclass supports other types as well, it should consider self.accept in encode_event() and return the resulting content type.
encode_event
abstractmethod
encode_event(event: EventT) -> str
Encode a protocol-specific event as a string.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
119 120 121 122 | |
encode_stream
async
encode_stream(
stream: AsyncIterator[EventT],
) -> AsyncIterator[str]
Encode a stream of protocol-specific events as strings according to the Accept header value.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
124 125 126 127 | |
streaming_response
streaming_response(
stream: AsyncIterator[EventT],
) -> StreamingResponse
Generate a streaming response from a stream of protocol-specific events.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
transform_stream
async
transform_stream(
stream: AsyncIterator[NativeEvent],
on_complete: OnCompleteFunc[EventT] | None = None,
) -> AsyncIterator[EventT]
Transform a stream of Pydantic AI events into protocol-specific events.
This method dispatches to specific hooks and handle_* methods that subclasses can override:
- before_stream()
- after_stream()
- on_error()
- before_request()
- after_request()
- before_response()
- after_response()
- handle_event()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
AsyncIterator[NativeEvent]
|
The stream of Pydantic AI events to transform. |
required |
on_complete
|
OnCompleteFunc[EventT] | None
|
Optional callback function called when the agent run completes successfully.
The callback receives the completed |
None
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
handle_event
async
handle_event(event: NativeEvent) -> AsyncIterator[EventT]
Transform a Pydantic AI event into one or more protocol-specific events.
This method dispatches to specific handle_* methods based on event type:
PartStartEvent->handle_part_start()PartDeltaEvent->handle_part_deltaPartEndEvent->handle_part_endFinalResultEvent->handle_final_resultFunctionToolCallEvent->handle_function_tool_callFunctionToolResultEvent->handle_function_tool_resultOutputToolCallEvent->handle_output_tool_callOutputToolResultEvent->handle_output_tool_resultAgentRunResultEvent->handle_run_result
Subclasses are encouraged to override the individual handle_* methods rather than this one.
If you need specific behavior for all events, make sure you call the super method.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
handle_part_start
async
handle_part_start(
event: PartStartEvent,
) -> AsyncIterator[EventT]
Handle a PartStartEvent.
This method dispatches to specific handle_* methods based on part type:
TextPart->handle_text_start()ThinkingPart->handle_thinking_start()ToolCallPart->handle_tool_call_start()NativeToolCallPart->handle_builtin_tool_call_start()NativeToolReturnPart->handle_builtin_tool_return()FilePart->handle_file()CompactionPart->handle_compaction()
Subclasses are encouraged to override the individual handle_* methods rather than this one.
If you need specific behavior for all part start events, make sure you call the super method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
PartStartEvent
|
The part start event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
handle_part_delta
async
handle_part_delta(
event: PartDeltaEvent,
) -> AsyncIterator[EventT]
Handle a PartDeltaEvent.
This method dispatches to specific handle_*_delta methods based on part delta type:
TextPartDelta->handle_text_delta()ThinkingPartDelta->handle_thinking_delta()ToolCallPartDelta->handle_tool_call_delta()
Subclasses are encouraged to override the individual handle_*_delta methods rather than this one.
If you need specific behavior for all part delta events, make sure you call the super method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
PartDeltaEvent
|
The PartDeltaEvent. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
handle_part_end
async
handle_part_end(
event: PartEndEvent,
) -> AsyncIterator[EventT]
Handle a PartEndEvent.
This method dispatches to specific handle_*_end methods based on part type:
TextPart->handle_text_end()ThinkingPart->handle_thinking_end()ToolCallPart->handle_tool_call_end()NativeToolCallPart->handle_builtin_tool_call_end()
Subclasses are encouraged to override the individual handle_*_end methods rather than this one.
If you need specific behavior for all part end events, make sure you call the super method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
PartEndEvent
|
The part end event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
before_stream
async
before_stream() -> AsyncIterator[EventT]
Yield events before agent streaming starts.
This hook is called before any agent events are processed. Override this to inject custom events at the start of the stream.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
425 426 427 428 429 430 431 432 | |
after_stream
async
after_stream() -> AsyncIterator[EventT]
Yield events after agent streaming completes.
This hook is called after all agent events have been processed. Override this to inject custom events at the end of the stream.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
434 435 436 437 438 439 440 441 | |
on_error
async
on_error(error: Exception) -> AsyncIterator[EventT]
Handle errors that occur during streaming.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
Exception
|
The error that occurred during streaming. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
443 444 445 446 447 448 449 450 | |
before_request
async
before_request() -> AsyncIterator[EventT]
Yield events before a model request is processed.
Override this to inject custom events at the start of the request.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
452 453 454 455 456 457 458 | |
after_request
async
after_request() -> AsyncIterator[EventT]
Yield events after a model request is processed.
Override this to inject custom events at the end of the request.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
460 461 462 463 464 465 466 | |
before_response
async
before_response() -> AsyncIterator[EventT]
Yield events before a model response is processed.
Override this to inject custom events at the start of the response.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
468 469 470 471 472 473 474 | |
after_response
async
after_response() -> AsyncIterator[EventT]
Yield events after a model response is processed.
Override this to inject custom events at the end of the response.
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
476 477 478 479 480 481 482 | |
handle_text_start
async
handle_text_start(
part: TextPart, follows_text: bool = False
) -> AsyncIterator[EventT]
Handle the start of a TextPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
TextPart
|
The text part. |
required |
follows_text
|
bool
|
Whether the part is directly preceded by another text part. In this case, you may want to yield a "text-delta" event instead of a "text-start" event. |
False
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
484 485 486 487 488 489 490 491 492 | |
handle_text_delta
async
handle_text_delta(
delta: TextPartDelta,
) -> AsyncIterator[EventT]
Handle a TextPartDelta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
TextPartDelta
|
The text part delta. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
494 495 496 497 498 499 500 501 | |
handle_text_end
async
handle_text_end(
part: TextPart, followed_by_text: bool = False
) -> AsyncIterator[EventT]
Handle the end of a TextPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
TextPart
|
The text part. |
required |
followed_by_text
|
bool
|
Whether the part is directly followed by another text part. In this case, you may not want to yield a "text-end" event yet. |
False
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
503 504 505 506 507 508 509 510 511 | |
handle_thinking_start
async
handle_thinking_start(
part: ThinkingPart, follows_thinking: bool = False
) -> AsyncIterator[EventT]
Handle the start of a ThinkingPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
ThinkingPart
|
The thinking part. |
required |
follows_thinking
|
bool
|
Whether the part is directly preceded by another thinking part. In this case, you may want to yield a "thinking-delta" event instead of a "thinking-start" event. |
False
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
513 514 515 516 517 518 519 520 521 | |
handle_thinking_delta
async
handle_thinking_delta(
delta: ThinkingPartDelta,
) -> AsyncIterator[EventT]
Handle a ThinkingPartDelta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
ThinkingPartDelta
|
The thinking part delta. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
523 524 525 526 527 528 529 530 | |
handle_thinking_end
async
handle_thinking_end(
part: ThinkingPart, followed_by_thinking: bool = False
) -> AsyncIterator[EventT]
Handle the end of a ThinkingPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
ThinkingPart
|
The thinking part. |
required |
followed_by_thinking
|
bool
|
Whether the part is directly followed by another thinking part. In this case, you may not want to yield a "thinking-end" event yet. |
False
|
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
532 533 534 535 536 537 538 539 540 541 542 | |
handle_tool_call_start
async
handle_tool_call_start(
part: ToolCallPart,
) -> AsyncIterator[EventT]
Handle the start of a ToolCallPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
ToolCallPart
|
The tool call part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
544 545 546 547 548 549 550 551 | |
handle_tool_call_delta
async
handle_tool_call_delta(
delta: ToolCallPartDelta,
) -> AsyncIterator[EventT]
Handle a ToolCallPartDelta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
ToolCallPartDelta
|
The tool call part delta. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
553 554 555 556 557 558 559 560 | |
handle_tool_call_end
async
handle_tool_call_end(
part: ToolCallPart,
) -> AsyncIterator[EventT]
Handle the end of a ToolCallPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
ToolCallPart
|
The tool call part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
562 563 564 565 566 567 568 569 | |
handle_builtin_tool_call_start
async
handle_builtin_tool_call_start(
part: NativeToolCallPart,
) -> AsyncIterator[EventT]
Handle a NativeToolCallPart at start.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
NativeToolCallPart
|
The builtin tool call part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
571 572 573 574 575 576 577 578 | |
handle_builtin_tool_call_end
async
handle_builtin_tool_call_end(
part: NativeToolCallPart,
) -> AsyncIterator[EventT]
Handle the end of a NativeToolCallPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
NativeToolCallPart
|
The builtin tool call part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
580 581 582 583 584 585 586 587 | |
handle_builtin_tool_return
async
handle_builtin_tool_return(
part: NativeToolReturnPart,
) -> AsyncIterator[EventT]
Handle a NativeToolReturnPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
NativeToolReturnPart
|
The builtin tool return part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
589 590 591 592 593 594 595 596 | |
handle_file
async
handle_file(part: FilePart) -> AsyncIterator[EventT]
Handle a FilePart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
FilePart
|
The file part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
598 599 600 601 602 603 604 605 | |
handle_compaction
async
handle_compaction(
part: CompactionPart,
) -> AsyncIterator[EventT]
Handle a CompactionPart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
part
|
CompactionPart
|
The compaction part. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
607 608 609 610 611 612 613 614 | |
handle_final_result
async
handle_final_result(
event: FinalResultEvent,
) -> AsyncIterator[EventT]
Handle a FinalResultEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
FinalResultEvent
|
The final result event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
616 617 618 619 620 621 622 623 | |
handle_function_tool_call
async
handle_function_tool_call(
event: FunctionToolCallEvent,
) -> AsyncIterator[EventT]
Handle a FunctionToolCallEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
FunctionToolCallEvent
|
The function tool call event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
625 626 627 628 629 630 631 632 | |
handle_function_tool_result
async
handle_function_tool_result(
event: FunctionToolResultEvent,
) -> AsyncIterator[EventT]
Handle a FunctionToolResultEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
FunctionToolResultEvent
|
The function tool result event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
634 635 636 637 638 639 640 641 | |
handle_output_tool_call
async
handle_output_tool_call(
event: OutputToolCallEvent,
) -> AsyncIterator[EventT]
Handle an OutputToolCallEvent (the model's "submit final answer" call).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
OutputToolCallEvent
|
The output tool call event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
643 644 645 646 647 648 649 650 | |
handle_output_tool_result
async
handle_output_tool_result(
event: OutputToolResultEvent,
) -> AsyncIterator[EventT]
Handle an OutputToolResultEvent (the result of an output tool call).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
OutputToolResultEvent
|
The output tool result event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
652 653 654 655 656 657 658 659 | |
handle_run_result
async
handle_run_result(
event: AgentRunResultEvent,
) -> AsyncIterator[EventT]
Handle an AgentRunResultEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
AgentRunResultEvent
|
The agent run result event. |
required |
Source code in pydantic_ai_slim/pydantic_ai/ui/_event_stream.py
661 662 663 664 665 666 667 668 | |
MessagesBuilder
dataclass
Helper class to build Pydantic AI messages from request/response parts.
Source code in pydantic_ai_slim/pydantic_ai/ui/_messages_builder.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
add
add(part: ModelRequestPart | ModelResponsePart) -> None
Add a new part, creating a new request or response message if necessary.
Source code in pydantic_ai_slim/pydantic_ai/ui/_messages_builder.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |