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(core): scope 90% summarization trigger to GPT-5 models (#9869)

jnjpng98c7d106739a
diff --git a/letta/agents/letta_agent_v3.py b/letta/agents/letta_agent_v3.py
index 068a840c2..15d13bef4 100644
--- a/letta/agents/letta_agent_v3.py
+++ b/letta/agents/letta_agent_v3.py
@@ -72,6 +72,7 @@ from letta.services.provider_manager import AUTO_MODE_HANDLES
from letta.services.summarizer.compact import compact_messages
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
from letta.utils import safe_create_task_with_return, validate_function_response
@@ -910,6 +911,8 @@ class LettaAgentV3(LettaAgentV2):
if self.context_token_estimate is None:
self.logger.warning("Context token estimate is not set")
+ compaction_trigger_threshold = get_compaction_trigger_threshold(self.agent_state.llm_config)
+
step_progression = StepProgression.START
caught_exception = None
# TODO(@caren): clean this up
@@ -1184,7 +1187,7 @@ class LettaAgentV3(LettaAgentV2):
summary_message, messages, summary_text = await self.compact(
messages,
- trigger_threshold=self.agent_state.llm_config.context_window,
+ trigger_threshold=compaction_trigger_threshold,
run_id=run_id,
step_id=step_id,
use_summary_role=include_compaction_messages,
@@ -1379,9 +1382,11 @@ class LettaAgentV3(LettaAgentV2):
yield message
# check compaction
- if self.context_token_estimate is not None and self.context_token_estimate > self.agent_state.llm_config.context_window:
+ if self.context_token_estimate is not None and self.context_token_estimate > compaction_trigger_threshold:
self.logger.info(
- f"Context window exceeded (current: {self.context_token_estimate}, threshold: {self.agent_state.llm_config.context_window}), trying to compact messages"
+ "Compaction threshold exceeded "
+ f"(current: {self.context_token_estimate}, threshold: {compaction_trigger_threshold}, "
+ f"context_window: {self.agent_state.llm_config.context_window}), trying to compact messages"
)
# Capture pre-compaction state for metadata
@@ -1404,7 +1409,7 @@ class LettaAgentV3(LettaAgentV2):
summary_message, messages, summary_text = await self.compact(
messages,
- trigger_threshold=self.agent_state.llm_config.context_window,
+ trigger_threshold=compaction_trigger_threshold,
run_id=run_id,
step_id=step_id,
use_summary_role=include_compaction_messages,
diff --git a/letta/services/summarizer/constants.py b/letta/services/summarizer/constants.py
new file mode 100644
index 000000000..122152a61
--- /dev/null
+++ b/letta/services/summarizer/constants.py
@@ -0,0 +1,3 @@
+"""Shared constants for summarization services."""
+
+SUMMARY_TRUNCATION_SUFFIX = "... [summary truncated to fit]"
diff --git a/letta/services/summarizer/self_summarizer.py b/letta/services/summarizer/self_summarizer.py
index 4aeae5f26..a74ab9000 100644
--- a/letta/services/summarizer/self_summarizer.py
+++ b/letta/services/summarizer/self_summarizer.py
@@ -11,6 +11,7 @@ from letta.schemas.letta_message_content import TextContent
from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message
from letta.schemas.user import User
+from letta.services.summarizer.constants import 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
@@ -131,7 +132,7 @@ async def self_summarize_all(
# Clip if needed
if compaction_settings.clip_chars is not None and len(summary_text) > compaction_settings.clip_chars:
logger.warning(f"CC summary length {len(summary_text)} exceeds clip length {compaction_settings.clip_chars}. Truncating.")
- summary_text = summary_text[: compaction_settings.clip_chars] + "... [summary truncated to fit]"
+ summary_text = summary_text[: compaction_settings.clip_chars] + SUMMARY_TRUNCATION_SUFFIX
# Build final messages: [system] + protected messages
# Summary message handling is done in compact parent function
diff --git a/letta/services/summarizer/summarizer_all.py b/letta/services/summarizer/summarizer_all.py
index aa3818d02..d95d3ca9e 100644
--- a/letta/services/summarizer/summarizer_all.py
+++ b/letta/services/summarizer/summarizer_all.py
@@ -5,6 +5,7 @@ from letta.otel.tracing import trace_method
from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message, MessageRole
from letta.schemas.user import User
+from letta.services.summarizer.constants import SUMMARY_TRUNCATION_SUFFIX
from letta.services.summarizer.summarizer import simple_summary
from letta.services.summarizer.summarizer_config import CompactionSettings
@@ -77,6 +78,6 @@ async def summarize_all(
if summarizer_config.clip_chars is not None and len(summary_message_str) > summarizer_config.clip_chars:
logger.warning(f"Summary length {len(summary_message_str)} exceeds clip length {summarizer_config.clip_chars}. Truncating.")
- summary_message_str = summary_message_str[: summarizer_config.clip_chars] + "... [summary truncated to fit]"
+ summary_message_str = summary_message_str[: summarizer_config.clip_chars] + SUMMARY_TRUNCATION_SUFFIX
return summary_message_str, [in_context_messages[0], *protected_messages]
diff --git a/letta/services/summarizer/summarizer_sliding_window.py b/letta/services/summarizer/summarizer_sliding_window.py
index b271c3c1a..9fd3cc7b6 100644
--- a/letta/services/summarizer/summarizer_sliding_window.py
+++ b/letta/services/summarizer/summarizer_sliding_window.py
@@ -10,6 +10,7 @@ from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message
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.summarizer import simple_summary
from letta.services.summarizer.summarizer_config import CompactionSettings
@@ -222,7 +223,7 @@ async def summarize_via_sliding_window(
if summarizer_config.clip_chars is not None and len(summary_message_str) > summarizer_config.clip_chars:
logger.warning(f"Summary length {len(summary_message_str)} exceeds clip length {summarizer_config.clip_chars}. Truncating.")
- summary_message_str = summary_message_str[: summarizer_config.clip_chars] + "... [summary truncated to fit]"
+ summary_message_str = summary_message_str[: summarizer_config.clip_chars] + SUMMARY_TRUNCATION_SUFFIX
updated_in_context_messages = in_context_messages[assistant_message_index:]
return summary_message_str, [system_prompt, *updated_in_context_messages]
diff --git a/letta/services/summarizer/thresholds.py b/letta/services/summarizer/thresholds.py
new file mode 100644
index 000000000..c55133617
--- /dev/null
+++ b/letta/services/summarizer/thresholds.py
@@ -0,0 +1,43 @@
+"""Helpers for model-specific compaction/summarization trigger thresholds."""
+
+import re
+
+from letta.constants import SUMMARIZATION_TRIGGER_MULTIPLIER
+from letta.schemas.llm_config import LLMConfig
+
+# Matches GPT-5 model names in raw or provider-prefixed format, e.g.:
+# - gpt-5
+# - gpt-5.1
+# - gpt-5-mini
+# - openai/gpt-5
+# - openai/gpt-5.2
+_GPT5_MODEL_FAMILY_RE = re.compile(r"(^|/)gpt-5($|[.-])", re.IGNORECASE)
+
+
+# TODO: Centralize model name checking/classifying logic into a shared utility module.
+# Model string matching (startswith, regex, substring checks) is scattered across
+# LLM client code, provider schemas, LLMConfig, and legacy helpers for every provider.
+def is_gpt5_model_family(model_name: str | None) -> bool:
+ """Return True if model_name belongs to the GPT-5 family."""
+ if not model_name:
+ return False
+ return bool(_GPT5_MODEL_FAMILY_RE.search(model_name.strip()))
+
+
+def get_compaction_trigger_threshold(llm_config: LLMConfig, *, force_proactive: bool = False) -> int:
+ """Return effective compaction trigger threshold for a model config.
+
+ If ``force_proactive`` is True, always use the proactive 90% threshold. This
+ is used by Temporal paths that intentionally preserve legacy proactive behavior
+ for all models.
+
+ GPT-5 family models trigger compaction proactively at 90% of context window.
+ We observed GPT-5 runs hitting max_output_tokens exceeded when prompt input got
+ close to the 272k input context window; this aligns GPT-5 behavior with the
+ codex harness' proactive 90% compaction policy.
+
+ All other models trigger at 100% of context window.
+ """
+ if force_proactive or is_gpt5_model_family(llm_config.model):
+ return int(llm_config.context_window * SUMMARIZATION_TRIGGER_MULTIPLIER)
+ return llm_config.context_window
diff --git a/tests/integration_test_summarizer.py b/tests/integration_test_summarizer.py
index b339c4d69..5e14911c0 100644
--- a/tests/integration_test_summarizer.py
+++ b/tests/integration_test_summarizer.py
@@ -1782,6 +1782,7 @@ async def test_summarize_all(server: SyncServer, actor, llm_config: LLMConfig):
This test verifies that the 'all' summarization mode works correctly,
summarizing the entire conversation into a single summary string.
"""
+ from letta.services.summarizer.constants import SUMMARY_TRUNCATION_SUFFIX
from letta.services.summarizer.summarizer_all import summarize_all
from letta.services.summarizer.summarizer_config import CompactionSettings
@@ -1789,6 +1790,9 @@ async def test_summarize_all(server: SyncServer, actor, llm_config: LLMConfig):
handle = llm_config.handle or f"{llm_config.model_endpoint_type}/{llm_config.model}"
summarizer_config = CompactionSettings(model=handle)
summarizer_config.mode = "all"
+ # Keep this test deterministic across provider/model output style changes.
+ # summarize_all truncates to clip_chars, then appends a truncation suffix.
+ summarizer_config.clip_chars = 2000
# Create test messages - a simple conversation
messages = [
@@ -1827,7 +1831,9 @@ async def test_summarize_all(server: SyncServer, actor, llm_config: LLMConfig):
assert len(new_in_context_messages) == 1
assert summary is not None
assert len(summary) > 0
- assert len(summary) <= 2000
+ assert len(summary) <= summarizer_config.clip_chars + len(SUMMARY_TRUNCATION_SUFFIX)
+ if len(summary) > summarizer_config.clip_chars:
+ assert summary.endswith(SUMMARY_TRUNCATION_SUFFIX)
print(f"Successfully summarized {len(messages)} messages using 'all' mode")
print(f"Summary: {summary[:200]}..." if len(summary) > 200 else f"Summary: {summary}")
diff --git a/tests/test_compaction_thresholds.py b/tests/test_compaction_thresholds.py
new file mode 100644
index 000000000..82a35a81b
--- /dev/null
+++ b/tests/test_compaction_thresholds.py
@@ -0,0 +1,53 @@
+from letta.schemas.llm_config import LLMConfig
+from letta.services.summarizer.thresholds import get_compaction_trigger_threshold, is_gpt5_model_family
+
+
+def test_is_gpt5_model_family_matches_raw_gpt5_names():
+ assert is_gpt5_model_family("gpt-5")
+ assert is_gpt5_model_family("gpt-5-mini")
+ assert is_gpt5_model_family("gpt-5.2")
+
+
+def test_is_gpt5_model_family_matches_provider_prefixed_names():
+ assert is_gpt5_model_family("openai/gpt-5")
+ assert is_gpt5_model_family("openai/gpt-5.1-codex")
+ assert is_gpt5_model_family("azure/gpt-5-chat-latest")
+
+
+def test_is_gpt5_model_family_rejects_non_gpt5_names():
+ assert not is_gpt5_model_family("gpt-4.1")
+ assert not is_gpt5_model_family("claude-sonnet-4")
+ assert not is_gpt5_model_family("gpt-50")
+
+
+def test_get_compaction_trigger_threshold_uses_90_percent_for_gpt5():
+ llm_config = LLMConfig(
+ model="gpt-5.2",
+ model_endpoint_type="openai",
+ model_endpoint="https://api.openai.com/v1",
+ context_window=272000,
+ )
+
+ assert get_compaction_trigger_threshold(llm_config) == int(272000 * 0.9)
+
+
+def test_get_compaction_trigger_threshold_uses_100_percent_for_non_gpt5():
+ llm_config = LLMConfig(
+ model="gpt-4.1",
+ model_endpoint_type="openai",
+ model_endpoint="https://api.openai.com/v1",
+ context_window=128000,
+ )
+
+ assert get_compaction_trigger_threshold(llm_config) == 128000
+
+
+def test_get_compaction_trigger_threshold_force_proactive_uses_90_percent_for_non_gpt5():
+ llm_config = LLMConfig(
+ model="gpt-4.1",
+ model_endpoint_type="openai",
+ model_endpoint="https://api.openai.com/v1",
+ context_window=128000,
+ )
+
+ assert get_compaction_trigger_threshold(llm_config, force_proactive=True) == int(128000 * 0.9)