A ReAct agent alternates between a model step that writes a thought and an action, and a tool step whose result is shown back to the model as an observation. Write the loop around the model. The model is a plain Python callable here, so the loop is fully deterministic.
Implement run_react(llm, tools, question, max_steps).
llm: callable taking the transcript string and returning the model's next output string.tools: dict mapping a tool name to a callable that takes one string and returns a value.question: the user question. max_steps: maximum number of llm calls.The transcript starts as "Question: <question>\n". On each step:
llm(transcript) and strip the output, call it out.out contains "Final Answer:", the answer is the text after the first occurrence, stripped. Stop.Action: <name> and the first line of the form Action Input: <text> (each line stripped of surrounding spaces; name and input stripped). A missing Action Input line means the input is "".Error: no action found if there is no Action: line,Error: unknown tool '<name>' if the name is not in tools,Error: <ExceptionType>: <message> if the tool raises,str(result).Action: line was found, record (name, input, observation).out + "\nObservation: " + observation + "\n" to the transcript.If max_steps calls pass without a final answer, the answer is None.
Return {"answer": answer, "llm_calls": <calls made>, "tool_calls": [<recorded tuples>]}.