def run_agent_loop( agent: Agent, initial_message: str, max_iterations: int = 10, verbose: bool = True ) -> str: """ Runs the agent in a loop, handling tool use until completion. Args: agent: The agent instance to run initial_message: The user's initial query max_iterations: Maximum iterations to prevent infinite loops verbose: Whether to print detailed execution logs Returns: The final text response from the agent """ iteration = 0 current_message = initial_message if verbose: print(f"\n{'='*80}") print(f"AGENT EXECUTION START") print(f"{'='*80}") print(f"User Query: {initial_message}\n") while iteration < max_iterations: iteration += 1 if verbose: print(f"\n--- Iteration {iteration} ---") # Send message to Claude response = agent.send_message(current_message) # Check if Claude wants to use tools tool_uses = extract_tool_uses(response) if not tool_uses: # No tools needed - we have the final answer final_response = get_text_response(response) if verbose: print(f"\n{'='*80}") print(f"AGENT EXECUTION COMPLETE") print(f"{'='*80}") print(f"Final Response: {final_response}\n") return final_response # Execute tools and prepare results if verbose: print(f"Claude wants to use {len(tool_uses)} tool(s):") tool_results = create_tool_result_content(tool_uses, agent.tool_map) # Send tool results back to Claude current_message = tool_results return "Maximum iterations reached without completion." __ __