Middleware API¶
pydantic_ai_summarization.middleware
¶
Context manager middleware for real-time conversation context management.
This module requires the hybrid extra::
pip install summarization-pydantic-ai[hybrid]
It provides :class:ContextManagerMiddleware, a dual-protocol class that:
- Acts as a pydantic-ai history processor (
__call__): tracks token usage and auto-compresses when approaching the token limit. - Acts as a pydantic-ai-middleware AgentMiddleware (
after_tool_call): optionally truncates large tool outputs inline.
Example::
from pydantic_ai import Agent
from pydantic_ai_middleware import MiddlewareAgent
from pydantic_ai_summarization import (
ContextManagerMiddleware,
create_context_manager_middleware,
)
middleware = create_context_manager_middleware(
max_tokens=200_000,
compress_threshold=0.9,
on_usage_update=lambda pct, cur, mx: print(f"{pct:.0%} used"),
)
agent = Agent("openai:gpt-4.1", history_processors=[middleware])
wrapped = MiddlewareAgent(agent, middleware=[middleware])
UsageCallback = Callable[[float, int, int], Any]
module-attribute
¶
Callback type for usage updates: (percentage, current_tokens, max_tokens).
Supports both sync and async callables. If the callable returns an awaitable, it will be awaited automatically.
ContextManagerMiddleware
dataclass
¶
Bases: AgentMiddleware[Any]
Real-time context management middleware.
Combines token tracking, auto-compression, and optional tool output
truncation. Registered both as a pydantic-ai history_processor
(for per-model-call context management) and as an AgentMiddleware
(for tool output interception).
Attributes:
| Name | Type | Description |
|---|---|---|
max_tokens |
int
|
Maximum token budget for the conversation. |
compress_threshold |
float
|
Fraction of max_tokens at which auto-compression triggers. |
keep |
ContextSize
|
How much context to retain after compression. |
summarization_model |
ModelType
|
Model used for generating summaries. |
token_counter |
TokenCounter
|
Function to count tokens in messages. |
summary_prompt |
str
|
Prompt template for summary generation. |
trim_tokens_to_summarize |
int
|
Max tokens to include when generating the summary. |
max_input_tokens |
int | None
|
Model max input tokens (for fraction-based keep). |
max_tool_output_tokens |
int | None
|
Per-tool-output token limit before truncation. |
tool_output_head_lines |
int
|
Lines from the beginning of truncated output. |
tool_output_tail_lines |
int
|
Lines from the end of truncated output. |
on_usage_update |
UsageCallback | None
|
Callback invoked with usage stats before each model call. |
Source code in src/pydantic_ai_summarization/middleware.py
| Python | |
|---|---|
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 | |
max_tokens = 200000
class-attribute
instance-attribute
¶
Maximum token budget for the conversation.
compress_threshold = 0.9
class-attribute
instance-attribute
¶
Fraction of max_tokens at which auto-compression triggers (0.0, 1.0].
keep = ('messages', 20)
class-attribute
instance-attribute
¶
How much context to retain after compression.
summarization_model = 'openai:gpt-4.1-mini'
class-attribute
instance-attribute
¶
Model used for generating summaries.
Accepts a string model name, a pydantic-ai Model instance, or a KnownModelName literal.
token_counter = field(default=count_tokens_approximately)
class-attribute
instance-attribute
¶
Function to count tokens in messages.
summary_prompt = DEFAULT_SUMMARY_PROMPT
class-attribute
instance-attribute
¶
Prompt template for summary generation.
trim_tokens_to_summarize = 4000
class-attribute
instance-attribute
¶
Max tokens to include when generating the summary.
max_input_tokens = None
class-attribute
instance-attribute
¶
Model max input tokens (required for fraction-based keep).
max_tool_output_tokens = None
class-attribute
instance-attribute
¶
Per-tool-output token limit before truncation. None disables truncation.
tool_output_head_lines = 5
class-attribute
instance-attribute
¶
Lines to show from the beginning of truncated tool output.
tool_output_tail_lines = 5
class-attribute
instance-attribute
¶
Lines to show from the end of truncated tool output.
on_usage_update = None
class-attribute
instance-attribute
¶
Callback invoked with (percentage, current_tokens, max_tokens).
compression_count
property
¶
Number of times compression has been triggered.
__post_init__()
¶
Validate configuration.
Source code in src/pydantic_ai_summarization/middleware.py
__call__(messages)
async
¶
History processor: track usage and auto-compress.
Called by pydantic-ai before every model request within a run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ModelMessage]
|
Current message history. |
required |
Returns:
| Type | Description |
|---|---|
list[ModelMessage]
|
Potentially compressed message history. |
Source code in src/pydantic_ai_summarization/middleware.py
after_tool_call(tool_name, tool_args, result, deps, ctx=None)
async
¶
Middleware hook: optionally truncate large tool outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
Name of the tool that was called. |
required |
tool_args
|
dict[str, Any]
|
Arguments passed to the tool. |
required |
result
|
Any
|
The tool's return value. |
required |
deps
|
Any | None
|
Agent dependencies. |
required |
ctx
|
Any | None
|
Middleware scoped context. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Original or truncated result. |
Source code in src/pydantic_ai_summarization/middleware.py
create_context_manager_middleware(max_tokens=200000, compress_threshold=0.9, keep=('messages', 20), summarization_model='openai:gpt-4.1-mini', token_counter=None, summary_prompt=None, max_tool_output_tokens=None, tool_output_head_lines=5, tool_output_tail_lines=5, on_usage_update=None, max_input_tokens=None)
¶
Create a :class:ContextManagerMiddleware with sensible defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_tokens
|
int
|
Maximum token budget for the conversation. |
200000
|
compress_threshold
|
float
|
Fraction of max_tokens at which auto-compression triggers. |
0.9
|
keep
|
ContextSize
|
How much context to retain after compression. |
('messages', 20)
|
summarization_model
|
ModelType
|
Model used for generating summaries. |
'openai:gpt-4.1-mini'
|
token_counter
|
TokenCounter | None
|
Custom token counter (default: approximate char-based). |
None
|
summary_prompt
|
str | None
|
Custom prompt template for summaries. |
None
|
max_tool_output_tokens
|
int | None
|
Per-tool-output token limit before truncation. |
None
|
tool_output_head_lines
|
int
|
Lines from start of truncated output. |
5
|
tool_output_tail_lines
|
int
|
Lines from end of truncated output. |
5
|
on_usage_update
|
UsageCallback | None
|
Callback for usage updates. |
None
|
max_input_tokens
|
int | None
|
Model max input tokens (for fraction-based keep). |
None
|
Returns:
| Type | Description |
|---|---|
ContextManagerMiddleware
|
Configured ContextManagerMiddleware instance. |