Building AI Agents with LangChain Tutorial: Complete Guide from Setup to Production
Build production-ready AI agents with LangChain. Complete tutorial covering tools, memory, RAG, multi-agent systems, deployment, and monitoring.

Most LangChain tutorials on the internet teach APIs that no longer exist. LangChain 1.0, released in October 2025, replaced AgentExecutor, create_openai_tools_agent, and ConversationBufferMemory with a single create_agent function that runs on the LangGraph runtime, and moved the legacy modules into a separate langchain-classic package (release notes).
This building AI agents with LangChain tutorial teaches the current 1.0 API. You will build a working customer support agent with tools, persistent memory, automatic retries, and structured output, then add guardrails, monitoring, and a FastAPI deployment. Every code sample below works with langchain 1.x.
Why LangChain for AI Agents?
LangChain 1.0 is scoped to one job: being the fastest way to build an agent. An agent, in the framework's own definition, is a model calling tools in a loop until a task is complete. Everything around that loop (prompt, tools, middleware) is the harness, and create_agent is the harness you configure. From the official agents documentation, you get:
- Provider-agnostic models. Pass a
"provider:model"string such as"anthropic:claude-sonnet-4-6","openai:gpt-5.5", or"google_genai:gemini-3.6-flash"and swap providers by changing one line. - Tools as plain functions. Any Python callable with type hints and a docstring can be a tool; no wrapper classes required.
- Middleware. Prebuilt hooks for PII redaction, conversation summarization, human approval, and model or tool retries, plus custom hooks at every step of the agent loop.
- The LangGraph runtime. Persistence, streaming, human-in-the-loop pauses, and time travel come built in because
create_agentcompiles to a LangGraph graph.
Alternatives exist, including OpenAI's Agents SDK, Microsoft's Agent Framework, and LlamaIndex. We compared the main options in our AI agent development frameworks guide. One honest caveat up front: if your workflow is a fixed pipeline with no model-driven decisions, you do not need an agent framework at all. A plain script is cheaper and easier to test.
Prerequisites
You need:
- Python 3.10 or newer (LangChain 1.0 dropped Python 3.9, which reached end of life in October 2025)
- An API key from Anthropic, OpenAI, or Google
- About an hour
Install dependencies:
pip install -U "langchain[anthropic]"
# or, if you prefer OpenAI models:
pip install -U "langchain[openai]"
Set up environment variables:
# .env file
ANTHROPIC_API_KEY=sk-ant-...
Already running older LangChain code? pip install langchain-classic keeps the legacy imports (LLMChain, AgentExecutor, create_openai_tools_agent, ConversationBufferMemory) working while you migrate. New projects should use create_agent.
Core concepts in LangChain 1.0
The agent loop
An agent is a model calling tools in a loop until the task is done: the model reads the conversation, decides whether to call a tool, the tool runs, its result goes back into the conversation, and the loop repeats until the model answers directly. Everything you configure around that loop (the model, the tools, the system prompt, middleware) is the harness.
Models
You rarely call the model directly when building agents; you pass a model string and LangChain initializes the right provider client:
from langchain.chat_models import init_chat_model
llm = init_chat_model("anthropic:claude-sonnet-4-6", temperature=0)
response = llm.invoke("What is LangChain?")
print(response.content)
The "provider:model" format works across providers: "anthropic:claude-sonnet-4-6", "openai:gpt-5.5", "google_genai:gemini-3.6-flash". In an agent, you pass the same string to create_agent and never touch the model object yourself.
Tools are plain functions
def search_knowledge_base(query: str) -> str:
"""Search the company knowledge base for information."""
results = knowledge_base.search(query)
return results
The type hints become the tool's input schema and the docstring becomes its description. The model reads the docstring when deciding when and how to call the tool, so write it for the model, not for other developers.
Memory is a thread, not an object
ConversationBufferMemory is gone. In 1.0, an agent persists conversation history per thread when you give it a checkpointer, and you resume a conversation by reusing its thread_id. Step 3 below shows the full pattern.
Building the customer support agent
The agent answers questions from documentation, looks up order status, and creates support tickets. Three tools, one create_agent call. (If you would rather have this running in production than build it yourself, that is exactly what our customer support agents service does.)
Step 1: define the tools as plain functions
# Mock database (replace with a real DB in production)
orders_db = {
"ORD-12345": {"status": "shipped", "tracking": "1Z999AA10123456784"},
"ORD-12346": {"status": "processing", "tracking": None},
}
tickets_db = []
def search_docs(query: str) -> str:
"""Search company documentation for policy and product answers."""
docs = {
"refund": "Refunds are processed within 5-7 business days. Contact support@company.com.",
"shipping": "Standard shipping takes 3-5 days. Express shipping available.",
"returns": "Returns accepted within 30 days with original receipt.",
}
for key, value in docs.items():
if key in query.lower():
return value
return "No relevant documentation found. Please contact support."
def lookup_order(order_id: str) -> str:
"""Look up the status of an order by its ID, e.g. ORD-12345."""
order = orders_db.get(order_id.upper())
if not order:
return f"Order {order_id} not found."
status = f"Order {order_id}: status = {order['status']}"
if order["tracking"]:
status += f", tracking = {order['tracking']}"
return status
def create_ticket(issue_description: str) -> str:
"""Create a support ticket for issues that need a human."""
ticket_id = f"TKT-{len(tickets_db) + 1:05d}"
tickets_db.append({"id": ticket_id, "description": issue_description, "status": "open"})
return f"Support ticket {ticket_id} created. Our team will respond within 24 hours."
tools = [search_docs, lookup_order, create_ticket]
No decorators, no wrapper classes: any Python callable with type hints and a docstring works as a tool in 1.0.
Step 2: create the agent
from langchain.agents import create_agent
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
system_prompt="""You are a customer support agent for TechCorp.
Resolve customer issues using your tools:
- Search documentation for policy and product questions
- Look up order status when given an order ID
- Create a support ticket for issues you cannot resolve
Be polite and concise. If you don't know something, say so and create a ticket.""",
)
One call replaces the old ChatPromptTemplate + create_openai_tools_agent + AgentExecutor stack. Swap providers by changing the model string ("openai:gpt-5.5", "google_genai:gemini-3.6-flash").
Step 3: add memory with a checkpointer
There is no ConversationBufferMemory in 1.0. Give the agent a checkpointer and address each conversation with a thread_id; history is persisted and resumed automatically:
from langgraph.checkpoint.memory import InMemorySaver
from langchain_core.utils.uuid import uuid7
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
system_prompt="...", # as above
checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": str(uuid7())}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's your refund policy?"}]},
config=config,
)
print(result["messages"][-1].content)
# Follow-up on the same thread keeps the full history:
result = agent.invoke(
{"messages": [{"role": "user", "content": "And how long do returns take?"}]},
config=config,
)
InMemorySaver dies with the process. In production, use a durable checkpointer such as the Postgres implementation from langgraph-checkpoint-postgres, so conversations survive restarts.
Step 4: retries and error handling
Retries are middleware in 1.0, not hand-rolled loops:
import logging
from langchain.agents.middleware import ModelRetryMiddleware, ToolRetryMiddleware
logger = logging.getLogger(__name__)
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
system_prompt="...",
checkpointer=InMemorySaver(),
middleware=[
ModelRetryMiddleware(max_retries=3), # transient LLM API failures
ToolRetryMiddleware(max_retries=2), # flaky tool calls
],
)
def safe_chat(user_input: str, config: dict) -> str:
try:
result = agent.invoke(
{"messages": [{"role": "user", "content": user_input}]},
config=config,
)
return result["messages"][-1].content
except Exception as e:
logger.error(f"Agent failed: {e}")
return ("I'm experiencing technical difficulties. A support ticket "
"has been created and our team will contact you shortly.")
Middleware retries handle transient failures; the outer try/except is the last-resort fallback so a user never sees a stack trace.

