Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 32 ยท Agents and Tools

ReAct Agents and create_agent

Learn the ReAct pattern (reason, act, observe) and how LangChain's create_agent implements it with tools, prompts, streaming and structured output. Includes Python stand-ins.

ReAct is the pattern behind most agents: the model reasons about what to do, acts by calling a tool, observes the result, and repeats. The name comes from combining reasoning and acting. Early ReAct agents asked the model to print "Thought / Action / Observation" lines as plain text, and a parser extracted the action. Modern chat models with native tool calling make this cleaner (the action is a structured tool call), but the cycle is the same. In LangChain, create_agent gives you a ready-made ReAct-style agent in a few lines.

LangChain and a model provider are not available on this site, so real code is read-only. The runnable examples are stand-ins: a text-format ReAct parser and a streaming-steps display, both with scripted models.

create_agent

Python
# Real LangChain (read-only)
from langchain.agents import create_agent
from langchain.tools import tool

@tool
def search_docs(query: str) -> str:
    """Search the product documentation and return the best matching passage."""
    return "Refunds are available within 30 days of purchase."

@tool
def word_count(text: str) -> int:
    """Count the words in a piece of text."""
    return len(text.split())

agent = create_agent(
    model="anthropic:claude-sonnet-4-5",
    tools=[search_docs, word_count],
    system_prompt=(
        "You are a support assistant. Always check the documentation "
        "before answering policy questions. Be brief."
    ),
)

result = agent.invoke({"messages": [{"role": "user", "content": "Can I get a refund after 3 weeks?"}]})
for message in result["messages"]:
    message.pretty_print()

The arguments you will use most:

Argument Purpose
model A provider string like "provider:model-name" or a chat model object
tools List of tools the agent may call
system_prompt Standing instructions (role, rules, tone)
response_format A schema for a final structured answer
checkpointer Saves state per thread for memory (memory lessons)
middleware Hooks around the model and tool calls (limits, summaries, approvals)

The result is a state dictionary. Its messages list contains every message in order: your question, each AIMessage with its tool calls, each ToolMessage result, and the final answer.

The classic text format

Before native tool calling, ReAct prompts looked like this, and you will still meet it in older tutorials and papers:

TEXT
Question: How many words are in "to be or not to be"?
Thought: I should count the words with the word_count tool.
Action: word_count
Action Input: to be or not to be
Observation: 6
Thought: I now know the final answer.
Final Answer: There are 6 words.

The loop stops the model after Action Input, runs the tool, appends Observation: and continues. The stand-in below parses exactly this format.

Python Stand-in: a text-format ReAct loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A real LangChain agent no longer parses text: the model returns a structured tool call. But the transcript above is a faithful picture of what is happening.

System prompts that make agents better

The system_prompt is your main steering wheel. Good ones are short and concrete.

  • Role and scope: "You answer questions about our billing policy only."
  • Tool habits: "Search the docs before answering; never guess a price."
  • Stopping rule: "If two searches find nothing, say you do not know."
  • Format: "Answer in at most three sentences."

Avoid long lists of rules; models follow a few clear ones better than a page of them. Put hard guarantees (limits, permissions) in code, not in the prompt.

Streaming the steps

Agents can take many seconds. Streaming lets a UI show each step as it happens.

Python
# Real LangChain (read-only)
for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "Can I get a refund after 3 weeks?"}]},
    stream_mode="updates",
):
    for node, update in chunk.items():
        print(node, "->", update["messages"][-1].content)

With stream_mode="updates" you get one chunk per step (the model node, then the tools node, then the model again). Other modes stream individual tokens or the full state after each step.

Python Stand-in: show each step as it happens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Structured final answers

Sometimes the last message must be data, not prose, for example {"refund_allowed": true, "days_left": 9}. create_agent accepts a schema in response_format; the final state then contains a structured_response object validated against it. Your downstream code reads typed fields instead of parsing text. The schema side of this is covered in the chapter on models, prompts and parsers on the LangChain track page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ReAct stand for in practice?

    The model reasons, acts through a tool, observes the result and repeats.
  2. 2. In the final state of create_agent, where is the conversation stored?

    The state dictionary has a messages list with every human, AI and tool message.
  3. 3. Where should hard limits such as permissions be enforced?

    Prompts are guidance and can be ignored or attacked; enforce guarantees in code.
  4. 4. What does stream_mode='updates' give you?

    Each chunk contains the update from one node (model or tools), so you can display progress.

Summary

  • ReAct is a loop of reasoning, acting with a tool and observing the result.
  • create_agent(model, tools, system_prompt, ...) builds it; the result's messages holds the full trace.
  • Text-format ReAct exists in older material; native tool calling replaces the parsing.
  • Keep prompts short and concrete, stream steps for UX, use response_format for typed answers.

Next: Agent Errors and Guardrails