fix: simplify looping prevention - don't add instructions if assistant responded

Instead of complex checks for tool_calls in various formats, simply
check if any assistant message exists in the conversation. If the
assistant has already responded, don't add tool instructions again.
This prevents the conversation from growing with duplicate messages.
This commit is contained in:
2026-02-24 14:10:13 +01:00
parent df4587e796
commit c70f83ab6c
+4 -17
View File
@@ -56,25 +56,12 @@ 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 tool execution results
# or if assistant has already responded (prevents looping)
has_tool_results = any(msg.role == "tool" for msg in messages)
has_tool_calls = any(
msg.role == "assistant" and msg.tool_calls
for msg in messages
)
# Also check content in case tool_calls field isn't populated by client
has_tool_calls_in_content = any(
msg.role == "assistant" and msg.content and '"tool_calls"' in msg.content
for msg in messages
)
# 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
)
has_assistant_response = any(msg.role == "assistant" 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 and not has_tool_execution_results:
# Add tool instructions if tools are present and no assistant has responded yet
if tools and not has_tool_results and not has_assistant_response:
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.