Agents
Last lesson you wrote a loop by hand. Ask the model, run tools, ask again.
An agent is that loop, already built for you.
You give it a model and some tools. It decides which tools to use, in what order, until the job is done.
Install LangGraph
Agents live in the langgraph package. It is made by the LangChain team.
Build an agent in three lines
create_react_agent takes a model, a list of tools, and a prompt. It returns a ready agent.
The prompt is the system message. It sets the agent's personality and rules.
Run the agent
The input is a dictionary with a list of messages. The output is the same dictionary, with more messages added.
Print the list and you see the whole story. Human question, tool requests, tool results, final answer.
The last message is what you show to the user.
Think, act, observe
The agent runs a small loop. It repeats until the model answers without asking for a tool.
Think: the model reads the messages and decides what to do next
Act: if it picked a tool, the agent runs that tool
Observe: the tool result is added to the messages
Repeat: back to think, until the model gives a plain answer
That is why it is called a ReAct agent. Reason, then act.
Watch it work with stream
stream gives you each step as it happens. Good for showing progress.
stream_mode=values gives the full state after every step. We print only the newest message each time.
A tool that touches the real world
Tools can do anything Python can do. Here is one that reads a file.
The agent picks read_file, gets the text, then writes the summary. You did not tell it the steps.
Be careful what you hand over
The agent decides on its own which tool to call. If a tool can delete files or spend money, the agent can do that too.
Start with read only tools. Add write tools later, slowly.
Never give an agent a tool that runs any shell command it wants.
Set limits inside the tool itself. Check paths, check amounts, refuse bad input.
Ask a human before the dangerous steps.
Remember: an agent is a model in a loop with tools. It is only as safe as the tools you give it.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.