Advanced patterns
Structured output
When downstream code needs a predictable shape, pass a Pydantic model via response_format. In 1.0, structured output is generated inside the main agent loop instead of requiring an extra LLM call:
from pydantic import BaseModel
from langchain.agents.structured_output import ToolStrategy
class SupportResolution(BaseModel):
answer: str
resolved: bool
ticket_id: str | None = None
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
response_format=ToolStrategy(SupportResolution),
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "Check order ORD-12345"}]},
config=config,
)
resolution = result["structured_response"]
Guardrails: PII redaction and human approval
Some policies cannot live in a prompt; they need deterministic enforcement. Prebuilt middleware covers the common cases:
from langchain.agents.middleware import PIIMiddleware, HumanInTheLoopMiddleware
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=tools,
checkpointer=InMemorySaver(),
middleware=[
PIIMiddleware("email", strategy="redact", apply_to_input=True),
HumanInTheLoopMiddleware(
interrupt_on={"create_ticket": {"allowed_decisions": ["approve", "edit", "reject"]}}
),
],
)
Customer email addresses are now redacted before they reach the model, and every ticket creation pauses for a human decision. Because the agent runs on the LangGraph runtime, its state checkpoints while it waits — a human-in-the-loop pause costs nothing and survives restarts.
Streaming
Stream tokens and tool activity in real time instead of waiting for the full run:
for chunk in agent.stream(
{"messages": [{"role": "user", "content": "What's your shipping policy?"}]},
config=config,
stream_mode="messages",
):
print(chunk)
Multi-agent systems
For teams of specialized agents, Deep Agents builds on create_agent with planning, file system tools, subagents, and memory already assembled. Reach for it — or for LangGraph directly, when you need full control over the graph — once a single agent with good tools stops being enough.
RAG (Retrieval-Augmented Generation)
Integrate vector search for knowledge-intensive tasks:
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
# Load and chunk documents
loader = TextLoader("company_docs.txt")
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = text_splitter.split_documents(documents)
# Create vector store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(chunks, embeddings)
# Create retrieval tool (a plain function)
def search_knowledge_base(query: str) -> str:
"""Search the company knowledge base using semantic similarity."""
results = vectorstore.similarity_search(query, k=3)
return "\n\n".join(doc.page_content for doc in results)
# Recreate the agent with the retrieval tool added
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[search_docs, lookup_order, create_ticket, search_knowledge_base],
system_prompt="...",
checkpointer=InMemorySaver(),
)
Monitoring and Observability
Production agents need logging and tracing:
LangSmith integration
import os
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = "ls-..."
os.environ["LANGSMITH_PROJECT"] = "customer-support-agent"
# Every agent run is now traced: model calls, tool calls, latency, tokens
result = agent.invoke(
{"messages": [{"role": "user", "content": user_query}]},
config=config,
)
(The old LANGCHAIN_TRACING_V2 variable was renamed in 1.0.) Traces show every model call, tool invocation, latency, and token counts in the LangSmith dashboard.
Custom logging
import logging
from datetime import datetime, timezone
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def logged_chat(user_input: str, config: dict) -> str:
start = datetime.now(timezone.utc)
try:
result = agent.invoke(
{"messages": [{"role": "user", "content": user_input}]},
config=config,
)
answer = result["messages"][-1].content
logger.info({
"user_input": user_input,
"agent_output": answer,
"latency_ms": (datetime.now(timezone.utc) - start).total_seconds() * 1000,
"status": "success",
})
return answer
except Exception as e:
logger.error({"user_input": user_input, "error": str(e), "status": "error"})
raise
Deployment Patterns
REST API with FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class ChatRequest(BaseModel):
message: str
session_id: str
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
try:
# The session_id becomes the thread_id, so each customer's
# history persists (with a durable checkpointer) and resumes automatically
config = {"configurable": {"thread_id": request.session_id}}
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": request.message}]},
config=config,
)
return {"response": result["messages"][-1].content}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Run: uvicorn app:app --host 0.0.0.0 --port 8000
Async processing for scale
import asyncio
async def handle_batch(requests):
tasks = [
agent.ainvoke(
{"messages": [{"role": "user", "content": req.message}]},
config={"configurable": {"thread_id": req.session_id}},
)
for req in requests
]
return await asyncio.gather(*tasks)
Docker deployment
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
Testing AI agents
Unit test tools directly, and agent behavior with a fresh thread:
import pytest
def test_search_docs():
result = search_docs("refund policy")
assert "5-7 business days" in result
def test_lookup_order():
result = lookup_order("ORD-12345")
assert "shipped" in result.lower()
def test_agent_response():
config = {"configurable": {"thread_id": "test-1"}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's your shipping policy?"}]},
config=config,
)
assert result["messages"][-1].content
Integration tests with real LLM calls:
@pytest.mark.integration
def test_agent_end_to_end():
config = {"configurable": {"thread_id": "test-e2e"}}
r1 = agent.invoke(
{"messages": [{"role": "user", "content": "Hi, I need help"}]},
config=config,
)
assert r1["messages"][-1].content
# Same thread: the follow-up must see the earlier turn
r2 = agent.invoke(
{"messages": [{"role": "user", "content": "Check order ORD-12345"}]},
config=config,
)
assert "shipped" in r2["messages"][-1].content.lower()
Common pitfalls and fixes
- Agent loops forever. Cap the loop with a recursion limit: pass
{"recursion_limit": 10}in the config. If it still loops, the tool results are not answering the question — improve what the tools return. - Agent ignores its tools. The docstring is the tool's pitch to the model. Say exactly when to call the tool and what the inputs look like, with an example in the docstring.
- Context window overflows. Add
SummarizationMiddlewareto condense long histories instead of hand-pruning messages. - High latency. Stream responses (
stream_mode="messages"), and check whether your tools are the bottleneck — a slow database lookup usually dominates the model. - Inconsistent behavior. Set
temperature=0on the model and useresponse_formatfor anything downstream code parses.
What it costs to run
LLM API cost is the dominant expense, and it scales with the tokens in the conversation history — which grows every turn. Worked example: a support agent handling 50,000 conversations a month, each averaging 6,000 input tokens (system prompt plus history) and 800 output tokens, burns 300 million input and 40 million output tokens monthly.
Using current OpenAI API pricing (verified November 2026), that workload costs roughly:
- GPT-6 Luna ($0.10 / $0.50 per 1M input/output tokens): $50/month
- GPT-6.1 Terra ($1.00 / $5.00): $500/month
- GPT-6.1 Sol ($2.00 / $10.00): $1,000/month
Ways to pull the number down:
- Cache everything repeatable. Static system prompts, tool definitions, and retrieved documentation can be served from the provider's prompt cache at a steep discount (OpenAI advertises up to 90% off cached input tokens).
- Route easy queries to a small model. Most support questions do not need a frontier model.
- Keep prompts lean. A bloated system prompt is paid for on every single turn.
If building and operating this is not where you want your engineers spending time, our AI employees service runs agents like this as a managed deployment.
For a deeper treatment, see our guides to AI agent cost optimization and reducing agent response latency.
When LangChain is the wrong choice
- A simple chatbot with no tools. If the model never calls functions, skip the agent framework and call the provider's API directly — fewer dependencies, fewer surprises.
- You need deterministic, branching workflows. Agents are dynamic loops. If you know the exact steps a process must take, model it as an explicit graph in LangGraph (or plain code) instead of letting a model improvise.
- Your team is not on Python. LangChain has a JavaScript/TypeScript version, but on other stacks a thin client around the model API may serve you better.
- You need heavyweight orchestration from day one. Multiple cooperating agents, planners, and shared memory are Deep Agents or LangGraph territory; do not bolt them onto a single
create_agentloop.
Frequently asked questions
Is LangChain free to use? The framework is open source under the MIT license. You pay for the model API (Anthropic, OpenAI, or Google) and for LangSmith observability if you outgrow its free tier.
Can I use OpenAI or Google models instead of Anthropic?
Yes. Change the model string — "openai:gpt-5.5" or "google_genai:gemini-3.6-flash" — and install the matching extra (langchain[openai] or langchain[google-genai]). The rest of the code is unchanged.
Do I need langchain-classic?
Only if you are migrating an existing codebase that imports LLMChain, AgentExecutor, or ConversationBufferMemory. New projects should use create_agent directly.
How do conversations survive a server restart?
Swap InMemorySaver for a durable checkpointer such as langgraph-checkpoint-postgres. The thread_id pattern stays the same; history then lives in a database instead of process memory.
LangChain or LangGraph?
Start with LangChain's create_agent. Move to LangGraph when you need explicit control over the graph: custom branching, long-running durable workflows, or orchestration the standard agent loop cannot express.
Where to go from here
The code above runs as-is; the work that turns it into a reliable product is the tooling, guardrails, retrieval, and evaluation around it. If you would rather have a production support agent built and operated for you, look at our customer support agents service, or our AI employees for broader agent deployments.
Related reading
About AI Agents Plus Editorial
AI automation expert and thought leader in business transformation through artificial intelligence.



