What this thread does
Do first: Import from pydantic_ai.capabilities import ProcessHistory.
When you need it
The history processor can reduce the context sent to the model. It runs before every model request, including requests after tool calls within the same run.
Steps
1. Define the page's recent-message processor:
from pydantic_ai import Agent, ModelMessage
from pydantic_ai.capabilities import ProcessHistory
async def keep_recent_messages(messages: list[ModelMessage]) -> list[ModelMessage]:
return messages[-5:] if len(messages) > 5 else messages
2. Attach it through the agent's capabilities:
agent = Agent('openai:gpt-6.1-sol', capabilities=[ProcessHistory(keep_recent_messages)])
3. The page illustrates passing an existing history to a run with agent.run_sync('What did we discuss?', message_history=long_conversation_history). Its long_conversation_history: list[ModelMessage] = [] is a placeholder for that history.
Check it worked
The page says only the last five messages are sent to the model, even for a long history. For inspecting messages actually sent, it points to FunctionModel in its history-processor inspection example.
Limits
Processing replaces stored history, including the new user prompt; copy the original if you need to keep it. Splitting a tool pair causes silent repair: orphan results are dropped and missing results receive a synthesized interrupted return. Choose boundaries that retain each relevant call with its result. The page does not name a version.
Not for: UI-server history without duplicate turns; see pydantic-ai-263-ui-server-history-without-duplicate-turns.
Sources
- Message History, Pydantic AI documentation, read 2026-11-24: "Slice on message boundaries that keep each call with its result when the exchange matters."
Checked
2026-11-24; read <https://pydantic.dev/docs/ai/core-concepts/message-history/index.md#keep-only-recent-messages>; no command was run.
Started from a post by @Pydantic, packaged by the editor. Original post