#375ReAct Loop DriverMediumAgentic AIAsked atOpenAI · Anthropic · Google
ReAct Loop Driver
Background
ReAct = Reason + Act. Instead of asking the LLM for an immediate answer, you let it interleave reasoning steps with tool calls. The driver loop parses the LLM's output — either SEARCH: <query> (call the tool, append the result to history, loop) or ANSWER: <text> (return). Plus a max_steps cap so a buggy model doesn't loop forever.
Problem statement
Implement react_run(llm, tool, query, max_steps=5):
- Initialise the history with the user query.
- For up to
max_stepsiterations: callllm(history); parse its output. - If it starts with
ANSWER:, return the text after the colon (trimmed). - If it starts with
SEARCH:, calltool(query), append the LLM message + observation to history, continue. - If neither prefix matches OR steps exhaust, return
None.
Input
llm(messages) -> str— callable taking the running message list.tool(query: str) -> str— callable taking a query and returning an observation.query—str, the initial user query.max_steps—int, iteration cap (default5).
Output
Returns the trimmed answer str, or None if the loop terminates without one.
Examples
Example 1 — direct answer
llm returns "ANSWER: 42"
Output: "42"
Example 2 — search then answer
Step 1: llm returns "SEARCH: capital of France"
tool returns "Paris is the capital"
Step 2: llm returns "ANSWER: Paris"
Output: "Paris"
Example 3 — exhaustion
llm always returns "SEARCH: x" → loop hits max_steps → returns None
Example 4 — whitespace tolerance
llm returns " ANSWER: ok "
Output: "ok"
Constraints
- Strip whitespace from the LLM response before pattern-match.
- Malformed (no recognised prefix) responses return
Noneimmediately, not after exhausting steps. - Strip whitespace from the answer text.
Notes
- Why max_steps. A buggy ReAct prompt can loop searches forever; the cap is the safety belt.
- Trace mode. Production drivers tee a
TraceEventper LLM call so observability rolls up per-agent (seesummarise_trace).
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference direct answer
- •Sample search then answer
- •Example max-steps exhaustion returns None