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.
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_agentfrom langchain.tools import tool@tooldef 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.
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.
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.