Overview
As conversations grow, the amount of context you need to inject into your LLM’s prompt grows with them. Context compaction solves this by intelligently compressing conversation history while preserving the most important information: facts, decisions, preferences, and key narrative elements. Compaction is particularly valuable when:- Conversations exceed your LLM’s context window
- You want to reduce token costs without losing critical context
- You need to summarize long conversation histories into a concise prompt segment
| Approach | Method | Best for |
|---|---|---|
| Get context for prompt | get_context_for_prompt() | Most integrations: one call, prompt-ready context |
| Manual compaction control | compact() + get_compacted() + get_compaction_status() | Fine-grained control over strategy, token budgets, and timing |
Prerequisites: Recording Messages
Before calling any compaction method, the conversation must have messages recorded viasdk.conversation.record_message(). Calling compact() or get_context_for_prompt() on a conversation with no recorded messages raises a SynapError because no messages have been recorded yet.
conversation_id must be a valid UUID string. Non-UUID strings (e.g. "conv_abc123") are rejected by the server. Use str(uuid.uuid4()) to generate one, or pass a UUID you already manage in your system.Quick Start: Get Context for Your Prompt
For most use cases,get_context_for_prompt() is all you need. It returns the best available compacted context in a single call, pre-formatted for injection into your LLM’s system prompt.
formatted_context string plus metadata you act on: available (whether any compacted context exists), is_stale (newer messages recorded since the last compaction), and quality_warning (validation score below threshold). validation_score, compression_ratio, and compaction_age_seconds are also returned for monitoring and custom staleness thresholds.
Full parameter reference →
Every field on
ContextForPromptResponse, with types and defaults.Formatting Styles
Thestyle parameter is accepted by the SDK ("structured", "narrative", "bullet_points") and will control output formatting in a future backend release. At this stage, all three values return the same raw message content: there is no formatting difference between them yet.
Style-based formatting differentiation is not yet active on the backend. You can safely pass any supported style value: it will take effect automatically once the backend support ships, with no code changes required on your side.
Handling Missing Context
Whenavailable is False, no compacted context exists yet. This happens for new conversations or conversations that haven’t been compacted. You have two options:
Manual Compaction Control
Use these methods when you need fine-grained control over compaction: choosing a strategy, setting token budgets, polling for completion, or retrieving specific versions.Triggering Compaction
Usesdk.conversation.context.compact() to explicitly trigger compaction with specific parameters.
Key parameters.
strategy controls how aggressively the context is compressed (see Strategies below; defaults to "adaptive"). target_tokens sets a desired output size and takes priority over the strategy’s default compression level. force=True skips staleness checks so the conversation re-compacts even if no new memories have been ingested since the last run.Full parameter reference →
Every
compact() parameter, including the compaction_level alias, with types and defaults.Compaction Strategies
TheCompactionLevel enum exposes seven values: low, medium, high, conservative, balanced, aggressive, and adaptive. The four customer-facing strategies below cover the recommended use cases.
- adaptive
- aggressive
- balanced
- conservative
Recommended. Dynamically adjusts compression based on the content. Dense, fact-heavy conversations are compressed less aggressively; repetitive or low-information conversations are compressed more aggressively.
- Typical compression: 30-60% of original tokens
- Preserves: all high-confidence facts, decisions, preferences, key narrative flow
- Drops: repetitive information, low-value conversational filler, redundant context
Strategy Selection Guide
| Scenario | Recommended Strategy |
|---|---|
| General-purpose, unsure what to use | adaptive |
| Very long conversations (100+ turns) | aggressive with target_tokens |
| Important conversations, high-value context | conservative |
| Moderate conversations, cost optimization | balanced |
| Dynamic workload with varying conversation lengths | adaptive |
CompactionTriggerResponse
Thecompact() method kicks off a compaction job asynchronously. It returns a CompactionTriggerResponse confirming the job was accepted, not the compacted content itself. The handle carries a compaction_id (use it with get_compaction_status() to poll progress) and an initial status. To retrieve the compacted output, call get_compacted() once the job completes (see Retrieving Compacted Context below) or poll status via get_compaction_status().
Full parameter reference →
Every field on
CompactionTriggerResponse, including trigger_type, initiated_at, estimated_completion_seconds, and the previous_context returned while a new run completes.Retrieving Compacted Context
Usesdk.conversation.context.get_compacted() to retrieve a previously compacted version of a conversation’s context without triggering a new compaction. This returns the rich CompactionResponse model with the actual compacted text and typed extractions.
Key parameters. Pass
version=None (the default) for the latest compaction, or a specific version number to fetch that run from the cloud (skipping the local cache). format controls the shape of the result: "structured" returns typed facts, decisions, preferences, and current_state lists; "narrative" returns a prose summary in compacted_context; "injection" returns a pre-formatted string for direct prompt injection.get_compacted() returns a CompactionResponse with the compacted text (compacted_context), token counts and compression_ratio, the typed facts / decisions / preferences extractions, and quality signals (validation_score, validation_passed, quality_warning).
Full parameter reference →
Every
get_compacted() parameter and CompactionResponse field, with types and defaults.Checking Compaction Status
Usesdk.conversation.context.get_compaction_status() to check the current compaction state of a conversation without retrieving the full compacted content.
CompactionStatusResponse Pydantic model with the following fields:
| Field | Type | Description |
|---|---|---|
conversation_id | str | The conversation this status refers to |
status | str | One of "completed", "in_progress", "failed", or "none" (no compaction yet) |
compaction_id | Optional[str] | ID of the current compaction job, if one exists |
completed_at | Optional[datetime] | When the last successful compaction finished |
compression_ratio | Optional[float] | Compression ratio of the current compaction |
validation_score | Optional[float] | Quality score of the current compaction |
estimated_completion_seconds | Optional[int] | If status == "in_progress", approximate seconds remaining |
error_message | Optional[str] | Populated when status == "failed" |
latest_version | Optional[int] | Highest version number on record |
latest_created_at | Optional[datetime] | When latest_version was created |
Full parameter reference →
Every field on
CompactionStatusResponse, with types and defaults.Full Examples
Simple: Get Context for Prompt
The recommended approach for most integrations. One call per LLM turn.Advanced: Manual Compaction Control
Use this approach when you need explicit control over compaction strategy and timing.Best Practices
Start with get_context_for_prompt()
Start with get_context_for_prompt()
For most integrations,
get_context_for_prompt() is the right choice. It returns prompt-ready context in a single call, handles local caching automatically, and includes staleness and quality metadata. Only reach for the manual methods (compact(), get_compacted(), get_compaction_status()) when you need explicit control over strategy or token budgets.Combine compacted context with live retrieval
Combine compacted context with live retrieval
Use compacted context for broad historical context and
conversation.context.fetch() for query-specific recent context. This gives your LLM both a comprehensive history and targeted relevant details. Both examples above demonstrate this pattern.Use adaptive strategy as default
Use adaptive strategy as default
The
adaptive strategy automatically selects the right compression level based on content density. It is the safest default for most applications and handles a wide range of conversation lengths and content types.Set target_tokens based on your LLM's context window
Set target_tokens based on your LLM's context window
If your LLM has a 128k token context window and your system prompt uses ~2k tokens plus the user message, you might allocate 4-8k tokens for compacted memory context. Use
target_tokens to enforce this budget.Check is_stale before re-compacting
Check is_stale before re-compacting
Use
get_compaction_status() to avoid unnecessary re-compaction. Only compact when is_stale is True, meaning new memories have been added since the last compaction. This saves processing time and API calls. If you are using get_context_for_prompt(), the is_stale field on the response serves the same purpose.Monitor validation_score
Monitor validation_score
Track
validation_score over time. Consistently low scores (below 0.7) may indicate that your conversations contain highly diverse topics that do not compress well. Consider switching to conservative strategy or increasing target_tokens.Handle quality_warning gracefully
Handle quality_warning gracefully
When
quality_warning is present, log it and consider falling back to a less aggressive strategy. You can implement an automatic fallback pattern:Next Steps
Retrieving Memories
Retrieve context to combine with compacted history.
Ingesting Memories
Ingest new data that triggers compaction staleness.
Context Compaction Concepts
Deep dive into compaction algorithms and architecture.
SDK Configuration
Configure timeouts and retries for compaction operations.