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.

feat: ensure trailing thinking block doesn't break token counter (#5271)

cthomased74c595a68f
diff --git a/letta/schemas/message.py b/letta/schemas/message.py
index 7350cef03..4c316a5d3 100644
--- a/letta/schemas/message.py
+++ b/letta/schemas/message.py
@@ -1698,6 +1698,14 @@ class Message(BaseMessage):
if messages[-1].role == "approval" and messages[-1].tool_calls is not None and len(messages[-1].tool_calls) > 0:
messages.remove(messages[-1])
+ # Filter last message if it is a lone reasoning message without assistant message or tool call
+ if (
+ messages[-1].role == "assistant"
+ and messages[-1].tool_calls is None
+ and (not messages[-1].content or all(not isinstance(content_part, TextContent) for content_part in messages[-1].content))
+ ):
+ messages.remove(messages[-1])
+
return messages
@staticmethod
diff --git a/tests/integration_test_human_in_the_loop.py b/tests/integration_test_human_in_the_loop.py
index 5a96f6e76..701e61705 100644
--- a/tests/integration_test_human_in_the_loop.py
+++ b/tests/integration_test_human_in_the_loop.py
@@ -143,7 +143,7 @@ def agent(client: Letta, approval_tool_fixture) -> AgentState:
agent_type=AgentType.letta_v1_agent,
include_base_tools=False,
tool_ids=[approval_tool_fixture.id],
- model="anthropic/claude-sonnet-4-20250514",
+ model="anthropic/claude-sonnet-4-5-20250929",
embedding="openai/text-embedding-3-small",
tags=["approval_test"],
)
@@ -599,6 +599,38 @@ def test_deny_and_follow_up(
assert messages[3].message_type == "usage_statistics"
+def test_deny_with_context_check(
+ client: Letta,
+ agent: AgentState,
+) -> None:
+ response = client.agents.messages.create(
+ agent_id=agent.id,
+ messages=USER_MESSAGE_TEST_APPROVAL,
+ )
+ approval_request_id = response.messages[0].id
+
+ response = client.agents.messages.create_stream(
+ agent_id=agent.id,
+ messages=[
+ ApprovalCreate(
+ approve=False,
+ approval_request_id=approval_request_id,
+ reason="Cancelled by user. Instead of responding, wait for next user input before replying.",
+ ),
+ ],
+ stream_tokens=True,
+ )
+
+ messages = accumulate_chunks(response)
+
+ try:
+ client.agents.context.retrieve(agent_id=agent.id)
+ except Exception as e:
+ if len(messages) > 4:
+ raise ValueError("Model did not respond with only reasoning content, please rerun test to repro edge case.")
+ raise e
+
+
def test_deny_and_follow_up_with_error(
client: Letta,
agent: AgentState,