Courses / Agentic AI from Scratch (Python)

Session 21 of 40

Writing tools, and building an agent with LangChain's create_agent

Notes

How to Write a Tool for an AI Agent and Build It With LangChain create_agent

Agentic AI Foundations · Session 21 — Writing tools, and building an agent with LangChain’s create_agent

Before you start: what do I need before I write a tool and build an agent?

You need the code folder for this session open in your terminal. It holds agent_tools.py, make_tickets_db.py, data/tickets.csv with five sample tickets, data/policies/ with the 5 policies, and the copilot carried over from session 19 (helpdesk_rag.py and search.py) with build_index.py and load_policies.py. Install the libraries with pip install langchain langchain-openai langchain-chroma langchain-community langchain-text-splitters. You need the settings from earlier sessions (LLM_BASE_URL, LLM_API_KEY, LLM_MODEL, EMBED_MODEL), and the model must support tool calling. Two files are not in the lesson folder: policy_index/ and tickets.db, which you build with python build_index.py and python make_tickets_db.py. Python’s sqlite3 module is part of the standard library, so there is usually nothing extra to install for the database; the Python documentation calls it an optional module, so if the import fails, check your Python distribution. Recap of what this session assumes: an agent is a model that calls tools in a loop until the task is complete, and your code runs each tool (session 20). Have paper or a notes app ready for the Flashcards and the Model answer.

Summary: what is a LangChain tool, and what does create_agent do?

A tool is a Python function with a name, a description the model reads, and typed inputs, and the model picks a tool from those three things. In LangChain you mark the function with the @tool decorator, and the function name, docstring and type hints become the tool’s name, description and input schema. You then hand a model, a list of tools and a system prompt to create_agent, which returns an agent that runs the loop for you. When two tools have similar descriptions the model can pick the wrong one, so you write each description to say what the tool is for and what it is not for, and you test the choice on sample questions. This session’s agent has three tools: a calculator, a ticket lookup that reads a SQLite database with the id passed as a ? value, and the session-19 copilot as a policy tool.

Key concepts: LangChain tool and create_agent terms explained in plain English

Term Definition
Tool A function the model may ask your code to run, with a name, a description and typed inputs.
Tool description The plain-English text, taken from the function’s docstring, that tells the model when to use the tool.
Input schema The list of inputs a tool accepts, defined by the function’s type hints, that the model fills in.
@tool decorator The marker that turns a Python function into a tool the agent can be given.
create_agent LangChain’s function that builds an agent from a model, a list of tools and a system prompt.
System prompt The standing instructions given to the agent; here they are read from model_prompts/agent.md.
ask_policy The tool that hands a policy question to session 19’s ask_helper and returns the answer with its source.
SQLite A lightweight database stored in one file that needs no separate server process.
Parameterised query A SQL query where values are passed separately through placeholders such as ?, so text from outside is not read as SQL.

Explanations: how do you write a tool and build an agent with create_agent?

What is a tool, and how do you write one for an agent?

Failure first. An employee asks, “Who owns ticket T-1042?” and the agent, which has a policy tool and a ticket tool, calls the policy tool and replies that no clause was found. Both tools had descriptions like “find information”, so the model could not tell which one fitted.

Think of a restaurant menu. The diner chooses from the description of each dish, and the kitchen does the cooking. Or think of two buttons on a form: the label says what each does, and pressing one is somebody else’s job. A tool works the same way: it is a function the model may ask your code to run, and the model decides when to use it from the conversation and from what the tool says about itself. The three things the model sees are the name, the description and the inputs:

@tool
def lookup_ticket(ticket_id: str) -> str:
    """Find one help desk ticket by its id, such as T-1042.
    Returns its title, status and assignee.
    Use it when the question names a ticket. Do not use it
    for questions about company policy."""

In LangChain, the function name becomes the tool’s name, the docstring becomes the tool’s description by default, and type hints are required because they define the input schema. Prefer plain letters, digits, underscores and hyphens in a name, because other characters can cause trouble with some providers. Notice that the docstring gives an example id, so the model knows what a ticket id looks like, and that it says what the tool is not for.

How does the description steer the model’s choice between tools?

Picture unlabelled doors: a visitor guesses and sometimes guesses wrong. Label them “Tickets” and “Policies” and the visitor walks to the right one. The model is that visitor. In agent_tools.py each docstring says what its tool is for and what it is not for, because two tools that both sound like “find information” get confused:

Tool What the description says it is for What it says it is not for
lookup_ticket One help desk ticket by its id, such as T-1042 Questions about company policy
ask_policy Questions about leave, expenses, IT security, remote work, learning Looking up tickets
calculate Any arithmetic sum with numbers (nothing stated)

Here is how the agent should route four kinds of question:

The employee asks The agent should call Why
“What is the status of T-1042?” lookup_ticket The question names a ticket id
“How much is the home-office allowance?” ask_policy The answer is in a policy
“What is 12 times 3?” calculate Arithmetic is better done by code
“Hello, who are you?” No tool The prompt says to skip the tools when no sum, ticket or policy is involved

