Implement the ReAct (Reason + Act) loop: the model reasons, picks a tool, observes, and loops until done.
The ReAct loop you build from scratch
1 / 5Ask the model
Step 1 of 5
Ask the model
Send the task, the history so far and the tool definitions. The model either answers or asks for a tool.
Step 2 of 5
Tool requested?
If the reply has tool calls, continue round the loop. If it has none and the finish reason is stop, that reply is the final answer.
Step 3 of 5
Run the tool
Execute each requested tool with the arguments the model gave. A tool that throws is caught and turned into an error message.
Step 4 of 5
Feed back result
Append the output as a tool message, then call the model again. The observation is how it learns what happened.
Step 5 of 5
Check budget
Count each pass. When the count reaches max_iter, raise an error instead of looping on.
An agent is a loop around a model call. The max_iter limit is what stops it running forever.
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.py
~106 tokens
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.