LangChain Tutorial: Build Your First AI Agent Step-by-Step

Step-by-step LangChain tutorial to BUILD your first AI agent in Python. Covers tools, memory, and the ReAct pattern. Start building now.

Quick Answer: Install LangChain with pip install langchain langchain-openai, define your tools, create a ReAct agent, and invoke it — you can have a working AI agent in under 15 minutes.


LangChain is the most popular framework for building AI agents in Python, with over 38 million monthly PyPI downloads. This LangChain tutorial walks you through building your first agent from scratch — no machine learning experience required, just basic Python.

By the end, you'll have a working agent that reasons about problems, calls external tools, and returns structured answers. If you're building AI agents for your team, platforms like cowork.ink can help you orchestrate and deploy them at scale.

What You'll Build

A ReAct agent that can search the web, do math, and answer multi-step questions — the same pattern used in production AI systems.

What Is LangChain and Why Use It?

LangChain is an open-source Python framework that makes it easy to build applications powered by large language models (LLMs). Instead of writing raw API calls, LangChain gives you composable building blocks — prompts, chains, tools, memory, and agents — that snap together.

Here's why developers choose LangChain over direct API calls:

  • Abstraction over LLM providers — switch between OpenAI, Anthropic, Google, or open-source models with one line of code
  • Built-in agent patterns — the ReAct loop, tool calling, and planning are handled for you
  • Rich tool ecosystem — web search, calculators, databases, APIs, and hundreds of community integrations
  • Memory management — conversation history, summarization buffers, and persistent storage
  • Production-ready — LangChain's agent runtime now runs on LangGraph, a battle-tested orchestration engine
FeatureDirect API CallsLangChain
Model switchingRewrite code per providerChange one class
Tool integrationBuild from scratchPlug-and-play
Agent loopsManual implementationBuilt-in ReAct pattern
MemoryDIY state managementManaged buffers
ObservabilityCustom loggingLangSmith integration

Prerequisites

Before starting this LangChain tutorial, make sure you have:

  1. Python 3.9 or later installed (python.org)
  2. An OpenAI API key (or any supported LLM provider)
  3. Basic Python knowledge — variables, functions, and pip
  4. A terminal or IDE — VS Code, PyCharm, or a Jupyter notebook all work
No OpenAI Key?

You can follow this tutorial with any LangChain-supported model. We use OpenAI as the example, but the code works with Anthropic, Google Gemini, or local models via Ollama.


Step 1 — Install LangChain

Create a virtual environment and install the required packages:

python -m venv langchain-env
source langchain-env/bin/activate  # Windows: langchain-env\Scripts\activate

pip install langchain langchain-openai langchain-community

The langchain package is the core framework. langchain-openai adds the OpenAI integration, and langchain-community includes community tools like web search.

Set your API key as an environment variable:

export OPENAI_API_KEY="sk-your-key-here"

Verify the installation:

import langchain
print(langchain.__version__)

Step 2 — Create Your First Chain

Before building an agent, let's start with a simple chain — the fundamental building block in LangChain. A chain connects a prompt template to an LLM:

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

# Initialize the model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# Create a prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant that explains concepts simply."),
    ("human", "{input}")
])

# Combine into a chain using the pipe operator
chain = prompt | llm

# Run it
response = chain.invoke({"input": "What is an AI agent?"})
print(response.content)

The | (pipe) operator is LangChain's way of composing components. Data flows left to right — from prompt to model. This is called LangChain Expression Language (LCEL).


Step 3 — Define Custom Tools

Tools are what turn a plain LLM into an agent. A tool gives your model the ability to take actions — search the web, query a database, run calculations, or call external APIs.

Here's how to define custom tools:

from langchain_core.tools import tool

@tool
def multiply(a: float, b: float) -> float:
    """Multiply two numbers together."""
    return a * b

@tool
def get_word_count(text: str) -> int:
    """Count the number of words in a text string."""
    return len(text.split())

# LangChain also has built-in tools
from langchain_community.tools import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()

The @tool decorator automatically converts your function into a LangChain tool. The docstring becomes the tool description that the LLM reads to decide when to use it — so write clear, specific descriptions.

Tool Descriptions Matter

The LLM decides which tool to call based entirely on the tool's name and description. Vague descriptions like "does stuff" will confuse the agent. Be specific: "Multiply two numbers together and return the result."


Step 4 — Build a ReAct Agent

Now combine everything into an agent. The ReAct pattern (Reasoning + Acting) is the default and most reliable agent architecture in LangChain:

from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

# 1. Initialize the model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 2. Collect your tools
tools = [multiply, get_word_count, search]

# 3. Create the agent with tool binding
agent = llm.bind_tools(tools)

LangChain's modern API uses bind_tools() to attach tools directly to the model. The model then uses native function calling (not text parsing) to invoke tools reliably.

For a full agent loop with automatic tool execution, use AgentExecutor or the newer LangGraph-based approach:

from langgraph.prebuilt import create_react_agent

# Create a complete ReAct agent with LangGraph runtime
agent_executor = create_react_agent(llm, tools)

