Parse a ReAct Agent Step

medium
Unit 18 · Agents0/3 to milestone

ReAct agents interleave reasoning and tool use in plain text:

Thought: I need the population first.
Action: search[population of Lyon]

or finish with

Thought: I know the answer.
Final Answer: About 520,000 people.

Implement parse_step(text) returning one of:

  • {"type": "action", "thought": ..., "tool": ..., "input": ...}
  • {"type": "final", "thought": ..., "answer": ...}

Rules:

  • Thought: may span multiple lines, up to the Action: or Final Answer: line. Strip whitespace. It's "" if missing.
  • Action: tool[input]: the tool name is letters, digits and underscores. The input is everything between the first [ and the last ] on that line, so it may contain brackets.
  • If both appear, whichever comes first wins. Anything after a Final Answer: line (including following lines) is part of the answer.
  • Raise ValueError with a helpful message if there's neither, or if the Action line is malformed. Agents feed this error back to the model so it can fix itself.
#agents#parsing#prompting2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Parse a ReAct Agent Step · TechGradify