Building AI Agents with LangChain: The Complete Guide in 9 Chapters

Large language models can write, summarise, and reason, yet on their own they cannot look anything up, call an API, remember yesterday’s conversation, or take a single action in the world. LangChain exists to close that gap. It is an open-source framework that connects a language model to data, tools, and other systems, and turns a chat endpoint into an agent that can work through a task step by step. This guide explains the framework as it stands in its 1.x line: what each piece does, how the pieces fit together, and how to take a first agent from a notebook experiment to a service you can trust.

1. What LangChain Is — and What It Is Not

LangChain is a framework for building applications powered by large language models, and since its 1.0 release its centre of gravity is the agent: a model that calls tools in a loop until a task is complete. The framework supplies the parts around that loop — a standard interface for chat models, prompts, tools, retrieval, and memory — so that a developer composes an application from interoperable components instead of wiring every provider API by hand.

It is worth stating plainly what LangChain is not. It is not a model: it ships no weights of its own and trains nothing. It is not a hosting platform for agents, although its sibling product LangSmith Deployment covers that need. And it is not a shortcut that removes engineering judgement. An agent built on LangChain still needs careful prompts, well-chosen tools, limits on what it may do unsupervised, and observation of its behaviour in production. The framework makes those concerns manageable; it does not make them disappear.

The project is developed in the open under the MIT licence, in Python and in JavaScript and TypeScript. Its main repository, langchain-ai/langchain, was created in October 2022 and has grown into one of the most widely used open-source projects in applied AI, with more than 150,000 stars on GitHub at the time of writing. That scale matters for a practical reason: when a framework is this widely used, its integrations, examples, and failure modes are all well documented by the community around it.

LangChain logo
The LangChain logo. Copyright © 2025 LangChain, Inc., used under the MIT License.

2. One Ecosystem, Four Layers: LangChain, LangGraph, Deep Agents, and LangSmith

Newcomers often confuse LangChain with the other names that orbit it, so the official documentation now draws the map explicitly. There are four layers, each with a distinct job.

LangChain itself is the framework layer. It provides the high-level agent harness, create_agent, together with model interfaces, prompts, tools, and retrieval components. When you write application code, this is the layer you usually touch first.

LangGraph is the runtime underneath. It is a low-level orchestration framework for stateful workflows, and every LangChain agent compiles down to a LangGraph graph. Because of that, a LangChain agent inherits durable execution, persistent state, streaming, and human-in-the-loop support without extra code. When a workflow needs custom topology — branching, fan-out, deterministic steps mixed with agentic ones — you drop down to LangGraph directly. When a workflow needs custom topology, you drop down to LangGraph directly, as covered in our guide to building stateful agents with LangGraph.

Deep Agents is a higher-level harness built on LangChain for long, multi-step work. It adds planning, subagents, a virtual filesystem, and context compression out of the box, and it is the recommended starting point when you want a capable agent without assembling those pieces yourself. It is available as a managed service or as a SDK you host.

LangSmith is the observability layer: tracing, debugging, and evaluation for agents built with any of the other three. Setting the environment variable LANGSMITH_TRACING=true with an API key starts recording traces of every model call, tool call, and state transition, which is the single most useful step you can take when an agent misbehaves.

The layers nest rather than compete. A typical production system uses LangChain to define the agent, LangGraph as its runtime, Deep Agents when the task is long and messy, and LangSmith to watch all of it.

3. The Road to 1.0: What Changed and Why Stability Matters

LangChain 1.0 was released on 22 October 2025, together with LangGraph 1.0, as the first major version of both frameworks. The release was deliberately a refinement rather than a reinvention: it introduced the create_agent abstraction as the standard way to build an agent, added a middleware system for customising the agent loop, standardised the content blocks that models return across providers, and moved legacy modules into a separate langchain-classic package. With 1.0 the project committed to no breaking changes until version 2.0.

That commitment is the most important thing about the release for anyone choosing a framework. In its early years LangChain changed quickly, and code written against one version often needed rework for the next. The 1.x line is designed to end that churn: the surface area is smaller, the agent story is centred on one loop, and the old constructors — AgentExecutor, create_react_agent, the legacy LLMChain class — live on only in langchain-classic for code that cannot yet be migrated.

The current release at the time of writing is langchain 1.5.2, published on 18 November 2026, which requires Python 3.11 or later. Minor releases in the 1.x line continue to add capabilities — middleware, execution environments, context management — without breaking the stable core.

4. Installation and Your First Agent

Installation follows the pattern of a modern Python library with provider integrations kept in separate packages. As a code block:

