All labs
Build a ReAct Agent Loop
Implement the ReAct (Reason + Act) loop: the model reasons, picks a tool, observes, and loops until done.
Scenario
Build the agent loop from scratch — no framework. Understand exactly how agents work by implementing one.
Objective
Implement run_agent(task, tools, max_iter) that loops reasoning + tool calling until final answer or max_iter.
Starter code
Implement the TODOs to complete the lab.
agent.pypython
def run_agent(task: str, tools: list[Tool], max_iter: int = 10) -> str:
"""Run the ReAct loop.
- Call LLM with task + tool definitions
- If model returns tool_calls, execute them
- Feed observations back to model
- Loop until final answer or max_iter
- Raise on max_iter exceeded
"""
messages = [{"role": "user", "content": task}]
# TODO: implement the loop
pass Solution hints
- 1Pass tools as function definitions
- 2Check response.choices[0].message.tool_calls
- 3Execute each tool, append tool result as 'tool' role message
- 4Stop when no tool_calls and finish_reason='stop'
- 5Enforce max_iter strictly
Validation steps
Your implementation should pass these checks.
- Agent calls the right tool for the task
- Agent loops until it has the answer
- Agent stops at max_iter with an error
- Tool errors are caught and fed as observations
Run validation
This is a simulated validation environment. In production, this would run your code against the validation steps.