🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LangChain Quickstart: Your First Tool-Using Agent

đŸŸĸ Free Lesson

What LangChain actually gives you

A language model on its own returns text. To do useful work it needs three things wrapped around it: a structured way to describe callable functions, a loop that feeds tool results back into the model, and a consistent message format that survives multiple turns. LangChain provides those three as reusable components, plus a large catalog of integrations for models, vector stores and data sources.

The main building blocks you will touch in a first project are small. A model is a thin wrapper over a provider SDK such as OpenAI or Anthropic, normalizing their different message formats. A tool is a Python function with a type-annotated signature and a docstring, which the framework converts into a JSON schema the model can read. An agent is a loop: the model decides whether to call a tool, the framework executes it, the result goes back into the conversation, and the model decides again until it stops.

ConceptWhat it isWhat you write
ModelWrapper around an LLM APIModel name and API key
ToolA callable with a schemaFunction, type hints, docstring
MessagesTyped conversation turnsHuman, AI and tool messages
AgentDecide, act, observe loopUsually one factory call
RunnableComposable unit of workOptional, used for chains
The LangChain agent loopUserAgent loopdecide, call, observeToolsModelAnswer

Setup that survives more than ten minutes

Install the core packages and the provider integration you plan to use. Keep the key out of the source tree; load it from the environment so it never lands in version control.

pip install langchain langchain-openai langgraph python-dotenv
python
# .env holds OPENAI_API_KEY=sk-...
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

load_dotenv()
assert os.environ.get("OPENAI_API_KEY"), "set OPENAI_API_KEY before running"

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
reply = llm.invoke("Reply with exactly one word: ready")
print(reply.content)   # ready

Two habits pay off immediately. Set temperature to zero while you build, so tool selection is reproducible while you debug. And pin the model name to a versioned identifier rather than an alias that the provider can silently update.


Tools are contracts, not just functions

The model never reads your Python source. It reads the JSON schema generated from your signature and docstring, which means the docstring is the only description of when the tool should be used. Write it as an instruction to a colleague who has no other context, including the failure case.

python
from langchain_core.tools import tool


@tool
def get_weather(city: str) -> str:
    """Current weather for a city.

    Use this whenever the user asks about temperature, rain or
    conditions outside. Call it even if you think you already know
    the answer, because your training data is out of date.
    """
    catalog = {"new york": "72F, sunny", "london": "55F, rainy",
               "tokyo": "68F, cloudy"}
    return catalog.get(city.lower(),
                       f"No weather station data for {city}")


@tool
def calculator(expression: str) -> str:
    """Evaluate an arithmetic expression such as '12 * (4 + 3)'.

    Use for any math the user asks for. Do not use it for unit
    conversion; there is no conversion tool available.
    """
    allowed = set("0123456789+-*/(). %")
    if not set(expression) <= allowed:
        return "Error: only digits and basic operators are supported"
    try:
        return f"The result is {eval(expression, {'__builtins__': None}, {})}"
    except Exception as exc:
        return f"Error: {exc}"

Notice the defensive details. The calculator rejects any character outside a whitelist instead of evaluating arbitrary Python, and every failure path returns a string rather than raising, because the model can only recover from information it receives back.


Assembling the agent and reading its trace

With LangGraph's prebuilt agent, wiring is one call. What matters is learning to inspect the message list it returns, because that list is where almost every bug becomes visible.

python
from langgraph.prebuilt import create_react_agent

agent = create_react_agent(model=llm, tools=[get_weather, calculator])

result = agent.invoke({
    "messages": [{"role": "user",
                  "content": "Is it warmer in New York or London?"}]
})

for message in result["messages"]:
    print(f"{message.type:12} {getattr(message, 'content', '')[:90]}")

A healthy trace for that question shows a human message, an AI message containing a tool call for New York, a tool message with the weather string, a second tool call for London, a second tool message, and finally an AI message that compares the two. If you instead see a direct answer with no tool calls, the model decided it already knew the answer, which usually means the system prompt should state that tool use is required for weather questions.

💡Debug the trace before the prompt

Print every message, including tool calls and tool results. Nine out of ten agent bugs are a wrong argument, an exception string the model could not interpret, or a tool that returned nothing useful.


Messages, state, and why streaming matters

