Parse a ReAct agent's action from model output
A ReAct agent writes text like:
Thought: I need the weather.
Action: get_weather
Action Input: {"city": "Pune"}
or finishes with a line starting "Final Answer:".
Write parse_action(text). If a "Final Answer:" line exists, return {"type": "final", "answer": <text after the colon, stripped>}. Otherwise find the LAST "Action:" line and the "Action Input:" line after it, parse the input as JSON, and return {"type": "tool", "name": <stripped>, "args": <dict>}. If there is no action, or the JSON is invalid, return {"type": "error"}.
def parse_action(text)Understand the idea
A ReAct agent writes its reasoning as plain text with labelled lines, and your code must pull out what to do next. Model output is untrusted, so parse defensively: anything malformed becomes an explicit error the loop can show the model, never a crash and never a silent final answer. Priority matters: if any line starts with 'Final Answer:', the run is finished. Otherwise use the last 'Action:' line and the 'Action Input:' line after it, which must be valid JSON. Worked trace: text 'Thought: check rates / Action: convert / Action Input: {"amount": 5}' gives a tool call named convert with args {amount: 5}. If the input line were {amount: 5} without quotes, json.loads fails, so return an error. If two Action blocks appear, the second one wins, since it reflects the model's latest decision. Rule: final line first, else last Action plus following Action Input parsed as JSON, else error; strip whitespace from names and answers. LangChain-style ReAct agents depend on a parser like this.