Parse a full multi-step ReAct trace into structured steps
Why it matters Agent tracing and evaluation tools turn raw transcripts into steps exactly like this before scoring tool use.
Logging and evaluating agents needs the whole ReAct transcript as data, not just the last action.
Write parse_trace(text). Process text line by line (strip each line). Keywords are checked in this order: "Thought:", "Action Input:", "Action:", "Observation:", "Final Answer:". Each step is a dict with keys "thought", "action", "input", "observation", all strings defaulting to "".
- A "Thought:" line always starts a new step.
- An "Action:", "Action Input:" or "Observation:" line fills that field of the current step; if there is no current step or that field is already set, it starts a new step first.
- A "Final Answer:" line sets the final answer.
- Values are the text after the keyword, stripped. A non-empty line with no keyword is a continuation: append "\n" plus the line to the most recently written field (or to the final answer); ignore it if nothing was written yet. Blank lines are ignored.
Return {"steps": [list of step dicts], "final": final answer string or None}.
def parse_trace(text)Example
parse_trace("Thought: look it up\nAction: search\nAction Input: {\"q\": \"pune\"}\nObservation: 31C\nhumid\nFinal Answer: 31C") gives {'steps': [{'thought': 'look it up', 'action': 'search', 'input': '{"q": "pune"}', 'observation': '31C\nhumid'}], 'final': '31C'}.
Understand the idea
A ReAct agent alternates reasoning and acting in plain text: Thought (why), Action (which tool), Action Input (arguments), Observation (what the tool returned), repeated until a Final Answer. To debug or grade an agent you need this as structured data: a list of steps, each with its four parts.
Example: "Thought: look it up / Action: search / Action Input: {...} / Observation: 31C / humid / Final Answer: 31C" becomes one step whose observation is "31C\nhumid" (the line "humid" has no keyword, so it continues the previous field) and final answer "31C".
Rules: one keyword per line, checked longest-prefix first; Thought opens a step; a repeated field opens a step; plain lines continue the last field.
Observability tools for agents store traces in this shape so they can count tool calls, find failing tools and measure how many steps a task took.