Learning resourcesReviewed · Pydantic

Pydantic AI: Messages and chat history

This Pydantic AI guide teaches Python developers to manage AI conversations, but applications must still control storage and access. It explains message inspection, conversation state, JSON serialization, streaming, history processing and the risks of accepting history from clients.

Researched 23 Nov 2026

In short.

This Pydantic AI guide helps Python developers save and continue AI conversations, but secure storage and user authorization remain application responsibilities. Its central distinction is between passing messages alone and carrying a complete Conversation with accumulated usage and deferred tool requests. It also explains streaming caveats, automatic history repair, provider-specific behavior, agent handoffs and updates during a run. Examples were not executed; deployment reliability, actual costs and security effectiveness were not independently assessed.

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

Covers the complete selected Messages and chat history page at [https://pydantic.dev/docs/ai/core-concepts/message-history/index.md], including streaming notices, instruction framing, request-scoped prompts, serialization, history repair, client-history trust boundaries, persistence, handoffs, enqueue behavior and history processors. The documentation index and all linked pages are excluded. Installation, example execution, live provider behavior, performance and security effectiveness were not assessed. Licensing and actual operating costs are not established.

The overview

Identity

Messages and chat history is a Pydantic AI documentation guide at [https://pydantic.dev/docs/ai/core-concepts/message-history/index.md]. It teaches a framework feature rather than providing a standalone chat application or a separately packaged library.

Its scope extends from reading an agent's messages to storing conversations, accepting client-submitted history, sharing context between agents and changing what a model receives during a run.

Assessment

The guide is useful for developers building chat interfaces, inspecting agent behavior or recovering conversation state. It explains consequential distinctions that a basic chat-loop example can hide: messages are not the entire conversation, provider-valid history is not necessarily trustworthy history, and frontend formats do not preserve every field.

Its practical value is the combination of API examples and explicit failure cases. It requires careful reading for production use because behavior varies by provider, model profile and where conversation state is stored.

Users

Python developers starting with Pydantic AI can use the message-access and two-turn conversation examples. The streaming examples require familiarity with asynchronous Python, while custom processors and capabilities assume comfort with typed functions and framework hooks.

Experienced developers will find material relevant to authenticated chat services, tool approval flows, conversation branching, trace correlation and model switching. People seeking a ready-made user interface or a complete database implementation will need additional resources.

Capabilities

The page documents extracting all messages or only the current run's messages, returning JSON bytes, serializing typed histories and storing complete AgentRunResult values. It explains run_id and conversation_id for correlating activity, plus model_id and model_name for identifying which configured model answered.

It also covers conversation continuation and branching, context sharing between agents and realtime sessions, automatic tool-call pairing repair, and custom history processing before every model request. The enqueue APIs let tools or external code supply additional content during a run, with asap and when_idle delivery priorities.

Using it

Requirements

The examples use the pydantic_ai Python package. Some also import pydantic, pydantic_core, asyncio or pytest. Live examples assume a configured model provider; separate examples use TestModel or FunctionModel.

The page does not establish minimum Python or package versions, installation commands, hardware requirements or provider credential setup. Applications that retain conversations must choose storage and enforce ownership and access themselves. Implementing persistent storage is distinct from serializing a conversation into bytes.

Mechanism

Pydantic AI represents exchanges as ModelRequest and ModelResponse dataclasses containing typed parts. all_messages() includes supplied history and the current run; new_messages() isolates the current run. Passing message_history restores messages, while conversation= also carries accumulated usage, the conversation identifier and deferred tool requests.

Before model requests, the framework adapts history to provider requirements. It can synthesize interrupted results for unanswered tool calls, remove results whose calls are missing and merge compatible adjacent messages. These repairs preserve valid exchanges where possible but do not reconstruct missing real-world results.

Mid-conversation instructions and capability parts are rendered according to the provider. Some use native system messages; others use text frames and attribution notes. The guide explicitly describes these as model guidance rather than proof that content is trustworthy.

Setup

The documented starting point is an Agent configured with a model and instructions. After the first run, pass its result.conversation to the next run to retain the complete conversation state. conversation= cannot be combined with the separate message_history, usage or conversation_id arguments.

For storage, use ConversationTypeAdapter for the conversation bundle or ModelMessagesTypeAdapter when messages alone are sufficient. A frontend's message format is a different boundary and can discard application-only fields. For history submitted by a client, the guide calls for sanitize_messages alongside authentication, caller-specific tools and server-side authorization.

Example

The page demonstrates first = agent.run_sync('Tell me a joke.'), followed by second = agent.run_sync('Explain?', conversation=first.conversation). The second call receives the earlier exchange and accumulated usage. Using only message_history would not carry the usage total automatically.

For streaming, the page reads result.all_messages() before and after consuming stream_text(). The final response appears only after completion. It separately warns that stream_text(delta=True) never assembles the final response string, so that final result message is not added. These are documented examples, not independently reproduced results.

Assessment & evidence

Limitations

Client-submitted history can contain fabricated tool calls and approvals. sanitize_messages removes or resets many sensitive fields, but it does not authenticate the transcript or establish ownership of provider-held state. The page says some response, conversation and container references survive sanitization, requiring additional server-side controls.

History repair is bounded: duplicate results and some provider-specific ordering problems remain outside its general pairing repair. Slicing or summarizing across a tool exchange can cause a result to be dropped or replaced with an interrupted placeholder. History processors replace the stored working history, and unsupported in-place mutation can make request traces inaccurate.

Portability is conditional. UI adapters discard some fields; provider-held state and signed reasoning have endpoint or provider-family restrictions. Request-scoped prompts also have provider-specific exceptions: with openai_conversation_id, a previously sent prompt remains visible in later requests. Prompt framing and special-token handling do not guarantee resistance to malicious instructions.

Reasoning

The strongest reason to use the Conversation bundle is to keep related state together. A transcript can look complete while its accumulated usage or pending tool requirements have been lost. Keeping those values together supports meaningful conversation-wide limits and continuation.

The guide also explains why preserving structure matters: tool calls need their results, cached prefixes depend on stable history, and authorization cannot be inferred from model-facing text. These are documented design arguments, not independently measured reliability or savings.

Alternatives

The page presents several approaches within Pydantic AI. Use message_history for messages alone, Conversation for complete continuation state, and AgentRunResult serialization for a settled run record. Application-managed storage and provider-managed conversation state have different ownership, portability and billing implications.

For context management, ProcessHistory offers a simple processor interface, while before_model_request hooks provide broader control. The page also distinguishes Harness StepPersistence for run recovery, ConversationSearch for retrieving its history and Memory for notes that outlive conversations. It does not establish a comparative ranking against other agent frameworks.

Evidence

The evidence is the complete selected Pydantic AI documentation page at [https://pydantic.dev/docs/ai/core-concepts/message-history/index.md]. It contains API explanations, Python examples, migration caveats and maintainers' measurements of model behavior under different prompt renderings.

Those measurements concern fixed scenarios and include variation and unsuccessful cases. They do not establish expected application-wide success rates or a security guarantee. No code was executed, and no independent performance, integration or security results are available.

Access & freshness

Costs

Actual operating cost is unknown. The page provides no framework price schedule or dependable per-conversation estimate. Cost values in sample output do not establish current provider pricing or expected application costs.

The guide identifies several cost mechanisms: continued conversations can incur charges for earlier input tokens, model-based summarization adds work, framing announcements add prompt text, and rewriting a warm prompt prefix can lose cache savings. Carrying Conversation usage matters when enforcing a budget across turns; passing messages alone starts the usage budget over unless usage is supplied separately. Storage and infrastructure costs are not specified.

Rights

The supplied page states no licence for its documentation or code examples and establishes no redistribution permission. Reuse and redistribution rights are therefore unknown from this evidence.

Descriptions of examples as runnable do not supply licence terms. Model-provider terms, data retention commitments and rights concerning conversation content are also not established by this page.

Freshness

This documentation page was captured on 23 November 2026 at 21:10:59.090 UTC. The capture date does not establish when its features were released or last updated.

The page supplies no package release number or explicit last-updated date. It describes compatibility differences for older serialized multimodal histories without naming the relevant releases. Compatibility with a particular installed version, and changes after this capture, remain unknown.

Actions

For a chat application, begin with the complete Conversation continuation pattern and decide whether state will live on your server or with a provider. Confirm that the documented APIs exist in your installed version. Before adoption, check serialization round trips, accumulated usage, interrupted tool exchanges and the streaming mode your interface uses.

For client-held histories, establish authenticated ownership and caller-specific tools rather than relying on sanitization or prompt labels. Check the page's provider-state precautions for your configuration. If adding pruning or summarization, preserve complete tool exchanges and inspect the actual messages sent to the model; cache outlook and context-window usage can be unknown.

Evidence for this report

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