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.
This commit is contained in:
xianghuijin 2025-03-23 17:29:48 +08:00
parent 6ed0bee672
commit 0c747af743

View file

@ -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(