Course contentsShow
← AI Engineering
Lesson 646 of 1,88616. AI Agents - ImplementationFree lesson

Final Answer Detection and Extraction

Implement logic to recognize when the agent has completed reasoning and extract the final answer for the user.

Final Answer Detection and Extraction

What you'll learn: How to identify when your ReAct agent has finished reasoning and confidently extract its final answer for the user.

The Core Challenge

After your ReAct agent cycles through multiple reasoning and action steps, it eventually reaches a conclusion. But how does your code know when the agent is done thinking versus still working? And once done, how do you cleanly extract just the answer—not the whole chain of thought—to present to the user?

This is where final answer detection comes in: scanning the agent's output for specific markers that signal completion.

How It Works

ReAct agents typically signal completion with explicit markers like:

  • Final Answer: [the actual answer]
  • Answer: [result]
  • Similar structured formats you've defined in your prompt

Your implementation must:

  1. Parse each agent output looking for these markers
  2. Extract the content that follows the marker
  3. Terminate the agent loop once detected
  4. Return the extracted answer to the user

Think of it like a scavenger hunt: the agent leaves breadcrumbs (reasoning steps), but eventually plants a flag labeled "FINAL ANSWER" with the treasure underneath. Your job is to spot that flag and grab what's beneath it.

Detection Pattern Example

if "Final Answer:" in agent_output:
    answer = agent_output.split("Final Answer:")[1].strip()
    return answer

You're using string matching or regex to identify the completion signal, then extracting everything after it. Some implementations check if the agent stopped calling tools and provided answer-like text.

Why This Matters

Without proper detection, your agent might loop forever or you'd return raw reasoning traces instead of clean answers. The user wants "The capital is Paris," not five paragraphs of internal deliberation.

Key Takeaway: Final answer detection uses pattern matching to recognize completion signals in agent output, extract the clean answer, and gracefully terminate the reasoning loop.