LangChainLangChain 1.4 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
43 small wins to finish your pathNext lesson

create_agent: the agent loop

Lesson 6 ran one round trip by hand. create_agent runs that loop for you: call the model, run the tools it asks for, and call it again until it answers with text.

An agent is a model and tools in a loop. create_agent takes a model, a list of tools and an optional system_prompt, and returns an agent you call with a conversation.

Exampleagent.py
from langchain.agents import create_agent
from shop_model import ShopModel
from tools import lookup_order

agent = create_agent(
    ShopModel(),
    tools=[lookup_order],
    system_prompt="You help customers of a small online shop.",
)

tools.py is the file from lesson 5 and shop_model.py the one from lesson 6. Nothing ran yet: the agent is ready to take a conversation, as a dictionary with a messages list.

Four messages

Example
result = agent.invoke({"messages": [{"role": "user", "content": "Where is my order A17?"}]})

for message in result["messages"]:
    print(f"{message.type:<6} {message.text or message.tool_calls}")

The human message is what you sent. The first AI message has no text, only a tool call; the agent saw that and ran the tool. The tool message is the result, and the last AI message is the answer, written after the model read it. Text without tool calls is what ended the loop.

The system prompt is not in the list. The agent adds it to every model call without storing it with the conversation.

A question with no order

Example
result = agent.invoke({"messages": [{"role": "user", "content": "Hello there"}]})

for message in result["messages"]:
    print(f"{message.type:<6} {message.text or message.tool_calls}")

Two messages. The model answered with text on the first call, so no tool ran and the loop ended at once. The model decides how many times the loop goes round, not the agent.

Try it yourself
  • Ask about B22, an order the shop does not have, and read the final answer.
  • Remove lookup_order from the tools and ask about A17 again.
  • Print result.keys() to see what else the agent returns.

You understood something today that you didn't yesterday.