fix: prevent looping by checking for server-side tool execution results

Add check for 'Tool X result' pattern in assistant messages to detect
when server-side tool execution has already occurred. This prevents
the conversation from growing with duplicate user messages.
This commit is contained in:
2026-02-24 14:06:49 +01:00
parent 00cd483aca
commit df4587e796
+7 -8
View File
@@ -56,7 +56,7 @@ def format_messages_with_tools(messages: list, tools: Optional[list] = None) ->
formatted = []
# Check if there are already tool results in the conversation
# or if assistant has already generated tool_calls
# or if assistant has already generated tool_calls or tool execution results
has_tool_results = any(msg.role == "tool" for msg in messages)
has_tool_calls = any(
msg.role == "assistant" and msg.tool_calls
@@ -67,15 +67,14 @@ def format_messages_with_tools(messages: list, tools: Optional[list] = None) ->
msg.role == "assistant" and msg.content and '"tool_calls"' in msg.content
for msg in messages
)
# Debug: log what we're checking
if tools:
print(f"DEBUG TOOLS: has_tool_results={has_tool_results}, has_tool_calls={has_tool_calls}, has_tool_calls_in_content={has_tool_calls_in_content}")
for i, msg in enumerate(messages):
print(f" [{i}] {msg.role}: content={repr(msg.content)[:50] if msg.content else None}, tool_calls={msg.tool_calls is not None and len(msg.tool_calls) > 0 if hasattr(msg, 'tool_calls') else False}")
# Check for server-side tool execution results (prevents looping)
has_tool_execution_results = any(
msg.role == "assistant" and msg.content and "Tool '" in msg.content and "result:" in msg.content
for msg in messages
)
# Add tool instructions if tools are present and no tool results/calls yet
if tools and not has_tool_results and not has_tool_calls and not has_tool_calls_in_content:
if tools and not has_tool_results and not has_tool_calls and not has_tool_calls_in_content and not has_tool_execution_results:
tool_instructions = """You have access to tools. When asked to create, write, or modify files, USE the tools.
CRITICAL: Do not explain what you will do. Do not show commands. Actually use the tools to do it.