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: support filtering out approval messages for anthropic api (#4342)

cthomas9b315e9f54be
diff --git a/letta/agent.py b/letta/agent.py
index 99b48f1f2..52f7de377 100644
--- a/letta/agent.py
+++ b/letta/agent.py
@@ -1442,7 +1442,7 @@ class Agent(BaseAgent):
)
# conversion of messages to anthropic dict format, which is passed to the token counter
- in_context_messages_anthropic = [m.to_anthropic_dict() for m in in_context_messages]
+ in_context_messages_anthropic = Message.to_anthropic_dicts_from_list(in_context_messages)
# Extract system, memory and external summary
if (
diff --git a/letta/llm_api/anthropic_client.py b/letta/llm_api/anthropic_client.py
index 8c33f1627..b970682d5 100644
--- a/letta/llm_api/anthropic_client.py
+++ b/letta/llm_api/anthropic_client.py
@@ -266,13 +266,11 @@ class AnthropicClient(LLMClientBase):
raise RuntimeError(f"First message is not a system message, instead has role {messages[0].role}")
system_content = messages[0].content if isinstance(messages[0].content, str) else messages[0].content[0].text
data["system"] = self._add_cache_control_to_system_message(system_content)
- data["messages"] = [
- m.to_anthropic_dict(
- inner_thoughts_xml_tag=inner_thoughts_xml_tag,
- put_inner_thoughts_in_kwargs=bool(llm_config.put_inner_thoughts_in_kwargs),
- )
- for m in messages[1:]
- ]
+ data["messages"] = PydanticMessage.to_anthropic_dicts_from_list(
+ messages=messages[1:],
+ inner_thoughts_xml_tag=inner_thoughts_xml_tag,
+ put_inner_thoughts_in_kwargs=bool(llm_config.put_inner_thoughts_in_kwargs),
+ )
# Ensure first message is user
if data["messages"][0]["role"] != "user":
diff --git a/letta/schemas/message.py b/letta/schemas/message.py
index adc689096..929b95c28 100644
--- a/letta/schemas/message.py
+++ b/letta/schemas/message.py
@@ -862,13 +862,15 @@ class Message(BaseMessage):
self,
inner_thoughts_xml_tag="thinking",
put_inner_thoughts_in_kwargs: bool = False,
- ) -> dict:
+ ) -> dict | None:
"""
Convert to an Anthropic message dictionary
Args:
inner_thoughts_xml_tag (str): The XML tag to wrap around inner thoughts
"""
+ if self.role == "approval" and self.tool_calls is None:
+ return None
# Check for COT
if self.content and len(self.content) == 1 and isinstance(self.content[0], TextContent):
@@ -926,10 +928,10 @@ class Message(BaseMessage):
"role": self.role,
}
- elif self.role == "assistant":
+ elif self.role == "assistant" or self.role == "approval":
assert self.tool_calls is not None or text_content is not None
anthropic_message = {
- "role": self.role,
+ "role": "assistant",
}
content = []
# COT / reasoning / thinking
@@ -1009,6 +1011,22 @@ class Message(BaseMessage):
return anthropic_message
+ @staticmethod
+ def to_anthropic_dicts_from_list(
+ messages: List[Message],
+ inner_thoughts_xml_tag: str = "thinking",
+ put_inner_thoughts_in_kwargs: bool = False,
+ ) -> List[dict]:
+ result = [
+ m.to_anthropic_dict(
+ inner_thoughts_xml_tag=inner_thoughts_xml_tag,
+ put_inner_thoughts_in_kwargs=put_inner_thoughts_in_kwargs,
+ )
+ for m in messages
+ ]
+ result = [m for m in result if m is not None]
+ return result
+
def to_google_ai_dict(self, put_inner_thoughts_in_kwargs: bool = True) -> dict:
"""
Go from Message class to Google AI REST message object
diff --git a/letta/services/context_window_calculator/token_counter.py b/letta/services/context_window_calculator/token_counter.py
index c432d72e2..96aecb0e6 100644
--- a/letta/services/context_window_calculator/token_counter.py
+++ b/letta/services/context_window_calculator/token_counter.py
@@ -74,7 +74,7 @@ class AnthropicTokenCounter(TokenCounter):
return await self.client.count_tokens(model=self.model, tools=tools)
def convert_messages(self, messages: List[Any]) -> List[Dict[str, Any]]:
- return [m.to_anthropic_dict() for m in messages]
+ return Message.to_anthropic_dicts_from_list(messages)
class TiktokenCounter(TokenCounter):
diff --git a/tests/integration_test_human_in_the_loop.py b/tests/integration_test_human_in_the_loop.py
index 5d7c495fb..61061fae3 100644
--- a/tests/integration_test_human_in_the_loop.py
+++ b/tests/integration_test_human_in_the_loop.py
@@ -128,7 +128,7 @@ def agent(client: Letta, approval_tool_fixture) -> AgentState:
name="approval_test_agent",
include_base_tools=False,
tool_ids=[send_message_tool.id, approval_tool_fixture.id],
- model="openai/gpt-4o-mini",
+ model="anthropic/claude-3-5-sonnet",
embedding="openai/text-embedding-3-small",
tags=["approval_test"],
)
@@ -229,12 +229,13 @@ def test_send_message_after_turning_off_requires_approval(
)
assert response.messages is not None
- assert len(response.messages) == 5
+ assert len(response.messages) == 3 or len(response.messages) == 5
assert response.messages[0].message_type == "reasoning_message"
assert response.messages[1].message_type == "tool_call_message"
assert response.messages[2].message_type == "tool_return_message"
- assert response.messages[3].message_type == "reasoning_message"
- assert response.messages[4].message_type == "assistant_message"
+ if len(response.messages) == 5:
+ assert response.messages[3].message_type == "reasoning_message"
+ assert response.messages[4].message_type == "assistant_message"
# ------------------------------
@@ -303,13 +304,14 @@ def test_approve_cursor_fetch(
)
messages = client.agents.messages.list(agent_id=agent.id, after=last_message_cursor)
- assert len(messages) == 5
+ assert len(messages) == 2 or len(messages) == 5
assert messages[0].message_type == "approval_response_message"
assert messages[1].message_type == "tool_return_message"
assert messages[1].status == "success"
- assert messages[2].message_type == "user_message" # heartbeat
- assert messages[3].message_type == "reasoning_message"
- assert messages[4].message_type == "assistant_message"
+ if len(messages) == 5:
+ assert messages[2].message_type == "user_message" # heartbeat
+ assert messages[3].message_type == "reasoning_message"
+ assert messages[4].message_type == "assistant_message"
def test_approve_and_follow_up(