Parse a ReAct agent's action from model output

EasyAgents

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"}.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: tool callparse_action('Thought: need weather\nAction: get_weather\nAction Input: {"city": "Pune"}')
  • Sample 2: final answerparse_action('Thought: done\nFinal Answer: 31 C and sunny')
  • Test 3: bad jsonparse_action('Action: search\nAction Input: {query: llm}')
  • Test 4: last action winsparse_action('Action: a\nAction Input: {}\nAction: b\nAction Input: {"x": 1}')