Writing is half the work; testing is the other half. Run a sample question of each kind and read which tool the agent called. If a choice is wrong, change the description, not the model, and run the questions again. The README’s experiment makes the point: change both docstrings to "Find information." and see whether the agent still chooses correctly.

How do you look up a ticket in SQLite from a tool?

A card index in a drawer holds one card per ticket: you pull out the card with the number you want. A spreadsheet that answers questions works the same way, with a row per ticket and columns for id, title, status and assignee. SQLite is a lightweight disk-based database that lives in one file and needs no separate server process, and Python’s standard library talks to it through the sqlite3 module. python make_tickets_db.py loads the five tickets from data/tickets.csv into tickets.db; it prints Saved 5 tickets to tickets.db. The tool then reads a record instead of guessing one:

row = connection.execute(
    "SELECT id, title, status, assignee FROM tickets WHERE id = ?",
    (ticket_id.strip().upper(),)).fetchone()
if row is None:
    return f"No ticket {ticket_id} exists."

The id goes in through the ? mark as a separate value. Python’s documentation warns that building a query with string operations is vulnerable to SQL injection, and says to use the database interface’s parameter substitution instead. Text from a model is input you do not control, so treat it the way you would treat text typed by a stranger. The id is also tidied with .strip().upper(), so t-1042 still finds T-1042. And a ticket that does not exist is a normal answer: the tool returns a sentence and does not raise an error, so the model can report it. Real failures, such as a database that cannot be opened, are the subject of session 22.

How do you use the copilot as a tool?

A help desk has a policy expert in the next room. The agent at the front desk does not memorise the policies; it knows when to ask the expert. ask_policy is that arrangement in code: it hands the question to session 19’s ask_helper, which does the search and the cited, checked answer, and returns the answer with its source:

reply = ask_helper(question)     # session 19's copilot
if reply is None:
    return "The policy helper failed."
return f"{reply['answer']} (source: {reply['source']}, ...)"

If the copilot itself says “I don’t know”, the tool passes that on. The agent does not search the policies itself: its job is to decide when to ask. That is why helpdesk_rag.py, search.py, build_index.py and load_policies.py are in this folder unchanged, and why you run python build_index.py first; it prints Saved 34 chunks to policy_index/.

What is create_agent and how do you give it tools?

Think of a kit with a manual: the model is the brain, the tools are the parts and the system prompt is the manual. Or a shop assistant with a name badge: the prompt says who they are, and the tools say what they can reach. create_agent is LangChain’s function for building an agent from those pieces. You import it from langchain.agents, and it takes the model, the tools (Python functions or LangChain tools) and a system_prompt, the standing instructions that shape how the agent approaches tasks.

agent = create_agent(
    model,
    tools=[calculate, lookup_ticket, ask_policy],
    system_prompt=system_text)

model_prompts/agent.md lists the three tools and when to use each, says a question may need more than one tool, says to skip the tools when they are not needed, and tells the agent to base its answer on what the tools return and to say plainly when a tool finds nothing. As in session 20, agent.invoke returns the whole conversation as a list of messages, and show_steps prints each tool request (act), each result (observe) and the answer. The message list keeps the conversation history, adding new messages instead of replacing old ones.

What does the agent print for each kind of question?

Run python agent_tools.py. Ours printed these four runs (long lines trimmed with ...):

question: What is the status of ticket T-1042?
  act     : lookup_ticket({'ticket_id': 'T-1042'})
  observe : T-1042: Carry over ... status: open | assignee: Priya
answer: Ticket T-1042 is open and assigned to Priya. ...

question: How much is the home-office allowance?
  act     : ask_policy({'question': 'home office allowance'})
  observe : The company pays a one-time home-office allowance of 150 ...
answer: The company pays a one-time home-office allowance of 150 ...

question: Who owns T-1042, and what does the policy say about ...
  act     : lookup_ticket({'ticket_id': 'T-1042'})
  act     : ask_policy({'question': 'carrying over leave days'})
  observe : T-1042: Carry over ... status: open | assignee: Priya
  observe : Up to 5 unused annual-leave days can be carried over ...
answer: Priya owns T-1042. You can carry over up to 5 unused ...

question: Who owns ticket T-9999?
  act     : lookup_ticket({'ticket_id': 'T-9999'})
  observe : No ticket T-9999 exists.
answer: I can't find ticket T-9999. It might not exist.

Read the act lines. The ticket question went to lookup_ticket, the policy question to ask_policy, and the third question needed both, so the model asked for two tools in one turn. The last question shows a missing ticket: the tool returned a sentence and the agent reported it. Ask your own: python agent_tools.py "What is 12 times 3?".

What goes wrong with tools in practice, and what does it mean for the design?

Before the design table, three situations you will meet:

  1. A ticket question goes to the policy tool and comes back “nothing found”. Both descriptions said “find information”, so the model had no clue which to pick.
  2. The lookup fails when the model passes t-1042 in lower case. The input was not tidied inside the tool, so a small difference broke it.
  3. A query built by gluing the model’s text into the SQL gives odd results for a crafted ticket id. The text was treated as part of the query instead of as a value.