# Run the agent
result = agent_executor.invoke({
    "messages": [("human", "Search for the population of Tokyo and multiply it by 2")]
})

print(result["messages"][-1].content)

Here's what happens under the hood:

  1. Reason — the LLM reads the question and decides it needs to search first
  2. Act — it calls the search tool with "population of Tokyo"
  3. Observe — it reads the search result (approximately 14 million)
  4. Reason — it decides to call multiply next
  5. Act — it calls multiply(14000000, 2)
  6. Observe — it gets 28,000,000
  7. Answer — it formats and returns the final response

Step 5 — Add Memory to Your Agent

A stateless agent forgets everything between calls. To build conversational agents, you need memory:

from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver

# Create an agent with memory
memory = MemorySaver()
agent = create_react_agent(llm, tools, checkpointer=memory)

# First message
config = {"configurable": {"thread_id": "user-123"}}
agent.invoke(
    {"messages": [("human", "My name is Alice")]},
    config=config
)

# Second message — the agent remembers
result = agent.invoke(
    {"messages": [("human", "What's my name?")]},
    config=config
)
print(result["messages"][-1].content)
# Output: "Your name is Alice!"

The MemorySaver checkpointer persists conversation state across invocations. The thread_id groups messages into separate conversations — essential when building multi-user applications.


Step 6 — Handle Errors and Edge Cases

Production agents need guardrails. Here are the patterns that matter:

from langchain_core.tools import tool
from langchain_core.runnables import RunnableConfig

@tool
def divide(a: float, b: float) -> str:
    """Divide a by b. Returns an error message if b is zero."""
    if b == 0:
        return "Error: Cannot divide by zero."
    return str(a / b)

Common pitfalls and how to avoid them:

  • Infinite loops — set max_iterations on your agent (default is 15 in LangGraph)
  • Tool errors — always return error messages as strings instead of raising exceptions
  • Token limits — use trim_messages to keep conversation history within context windows
  • Hallucinated tool calls — write precise tool descriptions and validate inputs
Set a Token Budget

LLM costs add up fast when agents loop. Always set max_iterations and monitor token usage. A runaway agent can burn through your API budget in minutes.


Choosing the Right LangChain Components

LangChain's ecosystem has grown large. Here's what to use when:

ComponentUse WhenSkip When
LangChainSimple agents, chains, RAGComplex multi-agent workflows
LangGraphStateful workflows, branching logicQuick prototypes
LangSmithDebugging, evaluation, monitoringJust getting started
LangServeDeploying agents as APIsUsing your own FastAPI
LCEL (pipes)Composing prompt → model → parserSingle LLM call

If you're comparing LangChain with other frameworks, our CrewAI vs LangChain comparison breaks down the trade-offs for multi-agent use cases.


From Tutorial to Production

Building a working agent is step one. Deploying it for a team is where things get interesting. Here's the path:

  1. Local prototype — what you just built
  2. Add observability — connect LangSmith for tracing and debugging
  3. Deploy as an API — wrap your agent with FastAPI or LangServe
  4. Scale to a team — use cowork.ink to orchestrate agents across your engineering workflow, with shared context and team-wide visibility

Whether you're building AI agents from scratch, following our Python agent tutorial, or chaining together existing tools, LangChain gives you the foundation. The framework handles the plumbing so you can focus on what your agent actually does.


Get Started

You now have everything you need to build your first LangChain agent. The complete code from this tutorial fits in a single Python file — clone it, swap in your API key, and start experimenting.

For teams ready to move beyond prototypes, cowork.ink lets you deploy, monitor, and collaborate on AI agents from a shared workspace — no infrastructure setup required.

Frequently Asked Questions

Is LangChain free to use?
Yes. LangChain is an open-source MIT-licensed framework and completely free. You only pay for the LLM API calls you make (OpenAI, Anthropic, etc.). LangChain Academy also offers free introductory courses.
How long does it take to learn LangChain?
Developers with Python experience can learn LangChain basics in 2–4 weeks. Reaching production-ready proficiency — including RAG, deployment, and error handling — typically takes 3–6 months of self-study or 6–10 weeks with structured coaching.
What is the difference between LangChain and LangGraph?
LangChain is a high-level framework for building LLM-powered applications including chains, agents, and RAG pipelines. LangGraph is a lower-level orchestration library (also by LangChain Inc.) that uses directed graphs for complex, stateful agent workflows. LangChain's agent API is now built on top of LangGraph. See our [LangGraph tutorial](/blog/langgraph-tutorial/) for a deep dive.
What is the ReAct pattern in LangChain?
ReAct stands for "Reasoning + Acting." The agent alternates between thinking about the problem, calling a tool, and observing the result. This loop repeats until the agent reaches a final answer. It is the default agent pattern in LangChain.
Can I use LangChain with models other than OpenAI?
Absolutely. LangChain supports Anthropic Claude, Google Gemini, open-source models via Ollama, and any provider available through OpenRouter. Swap the model class and API key — the rest of your code stays the same.
Home Blog Company