# pip install -U langchain
# pip install -U langchain-openai

The core package contains the framework; each model provider lives in its own package, so you install only the integrations you use. The documentation recommends Python 3.11 or later, and the same code can target different providers by changing a model identifier string such as "openai:gpt-5.5", which keeps an application portable as model choices evolve. If you prefer to run models locally, the same agent code can point at a local server; see our guide to running Ollama locally. For routing many providers through a single interface, see our LiteLLM gateway guide.

A first agent needs only three ingredients: a model, a list of tools, and a system prompt. The framework’s own quickstart shows the shape of it — a small function offered to the model as a tool, wrapped in create_agent, and invoked with a message. That is the whole pattern: everything else in this guide is a refinement of those three ingredients.

5. The Agent Loop: Model, Tools, and Prompt

An agent, in LangChain’s definition, is a model calling tools in a loop until a given task is complete. The loop itself is simple, and understanding it explains most of the framework’s design. The agent sends a request to the model; the model either calls a tool or gives a final answer; if it called a tool, the framework executes it, appends the result to the conversation, and asks the model again. The cycle repeats until the model answers directly or a configured limit is reached.

create_agent is the harness around that loop. The word harness matters: it means everything surrounding the model call — the prompt, the tools, and any middleware that shapes behaviour. At its simplest you pass a model identifier, a list of tools, and a system prompt. The model can be given as a "provider:model" string or as an initialised model instance, and the system prompt accepts a plain string or a structured system message.

Every agent manages its execution context through a typed state object, AgentState, whose built-in field is messages: the full conversation history for the current thread, treated as append-only. Custom fields — a user identifier, a counter, a piece of application state — are added by subclassing AgentState and passing the subclass to create_agent. Middleware hooks receive that same state and return updates to merge back into it, which is how the framework keeps the loop both simple and extensible.

Two safety details deserve attention from the start. The default recursion limit is 9,999 steps, which means an agent that keeps calling tools will run for a very long time unless you intervene; production agents should pass a lower recursion_limit or cap model calls with the dedicated middleware. And the agent stops only when the model decides to answer — so the system prompt and the tool descriptions are not decoration, they are the controls that determine when the work is done.

6. Tools: Giving the Agent Something to Do

A model without tools can only talk. Tools are what let an agent act, and LangChain accepts almost anything as a tool: any Python callable, a LangChain tool object, or a tool dictionary. In practice most developers define tools with the @tool decorator, which turns an ordinary function and its docstring into a tool with a name, a description, and a typed input schema derived from the function’s signature. The description matters more than it looks: it is what the model reads when deciding which tool to call, so a vague description produces vague tool use.

As a code block:

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


@tool
def convert_units(value: float, from_unit: str, to_unit: str) -> str:
    """Convert a measurement between units, for example kilometres to miles."""
    factors = {("km", "miles"): 0.621371, ("miles", "km"): 1.60934}
    factor = factors.get((from_unit, to_unit))
    if factor is None:
        return f"Conversion from {from_unit} to {to_unit} is not supported."
    return f"{value} {from_unit} is {value * factor:.2f} {to_unit}."


agent = create_agent(
    model="openai:gpt-5.5",
    tools=[convert_units],
    system_prompt="You are a helpful assistant. Use the conversion tool for unit questions.",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "How many miles are 42 kilometres?"}]},
    config={"configurable": {"thread_id": "demo-thread"}},
)
print(result["messages"][-1].content_blocks)

Tools can also reach outside the process. The framework supports tools served over the Model Context Protocol, which lets one agent use tools exposed by other servers; our guide to the Model Context Protocol. And tools can be given runtime context — a user identifier, an API key, a feature flag — passed per invocation rather than baked into the tool, so the same agent serves different users safely.

Good tool design follows three rules. Keep each tool narrow: one job, clearly described. Make failures informative: a tool that returns a clear error message lets the model recover, while a crash ends the run. And never give an agent a tool you would not trust a careful junior colleague with, because the model will eventually use it in a way you did not anticipate.

7. LCEL: Composing Chains with the Pipe Operator

Not every task needs an agent. For fixed pipelines — classify this text, summarise that document, translate and then format — LangChain offers the LangChain Expression Language, LCEL: a declarative way to compose components with the pipe operator. A prompt, a model, and an output parser become one chain. As a code block:

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_template("Summarise this text in one sentence: {text}")
model = ChatOpenAI(model="gpt-5.5")

chain = prompt | model | StrOutputParser()
print(chain.invoke({"text": "LangChain connects language models to tools and data."}))

