Track step count and return a fallback result when the agent exceeds its allowed step budget.
The full prompt is available without an account.
Implement run_agent(question, llm, tools, max_steps, fallback) that enforces a step budget.
Requirements:
- Accept max_steps and fallback parameters alongside question, llm, and tools.
- Track the number of iterations used so far.
- On each iteration, call the LLM and parse the output for Final Answer or Action.
- Decrement the remaining budget on each step (or count up and compare).
- If the budget is exhausted before a Final Answer, return the fallback string.
- Dispatch tool calls as normal and append Observation: <result>\n.
- If the LLM emits Final Answer: <text>, return the captured text immediately.
Read-only Python 3.12 preview. Sign in to edit and execute it.
import re
ACTION_RE = re.compile(r"Action:\s*(\w+)\((.*)\)")
FINAL_RE = re.compile(r"Final Answer:\s*(.*)")
def run_agent(question: str, llm, tools: dict,
max_steps: int = 6, fallback: str = "") -> str:
scratchpad = f"Question: {question}\n"
# Track step count across iterations.
# Loop up to max_steps times.
# If the loop exits naturally (no Final Answer), return fallback.
pass
return fallback