Skip to content

< all problems113 · Level 05, Agents

Run a ReAct Loop on Plain Text

medium · implement · Agents

Implement react(question, model, tools, max_steps=5), the ReAct paper's loop. The model replies in plain text: Thought: lines, then an Action: and Action Input: line, or a Final Answer: line. The harness runs the tool and writes the Observation:. model(transcript) returns a reply; tools maps a name to a function of one string. Return (answer, transcript).

  1. The transcript starts as Question: <question> and a newline. Each step calls model(transcript) once and appends the kept lines of the reply joined by \n, then a newline, then (unless it answered) Observation: <text> and a newline.
  2. Cut the reply before its first line that starts with Observation:. Markers count at a line's start, after any leading spaces.
  3. The first marker in the kept lines decides. Final Answer: first: keep the lines through it and return the rest of that line, stripped. Action: first: the tool name is the rest of that line and the input is the rest of the first Action Input: line below it, both stripped. Keep the lines through the Action Input line, drop the rest, and the tool's result as str is the observation.
  4. Mistakes are observations, never exceptions. An unknown tool: name it and list the tools. No Action Input: say the Action Input is missing. A tool that raises: include its message. A reply with neither marker: ask for an Action or a Final Answer.
  5. After max_steps model calls with no answer, return (None, transcript).

The catch. After a few steps the model writes its own observation: Action Input: Lyon, Observation: 9 million, Final Answer: 9 million, all in one reply. That observation is a guess. Cut it, run the tool, and let the next call see the real result (in production, a stop sequence makes this cut).