Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix: surface error when system prompt is large during compaction (#10058)

amysguan63d3146fdca2
diff --git a/fern/openapi.json b/fern/openapi.json
index badd187d8..6132a28a3 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -35321,7 +35321,7 @@
},
"event_type": {
"type": "string",
- "const": "compaction",
+ "enum": ["compaction", "context_warning"],
"title": "Event Type"
},
"event_data": {
diff --git a/letta/agents/letta_agent_v3.py b/letta/agents/letta_agent_v3.py
index b86ef6988..915adae16 100644
--- a/letta/agents/letta_agent_v3.py
+++ b/letta/agents/letta_agent_v3.py
@@ -20,9 +20,17 @@ from letta.agents.helpers import (
merge_and_validate_prefilled_args,
)
from letta.agents.letta_agent_v2 import LettaAgentV2
-from letta.constants import DEFAULT_MAX_STEPS, NON_USER_MSG_PREFIX, REQUEST_HEARTBEAT_PARAM
+from letta.constants import (
+ DEFAULT_MAX_STEPS,
+ NON_USER_MSG_PREFIX,
+ REQUEST_HEARTBEAT_PARAM,
+ SHOULD_EMIT_SYSTEM_PROMPT_WARNING,
+ SYSTEM_PROMPT_WARNING_THRESHOLD,
+)
from letta.errors import (
ContextWindowExceededError,
+ LargeSystemPromptAndToolsError,
+ LargeSystemPromptError,
LLMEmptyResponseError,
LLMError,
LLMProviderOverloaded,
@@ -65,13 +73,14 @@ from letta.server.rest_api.utils import (
create_parallel_tool_messages_from_llm_response,
create_tool_returns_for_denials,
)
+from letta.services.context_window_calculator.token_counter import create_token_counter
from letta.services.conversation_manager import ConversationManager
from letta.services.helpers.tool_parser_helper import runtime_override_tool_json_schema
from letta.services.llm_router import get_llm_routing_client
from letta.services.provider_manager import AUTO_MODE_HANDLES
from letta.services.summarizer.compact import compact_messages
+from letta.services.summarizer.constants import COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN
from letta.services.summarizer.summarizer_config import CompactionSettings
-from letta.services.summarizer.summarizer_sliding_window import count_tokens
from letta.services.summarizer.thresholds import get_compaction_trigger_threshold
from letta.settings import settings, summarizer_settings
from letta.system import package_function_response
@@ -139,6 +148,8 @@ class LettaAgentV3(LettaAgentV2):
# Multi-turn token tracking for RL training (accumulated across all LLM calls)
self.turns: list[TurnTokenData] = []
self.return_token_ids: bool = False
+ # Track which run_ids have already emitted a context warning event.
+ self._context_warning_emitted_run_ids: set[str] = set()
def _compute_tool_return_truncation_chars(self) -> int:
"""Compute a dynamic cap for tool returns in requests.
@@ -663,19 +674,20 @@ class LettaAgentV3(LettaAgentV2):
yield f"data: {self.stop_reason.model_dump_json()}\n\n"
# Mid-stream error: yield error event to client in SSE format
- user_visible_error_message = "An error occurred during agent execution."
error_type = "internal_error"
- if isinstance(e, SystemPromptTokenExceededError):
+
+ if (
+ isinstance(e, SystemPromptTokenExceededError)
+ or isinstance(e, LargeSystemPromptError)
+ or isinstance(e, LargeSystemPromptAndToolsError)
+ ):
+ # error detail already includes message + detail for ContextWindowExceededError types
error_type = StopReasonType.context_window_overflow_in_system_prompt.value
- user_visible_error_message = (
- "Compaction failed because the system prompt is too large for this model's context window. "
- "Reduce system instructions, memory blocks, or tools, or use a model with a larger context window."
- )
error_message = LettaErrorMessage(
run_id=run_id,
error_type=error_type,
- message=user_visible_error_message,
+ message="An error occurred during agent execution.",
detail=error_detail,
)
yield f"event: error\ndata: {error_message.model_dump_json()}\n\n"
@@ -732,23 +744,6 @@ class LettaAgentV3(LettaAgentV2):
# Ensure adapter resources (e.g. WebSocket connections) are cleaned up
await llm_adapter.aclose()
- async def _check_for_system_prompt_overflow(self, system_message):
- """
- Since the system prompt cannot be compacted, we need to check to see if it is the cause of the context overflow
- """
- system_prompt_token_estimate = await count_tokens(
- actor=self.actor,
- llm_config=self.agent_state.llm_config,
- messages=[system_message],
- )
- if system_prompt_token_estimate is not None and system_prompt_token_estimate >= self.agent_state.llm_config.context_window:
- self.should_continue = False
- self.stop_reason = LettaStopReason(stop_reason=StopReasonType.context_window_overflow_in_system_prompt.value)
- raise SystemPromptTokenExceededError(
- system_prompt_token_estimate=system_prompt_token_estimate,
- context_window=self.agent_state.llm_config.context_window,
- )
-
async def _checkpoint_messages(self, run_id: str, step_id: str, new_messages: list[Message], in_context_messages: list[Message]):
"""
Checkpoint the current message state - run this only when the current messages are 'safe' - meaning the step has completed successfully.
@@ -839,6 +834,35 @@ class LettaAgentV3(LettaAgentV2):
step_id=step_id,
)
+ def _create_context_warning_event_message(
+ self,
+ step_id: str | None,
+ run_id: str | None,
+ *,
+ system_prompt_token_estimate: int,
+ context_window: int,
+ threshold: int,
+ ) -> EventMessage:
+ """Create an EventMessage for large system prompt context warnings."""
+ msg = EventMessage(
+ id=str(uuid.uuid4()),
+ date=get_utc_time(),
+ event_type="context_warning",
+ event_data={
+ "kind": "large_system_prompt",
+ "system_tokens_estimate": system_prompt_token_estimate,
+ "context_window": context_window,
+ "threshold": threshold,
+ "message": (
+ "System prompt is large and is reducing available context. Consider running /doctor to clean up system memory."
+ ),
+ },
+ run_id=run_id,
+ step_id=step_id,
+ )
+
+ return msg
+
def _create_summary_result_message(
self,
summary_message: Message,
@@ -1079,6 +1103,30 @@ class LettaAgentV3(LettaAgentV2):
active_llm_client = self.llm_client
force_tool_call = valid_tools[0]["name"] if len(valid_tools) == 1 and self._require_tool_call else None
+
+ ### TODO: toggle this to true once we have memory /doctor
+ if SHOULD_EMIT_SYSTEM_PROMPT_WARNING:
+ # Pre-LLM context warning: large system prompt may reduce available context.
+ approx_counter = create_token_counter(safety_margin=COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN)
+ system_prompt_token_estimate = await approx_counter.count_system_prompt_tokens(messages)
+
+ should_emit_context_warning = ( # include_compaction_messages and
+ system_prompt_token_estimate >= SYSTEM_PROMPT_WARNING_THRESHOLD
+ and (run_id is None or run_id not in self._context_warning_emitted_run_ids)
+ )
+
+ if should_emit_context_warning:
+ if run_id is not None:
+ self._context_warning_emitted_run_ids.add(run_id)
+
+ yield self._create_context_warning_event_message(
+ step_id=step_id,
+ run_id=run_id,
+ system_prompt_token_estimate=system_prompt_token_estimate,
+ context_window=active_llm_config.context_window,
+ threshold=SYSTEM_PROMPT_WARNING_THRESHOLD,
+ )
+
for llm_request_attempt in range(summarizer_settings.max_summarizer_retries + 1):
try:
request_data = active_llm_client.build_request_data(
@@ -1266,12 +1314,12 @@ class LettaAgentV3(LettaAgentV2):
yield msg
continue
- except SystemPromptTokenExceededError:
+ except (SystemPromptTokenExceededError, LargeSystemPromptError, LargeSystemPromptAndToolsError) as e:
self.should_continue = False
self.stop_reason = LettaStopReason(
stop_reason=StopReasonType.context_window_overflow_in_system_prompt.value
)
- raise
+ raise e
except Exception as e:
self.stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)
self.logger.error(f"Unknown error occured for summarization run {run_id}: {e}")
@@ -1487,10 +1535,10 @@ class LettaAgentV3(LettaAgentV2):
new_messages=[summary_message],
in_context_messages=messages,
)
- except SystemPromptTokenExceededError:
+ except (SystemPromptTokenExceededError, LargeSystemPromptError, LargeSystemPromptAndToolsError) as e:
self.should_continue = False
self.stop_reason = LettaStopReason(stop_reason=StopReasonType.context_window_overflow_in_system_prompt.value)
- raise
+ raise e
except Exception as e:
caught_exception = e
diff --git a/letta/constants.py b/letta/constants.py
index 126d12855..84593942c 100644
--- a/letta/constants.py
+++ b/letta/constants.py
@@ -532,3 +532,7 @@ DEFAULT_GENERATE_TOOL_MODEL_HANDLE = "openai/gpt-4.1"
# Reserved keyword arguments that are injected by the system into tool functions, not provided by the LLM
# These parameters are excluded from tool schema generation
TOOL_RESERVED_KWARGS = ["self", "agent_state"]
+
+SHOULD_EMIT_SYSTEM_PROMPT_WARNING = True
+SYSTEM_PROMPT_WARNING_THRESHOLD = 30000
+SYSTEM_PROMPT_TOO_LARGE_THRESHOLD = 0.8
diff --git a/letta/errors.py b/letta/errors.py
index c03bcab08..467abfb67 100644
--- a/letta/errors.py
+++ b/letta/errors.py
@@ -352,12 +352,37 @@ class SystemPromptTokenExceededError(ContextWindowExceededError):
"""Error raised when the system prompt token estimate exceeds the context window."""
def __init__(self, system_prompt_token_estimate: int, context_window: int):
- message = f"The system prompt tokens {system_prompt_token_estimate} exceeds the context window {context_window}. Please reduce the size of your system prompt, memory blocks, or increase the context window."
+ message = f"The system prompt tokens {system_prompt_token_estimate} exceeds the context window {context_window}. Please reduce the size of your system prompt, memory blocks, or increase the context window. You may also try recompiling the system prompt with /recompile."
super().__init__(
message=message, details={"system_prompt_token_estimate": system_prompt_token_estimate, "context_window": context_window}
)
+class LargeSystemPromptError(ContextWindowExceededError):
+ """Error raised when the system prompt is larger than a maximum threshold (but not exceeding the context window yet)."""
+
+ def __init__(self, system_prompt_token_estimate: int, context_window: int):
+ message = f"Compaction cannot effectively reduce the context window. The system prompt is extremely large ({system_prompt_token_estimate} tokens compared to {context_window} context window). Please reduce the size of your system prompt, memory blocks, or increase the context window. You may also try recompiling the system prompt with /recompile."
+ super().__init__(
+ message=message, details={"system_prompt_token_estimate": system_prompt_token_estimate, "context_window": context_window}
+ )
+
+
+class LargeSystemPromptAndToolsError(ContextWindowExceededError):
+ """Error raised when the system prompt + tools are larger than a maximum threshold (but not exceeding the context window yet)."""
+
+ def __init__(self, system_prompt_token_estimate: int, tools_token_estimate: int, context_window: int):
+ message = f"Compaction cannot effectively reduce the context window. The system prompt ({system_prompt_token_estimate}) + tools ({tools_token_estimate}) tokens are extremely large (compared to {context_window} context window). Please reduce the size of your system prompt, memory blocks, tools, or increase the context window. You may also try recompiling the system prompt with /recompile."
+ super().__init__(
+ message=message,
+ details={
+ "system_prompt_token_estimate": system_prompt_token_estimate,
+ "tools_token_estimate": tools_token_estimate,
+ "context_window": context_window,
+ },
+ )
+
+
class RateLimitExceededError(LettaError):
"""Error raised when the llm rate limiter throttles api requests."""
diff --git a/letta/schemas/letta_message.py b/letta/schemas/letta_message.py
index 1482e13c5..cb533511b 100644
--- a/letta/schemas/letta_message.py
+++ b/letta/schemas/letta_message.py
@@ -448,7 +448,7 @@ class EventMessage(LettaMessage):
"""
message_type: Literal["event_message"] = "event_message"
- event_type: Literal["compaction"]
+ event_type: Literal["compaction", "context_warning"]
event_data: dict
diff --git a/letta/services/context_window_calculator/token_counter.py b/letta/services/context_window_calculator/token_counter.py
index 7cbbd6a9c..383c3795e 100644
--- a/letta/services/context_window_calculator/token_counter.py
+++ b/letta/services/context_window_calculator/token_counter.py
@@ -37,6 +37,70 @@ class TokenCounter(ABC):
def convert_messages(self, messages: List[Any]) -> List[Dict[str, Any]]:
"""Convert messages to the appropriate format for this counter"""
+ @staticmethod
+ def extract_system_prompt_text(messages: List[Any]) -> str | None:
+ """Extract system prompt text from the first message (index 0).
+
+ Handles TextContent parts, falls back to JSON serialization of content,
+ then to None if messages is empty.
+ """
+ from letta.schemas.letta_message_content import TextContent
+
+ if not messages:
+ return None
+ first_message = messages[0]
+ if not first_message or not first_message.content:
+ return None
+ text_parts = [part.text for part in first_message.content if isinstance(part, TextContent) and part.text]
+ if text_parts:
+ return "\n".join(text_parts)
+ # Fallback: deterministic string representation for non-TextContent parts
+ return json.dumps(
+ [part.model_dump(mode="json") if hasattr(part, "model_dump") else str(part) for part in first_message.content],
+ ensure_ascii=False,
+ )
+
+ async def count_system_prompt_tokens(self, messages: List[Any]) -> int:
+ """Extract system prompt text from messages[0] and count its tokens."""
+ text = self.extract_system_prompt_text(messages)
+ if not text:
+ return 0
+ return await self.count_text_tokens(text)
+
+ async def count_messages_with_tools(self, messages: List[Any], tools: List[Any] | None = None) -> int:
+ """Count tokens in messages and tool definitions combined.
+
+ Converts messages, normalizes tools, and returns the total token count.
+ """
+ converted = self.convert_messages(messages)
+ msg_tokens = await self.count_message_tokens(converted)
+ if not tools:
+ return msg_tokens
+ tool_defs = self.normalize_tool_definitions(tools)
+ tool_tokens = await self.count_tool_tokens(tool_defs) if tool_defs else 0
+ return msg_tokens + tool_tokens
+
+ @staticmethod
+ def normalize_tool_definitions(tools: List[Any]) -> List["OpenAITool"]:
+ """Normalize Tool objects or raw dicts into OpenAI function tool definitions.
+
+ Accepts:
+ - Tool schema objects (with .json_schema attribute)
+ - Raw dicts (already a function schema)
+ - OpenAI FunctionTool objects (passed through as-is)
+ """
+ from openai.types.beta.function_tool import FunctionTool as OpenAIFnTool
+
+ result = []
+ for t in tools:
+ if isinstance(t, OpenAIFnTool):
+ result.append(t)
+ elif hasattr(t, "json_schema") and t.json_schema:
+ result.append(OpenAIFnTool(type="function", function=t.json_schema))
+ elif isinstance(t, dict) and t:
+ result.append(OpenAIFnTool(type="function", function=t))
+ return result
+
class AnthropicTokenCounter(TokenCounter):
"""Token counter using Anthropic's API"""
@@ -96,16 +160,20 @@ class ApproxTokenCounter(TokenCounter):
APPROX_BYTES_PER_TOKEN = 4
- def __init__(self, model: str | None = None):
+ def __init__(self, model: str | None = None, safety_margin: float = 1.0):
# Model is optional since we don't actually use a tokenizer
self.model = model
+ self.safety_margin = safety_margin
def _approx_token_count(self, text: str) -> int:
- """Approximate token count: ceil(byte_len / 4)"""
+ """Approximate token count: ceil(byte_len / 4), with optional safety margin."""
if not text:
return 0
byte_len = len(text.encode("utf-8"))
- return (byte_len + self.APPROX_BYTES_PER_TOKEN - 1) // self.APPROX_BYTES_PER_TOKEN
+ raw = (byte_len + self.APPROX_BYTES_PER_TOKEN - 1) // self.APPROX_BYTES_PER_TOKEN
+ if self.safety_margin != 1.0:
+ return int(raw * self.safety_margin)
+ return raw
async def count_text_tokens(self, text: str) -> int:
if not text:
@@ -266,17 +334,28 @@ class TiktokenCounter(TokenCounter):
def create_token_counter(
- model_endpoint_type: ProviderType,
+ model_endpoint_type: Optional[ProviderType] = None,
model: Optional[str] = None,
actor: "User" = None,
agent_id: Optional[str] = None,
+ safety_margin: float = 1.0,
) -> "TokenCounter":
"""
Factory function to create the appropriate token counter based on model configuration.
+ When called with no arguments, returns an ApproxTokenCounter.
+
+ Args:
+ safety_margin: Multiplier applied to ApproxTokenCounter estimates (default 1.0, no adjustment).
+ The bytes/4 heuristic underestimates by ~25-35% for JSON-heavy content; pass 1.3
+ for compaction/summarization where overestimating is safer.
+
Returns:
The appropriate TokenCounter instance
"""
+ if model_endpoint_type is None:
+ return ApproxTokenCounter(safety_margin=safety_margin)
+
from letta.llm_api.llm_client import LLMClient
from letta.settings import settings
@@ -306,7 +385,7 @@ def create_token_counter(
f"environment={settings.environment}"
)
else:
- token_counter = ApproxTokenCounter()
+ token_counter = ApproxTokenCounter(safety_margin=safety_margin)
logger.debug(
f"Using ApproxTokenCounter for agent_id={agent_id}, model={model}, "
f"model_endpoint_type={model_endpoint_type}, "
diff --git a/letta/services/streaming_service.py b/letta/services/streaming_service.py
index 0f0261d1a..8df59b5a2 100644
--- a/letta/services/streaming_service.py
+++ b/letta/services/streaming_service.py
@@ -14,6 +14,8 @@ from letta.agents.base_agent_v2 import BaseAgentV2
from letta.constants import REDIS_RUN_ID_PREFIX
from letta.data_sources.redis_client import NoopAsyncRedisClient, get_redis_client
from letta.errors import (
+ LargeSystemPromptAndToolsError,
+ LargeSystemPromptError,
LettaInvalidArgumentError,
LettaServiceUnavailableError,
LLMAuthenticationError,
@@ -579,23 +581,19 @@ class StreamingService:
yield f"event: error\ndata: {error_message.model_dump_json()}\n\n"
# Send [DONE] marker to properly close the stream
yield "data: [DONE]\n\n"
- except SystemPromptTokenExceededError as e:
+ except (SystemPromptTokenExceededError, LargeSystemPromptError, LargeSystemPromptAndToolsError) as e:
run_status = RunStatus.failed
stop_reason = LettaStopReason(stop_reason=StopReasonType.context_window_overflow_in_system_prompt)
error_detail = str(e) or repr(e)
error_message = LettaErrorMessage(
run_id=run_id,
error_type=StopReasonType.context_window_overflow_in_system_prompt.value,
- message=(
- "Compaction failed because the system prompt is too large for this model's context window. "
- "Reduce system instructions, memory blocks, or tools, or use a model with a larger context window."
- ),
+ message=e.message
+ if e.message
+ else "The system prompt and/or tools are too large for this model's context window. Reduce system instructions, memory blocks, or tools, or use a model with a larger context window.",
detail=error_detail,
)
- error_data = {"error": error_message.model_dump()}
- logger.warning(
- f"Run {run_id} stopped with system prompt overflow: {error_detail}, error_data: {error_message.model_dump()}"
- )
+ logger.warning(f"Run {run_id} stopped with system prompt overflow: {error_detail}")
yield f"data: {stop_reason.model_dump_json()}\n\n"
yield f"event: error\ndata: {error_message.model_dump_json()}\n\n"
# Send [DONE] marker to properly close the stream
diff --git a/letta/services/summarizer/compact.py b/letta/services/summarizer/compact.py
index 46b53c14a..bef55c986 100644
--- a/letta/services/summarizer/compact.py
+++ b/letta/services/summarizer/compact.py
@@ -3,7 +3,8 @@
from dataclasses import dataclass
from typing import List, Optional
-from letta.errors import ContextWindowExceededError
+from letta.constants import SYSTEM_PROMPT_TOO_LARGE_THRESHOLD
+from letta.errors import ContextWindowExceededError, LargeSystemPromptAndToolsError, LargeSystemPromptError, SystemPromptTokenExceededError
from letta.helpers.message_helper import convert_message_creates_to_messages
from letta.llm_api.llm_client import LLMClient
from letta.log import get_logger
@@ -15,14 +16,12 @@ from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message, MessageCreate
from letta.schemas.provider_trace import BillingContext
from letta.schemas.user import User
+from letta.services.context_window_calculator.token_counter import TokenCounter, create_token_counter
+from letta.services.summarizer.constants import COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN
from letta.services.summarizer.self_summarizer import self_summarize_all, self_summarize_sliding_window
from letta.services.summarizer.summarizer_all import summarize_all
from letta.services.summarizer.summarizer_config import CompactionSettings, get_default_prompt_for_mode, get_default_summarizer_model
-from letta.services.summarizer.summarizer_sliding_window import (
- count_tokens,
- count_tokens_with_tools,
- summarize_via_sliding_window,
-)
+from letta.services.summarizer.summarizer_sliding_window import summarize_via_sliding_window
from letta.services.telemetry_manager import TelemetryManager
from letta.system import package_summarize_message_no_counts
@@ -192,6 +191,17 @@ async def compact_messages(
CompactResult containing the summary message, compacted messages, summary text,
and updated context token estimate.
"""
+ # Precheck: if system prompt is too large, raise an error before attempting compaction
+ # Uses heuristic (doesn't pass in model/provider) for latency reasons
+ approx_counter = create_token_counter(safety_margin=COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN)
+ system_prompt_token_estimate = await approx_counter.count_system_prompt_tokens(messages)
+
+ if trigger_threshold is not None and system_prompt_token_estimate is not None and system_prompt_token_estimate >= trigger_threshold:
+ raise LargeSystemPromptError(
+ system_prompt_token_estimate=system_prompt_token_estimate,
+ context_window=agent_llm_config.context_window,
+ )
+
summarizer_config = compaction_settings if compaction_settings else CompactionSettings()
# Build the LLMConfig used for summarization
@@ -362,13 +372,16 @@ async def compact_messages(
else:
raise ValueError(f"Invalid summarizer mode: {summarizer_config.mode}")
- # Update the token count (including tools for accurate comparison with LLM's prompt_tokens)
- context_token_estimate = await count_tokens_with_tools(
+ # Create a token counter for post-compaction estimates
+ token_counter = create_token_counter(
+ model_endpoint_type=agent_llm_config.model_endpoint_type,
+ model=agent_llm_config.model,
actor=actor,
- llm_config=agent_llm_config,
- messages=compacted_messages,
- tools=tools or [],
+ safety_margin=COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN,
)
+
+ # Update the token count (including tools for accurate comparison with LLM's prompt_tokens)
+ context_token_estimate = await token_counter.count_messages_with_tools(compacted_messages, tools or [])
logger.info(f"Context token estimate after summarization: {context_token_estimate}")
# If the trigger_threshold is provided, verify the new token count is below it
@@ -395,24 +408,15 @@ async def compact_messages(
)
summarization_mode_used = "all"
- context_token_estimate = await count_tokens_with_tools(
- actor=actor,
- llm_config=agent_llm_config,
- messages=compacted_messages,
- tools=tools or [],
- )
+ context_token_estimate = await token_counter.count_messages_with_tools(compacted_messages, tools or [])
# Final edge case: check if we're still over threshold
if context_token_estimate is not None and context_token_estimate >= trigger_threshold:
+ # These checks use a more realistic token counter than the system prompt precheck (for anthropic/openai/gemini/etc.)
# Check if system prompt is the cause
- system_prompt_token_estimate = await count_tokens(
- actor=actor,
- llm_config=agent_llm_config,
- messages=[compacted_messages[0]],
- )
+ system_prompt_token_estimate = await token_counter.count_system_prompt_tokens(compacted_messages)
+ # System prompt exceeds context window
if system_prompt_token_estimate is not None and system_prompt_token_estimate >= agent_llm_config.context_window:
- from letta.errors import SystemPromptTokenExceededError
-
logger.warning(
f"System prompt ({system_prompt_token_estimate} tokens) exceeds context window ({agent_llm_config.context_window})"
)
@@ -421,8 +425,39 @@ async def compact_messages(
context_window=agent_llm_config.context_window,
)
- # Log error but don't brick the agent
- logger.critical(f"Failed to summarize messages after fallback: {context_token_estimate} > {trigger_threshold}")
+ # System prompt + tools are large but not exceeding the context window
+ if (
+ system_prompt_token_estimate is not None
+ and system_prompt_token_estimate >= SYSTEM_PROMPT_TOO_LARGE_THRESHOLD * agent_llm_config.context_window
+ ):
+ logger.warning(
+ f"System prompt is large ({system_prompt_token_estimate} tokens, context window {agent_llm_config.context_window}). Failed to reduce context window during compaction: {context_token_estimate} > {trigger_threshold}."
+ )
+
+ raise LargeSystemPromptError(
+ system_prompt_token_estimate=system_prompt_token_estimate,
+ context_window=agent_llm_config.context_window,
+ )
+
+ tool_defs = TokenCounter.normalize_tool_definitions(tools or [])
+ tools_token_estimate = await token_counter.count_tool_tokens(tool_defs) if tool_defs else 0
+ if (
+ tools_token_estimate is not None
+ and system_prompt_token_estimate is not None
+ and tools_token_estimate + system_prompt_token_estimate
+ >= SYSTEM_PROMPT_TOO_LARGE_THRESHOLD * agent_llm_config.context_window
+ ):
+ logger.warning(
+ f"System prompt ({system_prompt_token_estimate} tokens) + tools ({tools_token_estimate} tokens) are large (context window {agent_llm_config.context_window}). Failed to reduce context window during compaction: {context_token_estimate} > {trigger_threshold}."
+ )
+ raise LargeSystemPromptAndToolsError(
+ system_prompt_token_estimate=system_prompt_token_estimate,
+ tools_token_estimate=tools_token_estimate,
+ context_window=agent_llm_config.context_window,
+ )
+ else:
+ # Log error but don't brick the agent
+ logger.critical(f"Failed to summarize messages after fallback: {context_token_estimate} > {trigger_threshold}")
else:
logger.info(f"Summarization fallback succeeded: {context_token_estimate} < {trigger_threshold}")
diff --git a/letta/services/summarizer/constants.py b/letta/services/summarizer/constants.py
index 122152a61..d00ec8462 100644
--- a/letta/services/summarizer/constants.py
+++ b/letta/services/summarizer/constants.py
@@ -1,3 +1,4 @@
"""Shared constants for summarization services."""
SUMMARY_TRUNCATION_SUFFIX = "... [summary truncated to fit]"
+COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN = 1.3
diff --git a/letta/services/summarizer/self_summarizer.py b/letta/services/summarizer/self_summarizer.py
index b411af2d4..756959515 100644
--- a/letta/services/summarizer/self_summarizer.py
+++ b/letta/services/summarizer/self_summarizer.py
@@ -12,9 +12,9 @@ from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message
from letta.schemas.provider_trace import BillingContext
from letta.schemas.user import User
-from letta.services.summarizer.constants import SUMMARY_TRUNCATION_SUFFIX
+from letta.services.context_window_calculator.token_counter import create_token_counter
+from letta.services.summarizer.constants import COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN, SUMMARY_TRUNCATION_SUFFIX
from letta.services.summarizer.summarizer_config import CompactionSettings, get_default_prompt_for_mode
-from letta.services.summarizer.summarizer_sliding_window import count_tokens
from letta.services.telemetry_manager import TelemetryManager
logger = get_logger(__name__)
@@ -223,7 +223,14 @@ async def self_summarize_sliding_window(
# update token count
logger.info(f"Attempting to compact messages to index {assistant_message_index} messages")
post_summarization_buffer = list(messages[assistant_message_index:])
- approx_token_count = await count_tokens(actor, agent_llm_config, [system_prompt, *post_summarization_buffer])
+ token_counter = create_token_counter(
+ model_endpoint_type=agent_llm_config.model_endpoint_type,
+ model=agent_llm_config.model,
+ actor=actor,
+ safety_margin=COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN,
+ )
+ converted = token_counter.convert_messages([system_prompt, *post_summarization_buffer])
+ approx_token_count = await token_counter.count_message_tokens(converted)
logger.info(
f"Compacting messages index 1:{assistant_message_index} messages resulted in {approx_token_count} tokens, goal is {goal_tokens}"
)
diff --git a/letta/services/summarizer/summarizer_sliding_window.py b/letta/services/summarizer/summarizer_sliding_window.py
index a04f70cb4..8f37c83bc 100644
--- a/letta/services/summarizer/summarizer_sliding_window.py
+++ b/letta/services/summarizer/summarizer_sliding_window.py
@@ -1,7 +1,4 @@
-from typing import TYPE_CHECKING, List, Optional, Tuple
-
-if TYPE_CHECKING:
- from letta.schemas.tool import Tool
+from typing import List, Optional, Tuple
from letta.log import get_logger
from letta.otel.tracing import trace_method
@@ -11,90 +8,13 @@ from letta.schemas.message import Message
from letta.schemas.provider_trace import BillingContext
from letta.schemas.user import User
from letta.services.context_window_calculator.token_counter import create_token_counter
-from letta.services.summarizer.constants import SUMMARY_TRUNCATION_SUFFIX
+from letta.services.summarizer.constants import COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN, SUMMARY_TRUNCATION_SUFFIX
from letta.services.summarizer.summarizer import simple_summary
from letta.services.summarizer.summarizer_config import CompactionSettings
logger = get_logger(__name__)
-# Safety margin for approximate token counting.
-# The bytes/4 heuristic underestimates by ~25-35% for JSON-serialized messages
-# due to structural overhead (brackets, quotes, colons) each becoming tokens.
-APPROX_TOKEN_SAFETY_MARGIN = 1.3
-
-
-async def count_tokens(actor: User, llm_config: LLMConfig, messages: List[Message]) -> int:
- """Count tokens in messages using the appropriate token counter for the model configuration."""
- token_counter = create_token_counter(
- model_endpoint_type=llm_config.model_endpoint_type,
- model=llm_config.model,
- actor=actor,
- )
- converted_messages = token_counter.convert_messages(messages)
- tokens = await token_counter.count_message_tokens(converted_messages)
-
- # Apply safety margin for approximate counting to avoid underestimating
- from letta.services.context_window_calculator.token_counter import ApproxTokenCounter
-
- if isinstance(token_counter, ApproxTokenCounter):
- return int(tokens * APPROX_TOKEN_SAFETY_MARGIN)
- return tokens
-
-
-async def count_tokens_with_tools(
- actor: User,
- llm_config: LLMConfig,
- messages: List[Message],
- tools: Optional[List["Tool"]] = None,
-) -> int:
- """Count tokens in messages AND tool definitions.
-
- This provides a more accurate context token count by including tool definitions,
- which are sent to the LLM but not included in the messages list.
-
- Args:
- actor: The user making the request.
- llm_config: The LLM configuration for selecting the appropriate tokenizer.
- messages: The in-context messages (including system message).
- tools: Optional list of Tool objects. If provided, their schemas are counted.
-
- Returns:
- Total token count for messages + tools.
- """
- # Delegate message counting to existing function
- message_tokens = await count_tokens(actor, llm_config, messages)
-
- if not tools:
- return message_tokens
-
- # Count tools
- from openai.types.beta.function_tool import FunctionTool as OpenAITool
-
- from letta.services.context_window_calculator.token_counter import ApproxTokenCounter
-
- token_counter = create_token_counter(
- model_endpoint_type=llm_config.model_endpoint_type,
- model=llm_config.model,
- actor=actor,
- )
-
- # Tools can be either Tool objects (with .json_schema) or dicts (json schemas directly)
- # For compatibility with how tools need to be passed in for self compaction
- tool_definitions = [
- OpenAITool(type="function", function=t.json_schema if hasattr(t, "json_schema") else t)
- for t in tools
- if (hasattr(t, "json_schema") and t.json_schema) or (isinstance(t, dict) and t)
- ]
- tool_tokens = await token_counter.count_tool_tokens(tool_definitions) if tool_definitions else 0
-
- # Apply safety margin for approximate counting (message_tokens already has margin applied)
- if isinstance(token_counter, ApproxTokenCounter):
- tool_tokens = int(tool_tokens * APPROX_TOKEN_SAFETY_MARGIN)
-
- return message_tokens + tool_tokens
-
-
@trace_method
async def summarize_via_sliding_window(
# Required to tag LLM calls
@@ -185,7 +105,14 @@ async def summarize_via_sliding_window(
# update token count
logger.info(f"Attempting to compact messages index 1:{assistant_message_index} messages")
post_summarization_buffer = [system_prompt, *in_context_messages[assistant_message_index:]]
- approx_token_count = await count_tokens(actor, agent_llm_config, post_summarization_buffer)
+ token_counter = create_token_counter(
+ model_endpoint_type=agent_llm_config.model_endpoint_type,
+ model=agent_llm_config.model,
+ actor=actor,
+ safety_margin=COMPACTION_TOKEN_HEURISTIC_SAFETY_MARGIN,
+ )
+ converted = token_counter.convert_messages(post_summarization_buffer)
+ approx_token_count = await token_counter.count_message_tokens(converted)
logger.info(
f"Compacting messages index 1:{assistant_message_index} messages resulted in {approx_token_count} tokens, goal is {goal_tokens}"
)
diff --git a/tests/integration_test_summarizer.py b/tests/integration_test_summarizer.py
index 5e14911c0..f8d62a38e 100644
--- a/tests/integration_test_summarizer.py
+++ b/tests/integration_test_summarizer.py
@@ -1051,19 +1051,29 @@ async def test_v3_summarize_hard_eviction_when_still_over_threshold(
# We don't care which summarizer mode is used here; we just need
# summarize_conversation_history to run and then hit the branch where the
# *post*-summarization token count is still above the proactive
- # summarization threshold. We simulate that by patching the
- # count_tokens_with_tools helper to report an extremely large
+ # summarization threshold. We simulate that by patching
+ # TokenCounter.count_messages_with_tools to report an extremely large
# token count for the first call (post-summary) and a small count for the
# second call (after hard eviction).
- with patch("letta.services.summarizer.compact.count_tokens_with_tools") as mock_count_tokens:
- # First call: pretend the summarized context is still huge relative to
- # this model's context window so that we always trigger the
- # hard-eviction path. Second call: minimal context (system only) is
- # small.
- context_limit = llm_config.context_window or 100_000
- huge_tokens = context_limit * 10 # safely above any reasonable trigger
- mock_count_tokens.side_effect = [huge_tokens, 10]
+ context_limit = llm_config.context_window or 100_000
+ huge_tokens = context_limit * 10 # safely above any reasonable trigger
+ from letta.services.context_window_calculator.token_counter import TokenCounter
+
+ original_count = TokenCounter.count_messages_with_tools
+
+ call_count = 0
+ returns = [huge_tokens, 10]
+
+ async def mock_count(self, messages, tools=None):
+ nonlocal call_count
+ if call_count < len(returns):
+ result = returns[call_count]
+ call_count += 1
+ return result
+ return await original_count(self, messages, tools)
+
+ with patch.object(TokenCounter, "count_messages_with_tools", mock_count):
caplog.set_level("ERROR")
_summary, result, summary_text = await agent_loop.compact(
@@ -1073,7 +1083,7 @@ async def test_v3_summarize_hard_eviction_when_still_over_threshold(
# We should have made exactly two token-count calls: one for the
# summarized context, one for the hard-evicted minimal context.
- assert mock_count_tokens.call_count == 2
+ assert call_count == 2
print("COMPACTED RESULT ======")
for msg in result: