Wrap tool calls in try/except so that runtime errors become observations and the loop continues.
The full prompt is available without an account.
Implement run_agent(question, llm, tools) that catches exceptions from tool calls and continues the loop.
Requirements:
- Use the provided loop scaffold: parse each LLM output line for Final Answer or Action.
- When an Action is found, look up the tool name in the tools dict and call it.
- Wrap the tool call in a try/except Exception block.
- If the tool raises, append Observation: Error -- <exception message>\n to the scratchpad.
- If the tool succeeds, append Observation: <result>\n.
- Stop on Final Answer or after MAX_STEPS=6.
- Return the final answer or "I could not find an answer.".
Read-only Python 3.12 preview. Sign in to edit and execute it.
import re
MAX_STEPS = 6
ACTION_RE = re.compile(r"Action:\s*(\w+)\((.*)\)")
FINAL_RE = re.compile(r"Final Answer:\s*(.*)")
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"
for line in output.split("\n"):
m = FINAL_RE.search(line)
if m:
return m.group(1)
m = ACTION_RE.search(line)
if m:
name, args = m.group(1), m.group(2)
# TODO: wrap the tool call in try/except
pass
return "I could not find an answer."