The pipe takes the output of the left-hand component and feeds it into the right-hand one, and the resulting chain is itself a component that can be composed further. The practical payoff is that every chain gets streaming, batch processing, asynchronous execution, and fallback handling without extra code: chain.stream yields tokens as they arrive, chain.batch runs many inputs concurrently, and chain.with_fallbacks retries with an alternative when the first attempt fails. Parallel branches are expressed with RunnableParallel, conditional routing with RunnableLambda, and any plain function can be wrapped as a step in the chain.

LCEL replaced the older chain classes: LLMChain was deprecated in version 0.1.17 and removed from the core in 1.0. For new code the pipe operator is the expected style, and it is also the right default whenever the steps are known in advance. Reach for an agent when the model itself must decide what to do next; reach for LCEL when you already know the steps and only want them composed cleanly.

Source code on a computer screen
Source code on a developer’s screen. Photograph by Martin Vorel, licensed under CC BY-SA 4.0.

8. Memory, Context, and Keeping a Human in the Loop

An agent that forgets the conversation after one exchange is of limited use, and an agent that remembers everything eventually drowns in its own context window. LangChain handles both sides of that tension with a small set of mechanisms.

Short-term memory is handled by a checkpointer combined with a thread_id: each conversation thread keeps its checkpoints, and passing the same thread identifier resumes the conversation where it left off. Because create_agent compiles to a LangGraph graph, this persistence comes from the runtime rather than from application code. For longer conversations, summarisation middleware compresses history before the context window fills, memory middleware loads persistent instructions at startup so knowledge carries across sessions, and skills surface domain knowledge on demand instead of loading everything up front.

Context management is where many production agents succeed or fail, and it connects directly to retrieval: when an agent needs facts rather than conversation history, a retriever supplies them. Our guide to building RAG applications with LlamaIndex.

Full autonomy is not always appropriate, and the framework provides steering for the moments when it is not. Human-in-the-loop middleware pauses the agent before a destructive write, an expensive call, or any step that needs judgement; a person approves, edits, or rejects, and execution continues. Guardrails complement this by enforcing rules deterministically: PII middleware, for example, intercepts sensitive data as it flows through the loop regardless of what the model does. Retries for rate limits and transient errors are handled the same way, as middleware, so tools and business logic stay free of defensive code.

9. From Prototype to Production: Tracing, Evaluation, and Deployment

A prototype agent that works in a notebook and a production agent that works for users are separated by three disciplines: observation, evaluation, and controlled deployment.

Observation starts with LangSmith tracing, enabled with LANGSMITH_TRACING=true and an API key. A trace shows every model call, tool call, state transition, and latency figure in one place, which turns “the agent gave a strange answer” from a mystery into a sequence of steps you can inspect. LangSmith Engine builds on those traces to monitor them, detect issues, and propose fixes.

Evaluation means deciding, before you ship, what good behaviour looks like and measuring it. LangSmith provides datasets and evaluators for that purpose, and the habit that matters most is a small one: keep a set of real example tasks, run the agent against them after every change, and compare the results. An agent’s behaviour drifts as models, prompts, and tools change, and only a repeatable evaluation catches that drift before users do.

Deployment is the last step, and the framework’s design makes it less disruptive than it used to be. Because create_agent compiles to a LangGraph graph, the same agent can move from a script to a server without changing its runtime, persistence, or observability. LangSmith Deployment offers a purpose-built platform for long-running, stateful workflows, and the Python deployment guide in the official documentation covers serving the application yourself. Whichever route you choose, carry the same three production habits across it: a low recursion limit, human approval for irreversible actions, and tracing switched on from day one.

Summary

LangChain 1.x is a smaller, steadier framework than its early versions: one agent loop built on create_agent, one runtime in LangGraph, one composition language in LCEL, and one observability layer in LangSmith. Start with a model, a few well-described tools, and a clear system prompt. Add memory through checkpointers, context through summarisation and retrieval, and control through middleware — human approval, guardrails, and retries — only as the use case demands them. And measure the agent with tracing and evaluation from the beginning, because an agent you cannot observe is an agent you cannot improve. Built that way, LangChain turns a language model from a text generator into a working component of a real system.

Sources

LangChain overview — official documentation

Agents — official documentation

Install LangChain — official documentation

LangChain and LangGraph reach v1.0 — official blog

LangChain Expression Language — official blog

langchain-ai/langchain on GitHub

langchain on PyPI

1 thought on “Building AI Agents with LangChain: The Complete Guide in 9 Chapters”

Leave a Comment