#375ReAct Loop DriverMedium

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):

  1. Initialise the history with the user query.
  2. For up to max_steps iterations: call llm(history); parse its output.
  3. If it starts with ANSWER:, return the text after the colon (trimmed).
  4. If it starts with SEARCH:, call tool(query), append the LLM message + observation to history, continue.
  5. 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.
  • querystr, the initial user query.
  • max_stepsint, iteration cap (default 5).

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 None immediately, 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 TraceEvent per LLM call so observability rolls up per-agent (see summarise_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