Underneath every abstraction the agent manipulates a list of typed messages. Human messages carry user input, AI messages carry either plain content or a set of tool calls, and tool messages carry the result of one call keyed back to the identifier in its AI message. Understanding that list is understanding the whole system, because the model's next reply is a function of it and nothing else.

The state object an agent returns contains that list under a messages key, and it is yours to inspect, persist and replay. In a chat application you will usually trim it: keep the last few turns in full, summarize older turns, and never resend tool payloads the model has already consumed, since they are often the largest part of the history. Getting this wrong is the most common cause of surprise bills, because a conversation about weather can carry kilobytes of tool output on every subsequent question.

Streaming deserves a place in your first project rather than later. A tool-using turn takes seconds, and a blank terminal for three seconds feels broken. Requesting streamed tokens and printing them as they arrive turns the wait into visible progress, and it also surfaces malformed tool calls early, since you can watch the model typing arguments before the call executes.

One more habit saves debugging time: persist the message list alongside each user session, including the tool results. When a user reports that the agent did something odd last Tuesday, the stored trace tells you which tool ran with which arguments and what it returned. Without that record you are reconstructing behavior from memory, which is how regressions ship.

When LangChain is the right tool, and when it is not

LangChain earns its keep when your project will grow: more tools, more providers, retrieval, or structured output. Its abstractions make swapping a model a one-line change and keep tool schemas consistent across providers. That leverage is worth the extra layer.

It is the wrong tool for a script that calls one model once, where the wrapper adds installation weight and a versioning surface for nothing. It is also worth knowing that the library has churned its high-level agent APIs repeatedly; pin your dependency versions, and prefer the lower-level primitives such as tools and message types, which have stayed stable across releases.


Common failure modes on day one

SymptomUsual causeFix
Authentication error at first callKey never loaded into the environmentLoad dotenv before constructing the model
Agent answers without calling toolsDocstrings do not say when to use themAdd explicit usage and refusal guidance
Tool errors every timeExceptions bubble up instead of stringsCatch inside the tool and return text
Same question gives different answersTemperature above zeroSet temperature to zero while developing
Tool called with invented argumentsSignature missing type hintsAdd annotations to every parameter

Common Mistakes

Writing one-word docstrings such as 'Get weather' and expecting reliable tool selection

Fix: Describe when to use the tool, when not to, and what the return value contains

Letting tool exceptions propagate to the agent loop

Fix: Catch inside the tool and return a readable error string so the model can adapt or apologize

Evaluating arbitrary user input with eval and no restrictions

Fix: Whitelist characters or parse the expression properly, and never expose builtins

Debugging agent behavior by editing prompts blindly

Fix: Print the full message list first; the trace almost always names the real problem

Best Practices

  • Pin model versions and library versions while iterating, and set temperature to zero
  • Keep every tool's side effects explicit in its docstring, including cost and irreversibility
  • Return strings from tools, never raised exceptions, so the model can reason about failures
  • Load secrets from environment variables and assert their presence before the first call
  • Log tool inputs and outputs; they are the audit trail for anything an agent does in production

Interview Questions

Q1: What does the framework actually send to the model about a tool?

A JSON schema derived from the function name, type-annotated signature and docstring. The Python source never leaves your process, so those three fields are the entire contract.

Q2: Why should tools return error strings instead of raising?

The agent loop can only react to content in the message list. An exception stops the loop, while a readable error string lets the model retry with different arguments or explain the problem to the user.

Q3: How do you debug an agent that never uses its tools?

Print the full trace to confirm no tool calls are present, then inspect the docstrings and the system prompt. Missing usage guidance is the most common cause, followed by a model that was asked a question it could answer from memory.

Q4: When would you skip LangChain entirely?

For a single model call with no tools or retrieval, where a direct provider SDK call is shorter, faster to install and easier to audit.

Key Takeaways

  • LangChain standardizes models, tools, messages and the decide-act-observe loop
  • Tool docstrings and type hints are the only things the model sees, so they carry the whole contract
  • Build tools that return strings for every outcome, including errors
  • Reading the message trace resolves most agent bugs faster than prompt changes
  • Temperature zero and pinned versions make development reproducible
  • The framework pays off as tools and providers multiply, and gets in the way for one-shot scripts
  • Watch for API churn and prefer stable low-level primitives
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert AI Agents Beginner Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement