Parse agent output and route tool calls to the right handler with a fallback for unknown tools.
The full prompt is available without an account.
Implement run_agent(question, llm, tools) that routes tool calls parsed from LLM output.
Requirements:
- Use the provided parse_tool_call helper to extract tool name and args from each LLM output line.
- Look up the tool name in the tools dictionary and call tools[name](args).
- If the tool name is not found in tools, append Observation: Unknown tool "<name>"\n.
- Always append the observation (or error) to the scratchpad and continue the loop.
- Stop when a line starts with Final Answer: and return the text after the prefix.
- After MAX_STEPS=8 iterations, return "I could not find an answer.".
Read-only Python 3.12 preview. Sign in to edit and execute it.
import re
MAX_STEPS = 8
def parse_tool_call(line: str):
m = re.match(r"Action:\s*(\w+)\((.*)\)", line)
if m:
return m.group(1), m.group(2)
m = re.match(r"Action:\s*(\w+)", line)
if m:
return m.group(1), None
return None
def run_agent(question: str, llm, tools: dict) -> str:
scratchpad = f"Question: {question}\n"
for _ in range(MAX_STEPS):
output = llm(scratchpad)
scratchpad += output + "\n"
# TODO: iterate lines, check Final Answer, then route tool calls
pass
return "I could not find an answer."