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: dedupe approval response retries on server (#9038)

cthomas57ab117437d3
diff --git a/letta/agents/helpers.py b/letta/agents/helpers.py
index dffe50ff4..ca1506f68 100644
--- a/letta/agents/helpers.py
+++ b/letta/agents/helpers.py
@@ -97,6 +97,25 @@ async def _prepare_in_context_messages_async(
return current_in_context_messages, new_in_context_messages
+@trace_method
+def validate_persisted_tool_call_ids(tool_return_message: Message, approval_response_message: ApprovalCreate) -> bool:
+ persisted_tool_returns = tool_return_message.tool_returns
+ if not persisted_tool_returns:
+ return False
+ persisted_tool_call_ids = [tool_return.tool_call_id for tool_return in persisted_tool_returns]
+
+ approval_responses = approval_response_message.approvals
+ if not approval_responses:
+ return False
+ approval_response_tool_call_ids = [approval_response.tool_call_id for approval_response in approval_responses]
+
+ request_response_diff = set(persisted_tool_call_ids).symmetric_difference(set(approval_response_tool_call_ids))
+ if request_response_diff:
+ return False
+
+ return True
+
+
@trace_method
def validate_approval_tool_call_ids(approval_request_message: Message, approval_response_message: ApprovalCreate):
approval_requests = approval_request_message.tool_calls
@@ -227,6 +246,24 @@ async def _prepare_in_context_messages_no_persist_async(
if input_messages[0].type == "approval":
# User is trying to send an approval response
if current_in_context_messages and current_in_context_messages[-1].role != "approval":
+ if current_in_context_messages[-1].role == "tool" and validate_persisted_tool_call_ids(
+ current_in_context_messages[-1], input_messages[0]
+ ):
+ # Approval already handled, just process follow-up messages if any or manually inject keep-alive message
+ keep_alive_messages = input_messages[1:] or [
+ MessageCreate(
+ role="user",
+ content=[
+ TextContent(
+ text="<system-alert>Automated keep-alive ping. Ignore this message and continue from where you stopped.</system-alert>"
+ )
+ ],
+ )
+ ]
+ new_in_context_messages = await create_input_messages(
+ input_messages=keep_alive_messages, agent_id=agent_state.id, timezone=agent_state.timezone, run_id=run_id, actor=actor
+ )
+ return current_in_context_messages, new_in_context_messages
logger.warn(
f"Cannot process approval response: No tool call is currently awaiting approval. Last message: {current_in_context_messages[-1]}"
)
diff --git a/tests/integration_test_human_in_the_loop.py b/tests/integration_test_human_in_the_loop.py
index be9078a8c..6024660f9 100644
--- a/tests/integration_test_human_in_the_loop.py
+++ b/tests/integration_test_human_in_the_loop.py
@@ -1347,6 +1347,8 @@ def test_approve_with_cancellation(
import threading
import time
+ last_message_cursor = client.agents.messages.list(agent_id=agent.id, limit=1).items[0].id
+
# Step 1: Send message that triggers approval request
response = client.agents.messages.create(
agent_id=agent.id,
@@ -1370,13 +1372,15 @@ def test_approve_with_cancellation(
"type": "approval",
"approvals": [
{
- "type": "approval",
- "approve": True,
+ "type": "tool",
"tool_call_id": tool_call_id,
+ "tool_return": SECRET_CODE,
+ "status": "success",
},
],
},
],
+ streaming=True,
stream_tokens=True,
)
@@ -1384,7 +1388,7 @@ def test_approve_with_cancellation(
messages = accumulate_chunks(response)
# Step 5: Verify we got chunks AND a cancelled stop reason
- assert len(messages) > 0, "Should receive at least some chunks before cancellation"
+ assert len(messages) > 1, "Should receive at least some chunks before cancellation"
# Find stop_reason in messages
stop_reasons = [msg for msg in messages if hasattr(msg, "message_type") and msg.message_type == "stop_reason"]
@@ -1400,3 +1404,46 @@ def test_approve_with_cancellation(
cancel_thread.join(timeout=1.0)
logger.info(f"✅ Test passed: approval with cancellation handled correctly, received {len(messages)} chunks")
+
+ # Step 7: Verify that approval response message is persisted
+ messages = client.agents.messages.list(agent_id=agent.id, after=last_message_cursor).items
+ assert len(messages) > 0, "Should have persisted at least some messages before cancellation"
+ assert messages[-1].message_type == "tool_return_message", "Last message should be a tool return message"
+ last_message_cursor = messages[-1].id
+
+ # Step 8: Attempt retry with same response
+ response = client.agents.messages.stream(
+ agent_id=agent.id,
+ messages=[
+ {
+ "type": "approval",
+ "approvals": [
+ {
+ "type": "tool",
+ "tool_call_id": tool_call_id,
+ "tool_return": SECRET_CODE,
+ "status": "success",
+ },
+ ],
+ },
+ ],
+ streaming=True,
+ stream_tokens=True,
+ )
+
+ # Step 9: Accumulate chunks
+ messages = accumulate_chunks(response)
+
+ # Step 10: Verify we got chunks AND an end_turn stop reason
+ assert len(messages) > 1, "Should receive at least some chunks before cancellation"
+
+ # Find stop_reason in messages
+ stop_reasons = [msg for msg in messages if hasattr(msg, "message_type") and msg.message_type == "stop_reason"]
+ assert len(stop_reasons) == 1, f"Expected exactly 1 stop_reason, got {len(stop_reasons)}"
+ assert stop_reasons[0].stop_reason == "end_turn", f"Expected stop_reason 'end_turn', got '{stop_reasons[0].stop_reason}'"
+
+ # Step 11: Verify keep-alive message was sent
+ messages = client.agents.messages.list(agent_id=agent.id, after=last_message_cursor).items
+ assert len(messages) > 0, "Should have persisted new messages"
+ assert messages[0].message_type == "user_message", "First message should be a user message"
+ assert "keep-alive" in messages[0].content, f"Expected keep-alive message, got '{messages[0].content}'"