Processor API¶
pydantic_ai_summarization.processor
¶
Summarization history processor for managing conversation context.
DEFAULT_SUMMARY_PROMPT = "<role>\nContext Extraction Assistant\n</role>\n\n<primary_objective>\nExtract the most relevant context from the conversation history below.\n</primary_objective>\n\n<objective_information>\nYou're nearing the token limit and must extract key information. This context will overwrite the conversation history, so include only the most important information.\n</objective_information>\n\n<instructions>\nThe conversation history will be replaced with your extracted context. Extract and record the most important context. Focus on information relevant to the overall goal. Avoid repeating completed actions.\n</instructions>\n\nRead the message history carefully. Think about what is most important to preserve. Extract only essential context.\n\nRespond ONLY with the extracted context. No additional information.\n\n<messages>\nMessages to summarize:\n{messages}\n</messages>"
module-attribute
¶
Default prompt template used for generating summaries.
DEFAULT_CONTINUATION_PROMPT = 'Summary of previous conversation:\n\n'
module-attribute
¶
Default prefix prepended to the summary in the compressed message.
SummarizationProcessor
dataclass
¶
History processor that summarizes conversation when limits are reached.
This processor monitors message token counts and automatically summarizes older messages when a threshold is reached, preserving recent messages and maintaining context continuity.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
ModelType
|
Model to use for generating summaries. |
trigger |
ContextSize | list[ContextSize] | None
|
Threshold(s) that trigger summarization. |
keep |
ContextSize
|
How much context to keep after summarization. |
token_counter |
TokenCounter
|
Function to count tokens in messages. |
summary_prompt |
str
|
Prompt template for generating summaries. |
max_input_tokens |
int | None
|
Maximum input tokens (required for fraction-based triggers). |
trim_tokens_to_summarize |
int | None
|
Maximum tokens to include when generating summary. |
Example
Source code in src/pydantic_ai_summarization/processor.py
| Python | |
|---|---|
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 | |
model
instance-attribute
¶
Model to use for generating summaries.
Accepts a string model name (e.g., "openai:gpt-4.1"), a pydantic-ai
:class:~pydantic_ai.models.Model instance, or a
:data:~pydantic_ai.models.KnownModelName literal.
trigger = None
class-attribute
instance-attribute
¶
Threshold(s) that trigger summarization.
Examples:
- ("messages", 50) - trigger when 50+ messages
- ("tokens", 100000) - trigger when 100k+ tokens
- ("fraction", 0.8) - trigger at 80% of max tokens (requires max_input_tokens)
keep = ('messages', _DEFAULT_MESSAGES_TO_KEEP)
class-attribute
instance-attribute
¶
How much context to keep after summarization.
Examples:
- ("messages", 20) - keep last 20 messages
- ("tokens", 10000) - keep last 10k tokens worth
- ("messages", 0) - summarize everything except the in-flight request
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 generating summaries.
max_input_tokens = None
class-attribute
instance-attribute
¶
Maximum input tokens for the model (required for fraction-based triggers).
trim_tokens_to_summarize = _DEFAULT_TRIM_TOKEN_LIMIT
class-attribute
instance-attribute
¶
Maximum tokens to include when generating summary. None to skip trimming.
__post_init__()
¶
Validate configuration and set up trigger conditions.
plan_compression(messages, *, force=False)
async
¶
Decide whether and where to compress, without running the summary LLM.
The capability can use the returned plan to fire on_before_compress
with the real cutoff index before the LLM call runs. This is a pure
decision step: no network calls, no message mutation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ModelMessage]
|
Current message history. |
required |
force
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
CompressionPlan | None
|
A |
CompressionPlan | None
|
trigger matched (or the cutoff collapsed to 0). |
Source code in src/pydantic_ai_summarization/processor.py
execute_plan(plan, focus=None)
async
¶
Execute a compression plan: run the summary LLM and build the result.
The rebuilt history opens with a single ModelRequest holding the carried-over
system prompts plus the summary as a UserPromptPart, followed by the preserved
tail. The summary is deliberately user-visible so the result always maps to at
least one provider message.
On LLM failure, returns a SummarizationResult with summarized=False
and skip_reason="failed", with messages reconstructed from the plan
(equivalent to the original input). The original history is preserved
rather than partially mutated.
Source code in src/pydantic_ai_summarization/processor.py
process(messages, focus=None, *, force=False)
async
¶
One-shot plan + execute. Returns a structured result.
Use this when you want both the resulting messages and diagnostic metadata (whether compression happened, cutoff index, summary text) in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ModelMessage]
|
Current message history. |
required |
focus
|
str | None
|
Optional focus topic for the summary. |
None
|
force
|
bool
|
Bypass trigger checks (manual compaction). |
False
|
Returns:
| Type | Description |
|---|---|
SummarizationResult
|
|
Source code in src/pydantic_ai_summarization/processor.py
__call__(messages, focus=None)
async
¶
History-processor entry point. Returns the resulting messages only.
Backwards-compatible with pydantic-ai's history_processors contract
((messages) -> messages). Loses the structured metadata — use
process() directly if you need summarized / cutoff_index / summary.
Source code in src/pydantic_ai_summarization/processor.py
create_summarization_processor(model='openai:gpt-4.1', trigger=('tokens', _DEFAULT_TRIGGER_TOKENS), keep=('messages', _DEFAULT_MESSAGES_TO_KEEP), max_input_tokens=None, token_counter=None, summary_prompt=None)
¶
Create a summarization history processor.
This is a convenience factory function for creating SummarizationProcessor instances with sensible defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelType
|
Model to use for generating summaries. Accepts a string name, a Model instance, or a KnownModelName. Defaults to "openai:gpt-4.1". |
'openai:gpt-4.1'
|
trigger
|
ContextSize | list[ContextSize] | None
|
When to trigger summarization. Can be: - ("messages", N) - trigger when N+ messages - ("tokens", N) - trigger when N+ tokens - ("fraction", F) - trigger at F fraction of max_input_tokens - List of tuples to trigger on any condition Defaults to ("tokens", 170000). |
('tokens', _DEFAULT_TRIGGER_TOKENS)
|
keep
|
ContextSize
|
How much context to keep after summarization. Defaults to ("messages", 20). |
('messages', _DEFAULT_MESSAGES_TO_KEEP)
|
max_input_tokens
|
int | None
|
Maximum input tokens (required for fraction-based triggers). |
None
|
token_counter
|
TokenCounter | None
|
Custom token counting function. Defaults to approximate counter. |
None
|
summary_prompt
|
str | None
|
Custom prompt for summarization. Defaults to built-in prompt. |
None
|
Returns:
| Type | Description |
|---|---|
SummarizationProcessor
|
Configured SummarizationProcessor. |
Example
Source code in src/pydantic_ai_summarization/processor.py
count_tokens_approximately(messages)
¶
Approximate token count based on character length.
This is a simple heuristic: ~4 characters per token on average. For production use, consider using a proper tokenizer like tiktoken.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Sequence[ModelMessage]
|
Sequence of messages to count tokens for. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Approximate token count. |
Example
Source code in src/pydantic_ai_summarization/processor.py
format_messages_for_summary(messages)
¶
Format messages into a readable string for summarization.
This function converts a sequence of ModelMessage objects into a human-readable format suitable for passing to an LLM for summarization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Sequence[ModelMessage]
|
Sequence of messages to format. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted string representation of the messages. |
Example
Source code in src/pydantic_ai_summarization/processor.py
Async Token Counting¶
pydantic_ai_summarization._cutoff.async_count_tokens(token_counter, messages)
async
¶
Call a token counter, awaiting if it returns an awaitable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_counter
|
TokenCounter
|
Sync or async token counting function. |
required |
messages
|
Sequence[ModelMessage]
|
Messages to count tokens for. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Token count. |