What these mean for the design:

What you learned The design decision Where it shows
The model reads name, description and inputs Write each description for the model The @tool docstrings
Similar descriptions get mixed up Say what each tool is for and is not for lookup_ticket, ask_policy
Model text is input you do not control Pass values through ? and tidy ids lookup_ticket
The agent picks from its tool list Test the choice on one question of each kind python agent_tools.py

Basic assignment: run python build_index.py, python make_tickets_db.py and python agent_tools.py. For each of the four questions, write down which tool the agent used, and say which question needed two.

Project step: break the descriptions. Change the docstring of lookup_ticket and of ask_policy to "Find information." and ask the ticket question again. Add a ticket to data/tickets.csv, run python make_tickets_db.py again and ask about it. Ask a question no tool covers, such as "What is the capital of France?", and read what the agent says. The build prompts are prompts/1-write-make-tickets-db.md and prompts/2-write-agent-tools.md. Stop when you can say whether the choice changed and why.

Flashcards: test yourself on LangChain tools and create_agent

Say the answer aloud before revealing it. Speaking is a different skill from reading, so practise both.

1. What is a tool in an agent? A tool is a function the model may ask your code to run. It has a name, a plain-English description that tells the model when to use it, and typed inputs that tell it what to pass.
2. Where do a LangChain tool's name, description and inputs come from? From the decorated function: the function name is the tool's name, the docstring is its description by default, and the type hints define the input schema.
3. Why did the agent send a ticket question to the policy tool? Both tools had descriptions like "find information", so the model had nothing to tell them apart. Rewrite each description to say what it is for and what it is not for.
4. What does create_agent take, and what does it return? It takes a model, a list of tools and a system prompt, and returns an agent that runs the reason, act, observe loop. You invoke it with a messages list and read the last message.
5. What does ask_policy do? It hands a policy question to session 19's copilot, `ask_helper`, and returns the answer with its source, or the copilot's "I don't know". The agent's job is to decide when to ask.
6. How do you check which tool an agent picked? Run a question of each kind, such as a ticket, a policy, a sum and a greeting, and read the printed `act` lines to see which tool, if any, the agent asked for.
7. Why should a missing ticket return a sentence, not raise an error? "No ticket exists" is a normal answer, and the model can report it to the employee. An exception would be a failure, which session 22 handles separately.
8. Why pass the ticket id through a ? mark? Text from a model is input you do not control. A parameter is treated as a value, while gluing it into the SQL lets it be read as part of the query, which is how SQL injection works.
9. What is SQLite, and why use it here? It is a lightweight database kept in one file with no separate server. That makes it easy to run the sample tickets on your laptop and read real records from a tool.
10. What does it mean when one question prints two act lines? The model asked for two tools in one turn because the question needed both, such as a ticket's owner and a policy about its subject. Each result comes back as an observe line.

Model answer: how do I explain LangChain tools and create_agent in an interview?

The core question this session answers: “A teammate asks: the agent keeps using the policy tool for ticket questions. How do you write tools so the model picks the right one, and how do you check?”

Four beats a teammate listens for, in this order: describe for the model · type the inputs · hand them to the agent · test the choice. Skip any of these four and the answer is incomplete.

  1. Describe for the model: say what the tool is for and what it is not for.
  2. Type the inputs: the type hints define what the model passes.
  3. Hand them to the agent: a model, the tools and a system_prompt.
  4. Test the choice: run sample questions and read which tool ran.

The full answer, said aloud:

(Describe for the model) “I write each description for the model: what the tool is for and what it is not for, with an example id, so two tools do not sound alike.

(Type the inputs) I type the inputs, because the type hints become the schema the model fills in.

(Hand them to the agent) I give the tools to create_agent with a model and a system prompt.

(Test the choice) Then I test the choice on one question of each kind and read which tool the agent called, and I fix the description if it is wrong.“

Missing a beat is a failure state. The follow-up question lands where you went quiet: leave out the last beat and the next question is how you know it works. Practise until the four come out without prompting, then stop talking and let the questions come.

Why this matters: why do agent tools and create_agent matter at work?

In a conversation with a teammate or manager: when an assistant does the wrong thing, the first question is which tool it used and why. Knowing that descriptions steer the choice gives you a fix that does not involve a new model.

On the job: an assistant that reaches a database, a calendar or a ticket system usually does it through tools. The description, the inputs and how a missing record is handled are the parts you review.

In the rest of this course: session 22 makes tools fail safely, sessions 23 to 28 route questions to the right tool in a graph, and sessions 29 to 32 offer tools from outside servers using the same ideas.

After this unit: what do I do after this lesson, and what comes next?

Assignment. Run the four questions in agent_tools.py and write down which tool each used. The brief for the project work, breaking the two descriptions on purpose, is the project file. Keep agent_tools.py: the next session adds an error catcher and a step limit to it.

What’s next. Session 22 is about failure: catching a tool error in one place and telling the model what went wrong, replying “I can’t” instead of guessing, and putting a step limit on the loop.

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by OpenAI, Anthropic, LangChain or any other company named in this course.