AI Hints
LangChain · Lesson 44 of 120

create_agent

The easy way.

⏱ 2 min read▶ Video at 48:17🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

LangChain's create agent function builds the whole loop for you. Give it a model and some tools, and it returns an agent that runs until the question is answered.

create_agent
From the video: create_agent
  • create_agent
  • A model plus tools
  • The loop is built for you

Your first agent

We pass the model string, and the check stock tool, to create agent. We invoke it with a messages list, just like a chat model. Run it. The result holds the whole conversation. The user's question, the model's tool call, the tool's answer, and the final reply. The agent ran the loop for us.

first_agent.pypython
from langchain.agents import create_agent
from langchain.tools import tool

@tool
def check_stock(title: str) -> int:
    """Return how many copies of a book Riverside Books has in stock."""
    return {"Dune": 3, "Circe": 0}.get(title, 0)

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[check_stock])
result = agent.invoke({"messages": [{"role": "user", "content": "Is Dune in stock?"}]})

for m in result["messages"]:
    print(f"{type(m).__name__:<12} {m.text or m.tool_calls[0]['name'] + str(m.tool_calls[0]['args'])}")
Output
HumanMessage Is Dune in stock?
AIMessage    check_stock{'title': 'Dune'}
ToolMessage  3
AIMessage    Yes, "Dune" is in stock with 3 copies available.

What create_agent gives you

Create agent gives you a lot. The tool loop, with tool messages handled correctly. Streaming of every step. Memory, by adding a checkpointer. Structured answers. And middleware, to customise everything. Under the hood, it's built on LangGraph, which we'll mention again at the end of the course.

keyvalue
Tool loophandled for you
Streamingevery step
Memorywith a checkpointer
Middlewarecustomise anything

Summary

Create agent builds a complete tool using agent from a model and tools. The result contains every message in the loop. Next, giving an agent several tools.

Key takeaways
  • create_agent(model, tools)
  • invoke with messages
  • Every step recorded
Next up: Several Tools — choosing the right one