Skip to main content

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
Synap provides two ways to work with compacted context:
ApproachMethodBest for
Get context for promptget_context_for_prompt()Most integrations: one call, prompt-ready context
Manual compaction controlcompact() + 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 via sdk.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.
The SDK caches the result locally (5-minute TTL), so calling this method on every LLM turn is safe and fast. The response exposes the prompt-ready 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

The style 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

When available 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

Use sdk.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

The CompactionLevel enum exposes seven values: low, medium, high, conservative, balanced, aggressive, and adaptive. The four customer-facing strategies below cover the recommended use cases.
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

ScenarioRecommended Strategy
General-purpose, unsure what to useadaptive
Very long conversations (100+ turns)aggressive with target_tokens
Important conversations, high-value contextconservative
Moderate conversations, cost optimizationbalanced
Dynamic workload with varying conversation lengthsadaptive

CompactionTriggerResponse

The compact() 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

Use sdk.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).
Pay attention to the quality_warning field. When present, it indicates that the compaction may have lost important information. Consider using a less aggressive strategy or increasing target_tokens if quality warnings appear consistently.

Full parameter reference →

Every get_compacted() parameter and CompactionResponse field, with types and defaults.

Checking Compaction Status

Use sdk.conversation.context.get_compaction_status() to check the current compaction state of a conversation without retrieving the full compacted content.
The status response is a CompactionStatusResponse Pydantic model with the following fields:
FieldTypeDescription
conversation_idstrThe conversation this status refers to
statusstrOne of "completed", "in_progress", "failed", or "none" (no compaction yet)
compaction_idOptional[str]ID of the current compaction job, if one exists
completed_atOptional[datetime]When the last successful compaction finished
compression_ratioOptional[float]Compression ratio of the current compaction
validation_scoreOptional[float]Quality score of the current compaction
estimated_completion_secondsOptional[int]If status == "in_progress", approximate seconds remaining
error_messageOptional[str]Populated when status == "failed"
latest_versionOptional[int]Highest version number on record
latest_created_atOptional[datetime]When latest_version was created
To check whether any compaction exists, use status.status != "none". To check whether the compaction is current with the latest messages, fetch get_context_for_prompt and inspect its is_stale field: staleness is a property of the prompt-ready view, not the compaction job itself.

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

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.
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.
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.
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.
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.
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.
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.