Build a Tool-Calling Agent Loop
Implement run_agent(question, model, tools, max_turns=5):
- Send the question to the model, offering
tools.specs(). - Append the reply to the conversation.
- If the model didn't ask for a tool, return
response.text. - Otherwise run each requested tool and append one user message holding a
tool_resultblock per call, in request order. - An unknown tool is not a crash. Return the error as the tool result with
"is_error": Trueand let the model recover. - Stop at
max_turnsand returnNone.