From 0c747af743ffd7cc4128e94e84496afad7743360 Mon Sep 17 00:00:00 2001 From: xianghuijin Date: Sun, 23 Mar 2025 17:29:48 +0800 Subject: [PATCH] refactor: streamline tool_choice reset logic This update moves the tool_choice reset logic to a more appropriate location within the RunImpl class, ensuring that the original agent's model_settings remains unmodified during the reset process. The logic now checks for problematic scenarios before creating a modified copy of the agent's settings, maintaining expected behavior across sequential runs. This change enhances clarity and efficiency in handling tool choices. Addresses previous feedback regarding the modification of the agent instance and improves the overall structure of the reset logic. --- src/agents/_run_impl.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/agents/_run_impl.py b/src/agents/_run_impl.py index 1370462..0272520 100644 --- a/src/agents/_run_impl.py +++ b/src/agents/_run_impl.py @@ -211,15 +211,6 @@ class RunImpl: # Reset tool_choice to "auto" after tool execution to prevent infinite loops if processed_response.functions or processed_response.computer_actions: tools = agent.tools - # Only reset in the problematic scenarios where loops are likely unintentional - if cls._should_reset_tool_choice(agent.model_settings, tools): - # Create a modified copy instead of modifying the original agent - new_model_settings = dataclasses.replace( - agent.model_settings, - tool_choice="auto" - ) - # Create a new internal agent with updated settings - agent = dataclasses.replace(agent, model_settings=new_model_settings) if ( run_config.model_settings and @@ -233,6 +224,16 @@ class RunImpl: # Create a new run_config with the new settings run_config = dataclasses.replace(run_config, model_settings=new_run_config_settings) + # Only reset in the problematic scenarios where loops are likely unintentional + if cls._should_reset_tool_choice(agent.model_settings, tools): + # Create a modified copy instead of modifying the original agent + new_model_settings = dataclasses.replace( + agent.model_settings, + tool_choice="auto" + ) + # Create a new internal agent with updated settings + agent = dataclasses.replace(agent, model_settings=new_model_settings) + # Second, check if there are any handoffs if run_handoffs := processed_response.handoffs: return await cls.execute_handoffs(