Run a ReAct Loop on Plain Text
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).
- The transcript starts as
Question: <question>and a newline. Each step callsmodel(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. - Cut the reply before its first line that starts with
Observation:. Markers count at a line's start, after any leading spaces. - 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 firstAction Input:line below it, both stripped. Keep the lines through the Action Input line, drop the rest, and the tool's result asstris the observation. - 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.
- After
max_stepsmodel 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).