LangChain Best Practices: 12 Rules for 2026
Updated November 2026. This guide targets LangChain v1 and LangGraph 1.x. New to the stack? Start with install and the smallest agent; legacy LLMChain, Agent, and initialize_agent code is maintenance-only.
Quick answer: the LangChain best practice in 2026 is to treat LangChain as a thin agent harness, not as a giant chain library. Start with create_agent, define typed tools, use provider-native structured output, add retries and call limits through middleware, trace every run with LangSmith, and keep deterministic orchestration in LangGraph. Pin packages, evaluate regressions before deploys, and move secrets and tool permissions out of prompts.
How to Install LangChain
LangChain v1 is a thin agent harness: you get create_agent, typed tools, and middleware hooks, and you bring the rest. Install it into a pinned virtual environment so the runtime matches your lockfile.
python -m venv .venv
source .venv/bin/activate
pip install -U "langchain>=1.0" "langchain-openai>=1.0"
Install a provider package for the model you actually use (langchain-openai, langchain-anthropic, or another integration). Pin langchain, langchain-core, langgraph, and the provider package in a lockfile; practice 1 explains why.
How to Use LangChain: The Smallest Agent
The shortest useful path is init_chat_model plus create_agent: initialize a chat model, pass it the tools it may call, and invoke the agent with a message list. This is the smallest version; practice 2 adds a typed tool, and the reference implementation adds structured output, retries, tracing, and an approval gate. If you are migrating a 2023 tutorial, do not copy an LLMChain example; read the migration section first.
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
model = init_chat_model(os.environ["MODEL_ID"], temperature=0)
agent = create_agent(model=model, tools=[])
result = agent.invoke({"messages": [{"role": "user", "content": "Explain LangChain in one paragraph."}]})
print(result["messages"][-1].content)
What Changed in LangChain v1
LangChain v1, released in October 2025, is a smaller and more opinionated framework than the 2023 chain library. The core change is create_agent, which replaces langgraph.prebuilt.create_react_agent as the standard way to build an agent. LangChain describes the agent as model + harness: the model, tools, prompt, and middleware around the model loop. The agent is built on LangGraph, so persistence, streaming, human approval, and time travel come from the runtime rather than from custom wrapper code.
The package namespace was also simplified. Legacy functionality moved to langchain-classic, while langchain.agents now exposes the agent factory and agent state. That means most 2023 tutorials are not just stylistically old; they import modules and patterns that are no longer the default path.
| Older pattern | 2026 replacement | Why |
|---|---|---|
LLMChain for every prompt |
Plain function, LCEL pipeline, or create_agent |
Less indirection; the agent loop is explicit when you need tools. |
initialize_agent / Agent |
create_agent |
Standard factory with middleware, structured output, and LangGraph runtime. |
langchain.llms.OpenAI |
init_chat_model or provider integration |
One model interface across providers and chat/message semantics. |
| Custom memory code | LangGraph checkpointer or Agent Server | Durable state, replay, and human-in-the-loop support. |
| Ad-hoc print debugging | LangSmith traces and evals | Tool calls, retries, latency, and token use become observable. |
If you are starting a new project, build on the v1 APIs. If you maintain an older codebase, migrate deliberately; do not mix langchain-classic agents into a new create_agent loop just to reuse one old tool.
LangChain Best Practices: 12 Rules That Matter Most
1. Pin packages and lock the dependency graph
LangChain packages version independently and move quickly. Pin langchain, langchain-core, langgraph, and every provider package in a lockfile. Upgrade them in a branch, run the evaluation suite, and only then deploy.
uv add "langchain>=1.0" "langchain-core>=1.0" "langgraph>=1.0" "langchain-openai>=1.0"
uv lock
Do not let a container rebuild silently resolve newer minor versions. The most common “the agent broke overnight” report is a dependency change, not a model change.
2. Start with create_agent, not a custom chain
create_agent gives you the standard loop: call the model, execute any requested tools, feed the results back, and finish when the model stops calling tools. It also accepts middleware, structured output settings, and a checkpointer. Build the smallest harness that works before adding custom orchestration.
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
model = init_chat_model(os.environ["MODEL_ID"], temperature=0)
agent = create_agent(
model=model,
tools=[search_docs],
system_prompt="Answer from the provided documentation. Cite the source path.",
)
3. Keep the agent loop explicit
An agent is not a magic chatbot. It is a model call plus a bounded tool loop. Decide what the model may do, what it may not do, and when the loop must stop. Put that policy in code and middleware, not only in the system prompt.
For deterministic workflows, use LangGraph directly. For a simple question-answer flow, use a model call or a two-step LCEL pipeline. Reaching for an agent when a function would do is a reliability and cost regression.
4. Define typed tools with clear contracts
Tools are the agent’s public API. Give each tool a precise name, docstring, input schema, timeout, and error contract. Validate arguments before they reach a database, shell, or external service.
from pydantic import BaseModel, Field
from langchain_core.tools import tool
class SearchInput(BaseModel):
query: str = Field(description="Natural-language search query")
limit: int = Field(default=5, ge=1, le=20)
@tool(args_schema=SearchInput)
def search_docs(query: str, limit: int = 5) -> str:
"""Search the internal documentation and return short excerpts."""
...
Return compact, structured tool output. Dumping an entire web page or database row into the context window increases latency, cost, and prompt-injection exposure.
5. Use structured output instead of parsing prose
Pass a Pydantic model to response_format and read structured_response. LangChain selects provider-native structured output when the model supports it and falls back to tool calling when it does not. This removes fragile “extract the JSON from the answer” code.
from pydantic import BaseModel, Field
class SupportAnswer(BaseModel):
answer: str
confidence: float = Field(ge=0, le=1)
citations: list[str] = Field(default_factory=list)
agent = create_agent(
model=model,
tools=[search_docs],
response_format=SupportAnswer,
)
result = agent.invoke({"messages": [{"role": "user", "content": "How do I rotate an API key?"}]})
print(result["structured_response"])
Keep the schema small. If a field is optional in the product but required in the schema, the model will hallucinate a value to satisfy validation.
6. Add retries, fallbacks, and call limits through middleware
Network failures and malformed tool arguments are normal. Middleware is the correct place for cross-cutting behavior because it applies consistently to every model and tool call. Use model retry, tool retry, fallback, summarization, and call limits rather than nesting try/except blocks around every step.
from langchain.agents.middleware import (
ModelRetryMiddleware,
ToolRetryMiddleware,
)
agent = create_agent(
model=model,
tools=[search_docs],
middleware=[
ModelRetryMiddleware(max_retries=2, backoff_factor=2.0),
ToolRetryMiddleware(max_retries=2, on_failure="continue"),
],
)
Set a hard model-call or tool-call limit for every production agent. Without a budget, a confused loop can spend money until an external timeout kills it.
7. Persist state and require approval for sensitive tools
create_agent runs on LangGraph, so you can use checkpointing for multi-turn state and human-in-the-loop middleware for dangerous actions. A tool that sends email, changes infrastructure, issues refunds, or writes to production should pause for approval or run in a sandbox.
from langchain.agents.middleware import HumanInTheLoopMiddleware
agent = create_agent(
model=model,
tools=[search_docs, send_email],
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={
"send_email": {"allowed_decisions": ["approve", "edit", "reject"]}
}
)
],
)
Do not model authorization as a prompt instruction. A prompt can be overridden; a tool policy and an approval gate cannot.
8. Trace every run with LangSmith
Enable tracing before you need it. LangSmith records the model call, tool calls, retrieved documents, token usage, latency, and errors. That is the difference between “the bot gave a bad answer” and “retrieval returned the wrong chunk after the second tool call.”
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=<your-key>
export LANGSMITH_PROJECT=langchain-production
Trace production samples, not only local demos. Keep sensitive payloads out of traces or redact them before export; traces are production data.
9. Evaluate with a regression dataset
Build a small dataset of real questions with expected answers, required citations, and forbidden claims. Run it on every prompt, model, tool, or dependency change. Measure task success, citation validity, latency, and cost per successful answer.
A single “looks good” manual test is not an evaluation. LangSmith datasets and experiments make the comparison repeatable, and they catch regressions that a smoke test cannot see.
10. Treat tools and retrieved content as untrusted
Prompt injection often arrives through a web page, PDF, issue, or tool result, not through the user’s first message. Use allowlists for tools, least-privilege credentials, per-tool timeouts, and sandboxed execution. Redact PII before it reaches the model when the workflow does not need it.
from langchain.agents.middleware import PIIMiddleware
agent = create_agent(
model=model,
tools=[search_docs],
middleware=[
PIIMiddleware("email", strategy="redact", apply_to_input=True),
],
)
Never give an agent broad shell or database credentials because “it is internal.” Scope credentials to the specific operation and environment.
11. Control cost and latency deliberately
Use the smallest model that passes the evaluation suite. Cache stable retrieval and model responses where the product allows it. Stream user-visible output, batch offline work, and route easy requests to a cheaper model. Put a token budget and timeout on every request.
Measure cost per successful task, not cost per token. A cheap model that fails and retries three times is often more expensive than a stronger model that succeeds once.
12. Deploy as a stateless service with versioned configuration
The API process should be stateless; conversation state belongs in a checkpointer or external store. Put requests on a queue when traffic exceeds worker capacity, set concurrency limits, and expose health and readiness checks. Version the prompt, model, tool set, and middleware configuration together.
Roll out a new agent version to a small traffic slice, compare traces and evaluation results, and keep the previous version deployable. “It worked in the notebook” is not a production readiness signal.
Reference Implementation
This skeleton combines the practices above. It is intentionally small: one model, one typed tool, structured output, retries, tracing, and an approval gate for a dangerous action.
import os
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.agents.middleware import (
HumanInTheLoopMiddleware,
ModelRetryMiddleware,
ToolRetryMiddleware,
)
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
class SearchInput(BaseModel):
query: str = Field(description="What to search for")
limit: int = Field(default=5, ge=1, le=10)
class FinalAnswer(BaseModel):
answer: str
citations: list[str] = Field(default_factory=list)
@tool(args_schema=SearchInput)
def search_docs(query: str, limit: int = 5) -> str:
"""Search internal documentation and return short excerpts."""
...
@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email after human approval."""
...
model = init_chat_model(os.environ["MODEL_ID"], temperature=0)
agent = create_agent(
model=model,
tools=[search_docs, send_email],
system_prompt="Answer from documentation.",
response_format=FinalAnswer,
middleware=[
ModelRetryMiddleware(max_retries=2),
ToolRetryMiddleware(max_retries=2, on_failure="continue"),
HumanInTheLoopMiddleware(
interrupt_on={"send_email": {"allowed_decisions": ["approve", "reject"]}}
),
],
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "Summarize the API key rotation policy."}]},
config={"configurable": {"thread_id": "support-123"}},
)
print(result["structured_response"])
In production, replace thread_id with your own tenant-scoped conversation ID, store checkpoints in a durable database, and add authentication before the request reaches the agent.
LangChain Best Practices: Migration and Common Mistakes
Two practical checks close out the guide: migrate old chains deliberately, and avoid the production mistakes that survive demos.
Migrating Legacy LangChain Code
Do not rewrite everything at once. Put a seam between the legacy chain and the new agent, then migrate one workflow at a time.
- Inventory imports. Find
LLMChain,initialize_agent,AgentExecutor,langchain.llms, and custom memory. - Replace the model layer. Move to
init_chat_modelor a provider integration so the rest of the code uses messages and content blocks. - Replace the loop. Use
create_agentfor tool-using workflows; use LangGraph for deterministic multi-step workflows. - Move cross-cutting behavior to middleware. Retries, limits, PII, summarization, and approvals should not be duplicated in each chain.
- Add traces and evals before cutover. Compare old and new outputs on the same dataset, then route a small percentage of traffic to the new path.
Legacy packages are still available in langchain-classic, but keeping new code on the v1 surface prevents two incompatible agent styles from spreading through the codebase.
Common Production Mistakes
- Putting policy in the prompt only. Tool permissions, allowlists, and approval gates belong in code.
- Using an agent for a deterministic task. A function, SQL query, or LCEL pipeline is cheaper and easier to test.
- Returning raw tool output. Large or untrusted outputs increase cost and prompt-injection risk.
- No call limit. A loop with no budget can run until the provider times out.
- No trace sampling. You cannot debug production failures from aggregate error rates alone.
- Upgrading packages without evals. Minor releases can change model integration behavior.
Sources and Further Reading
- LangChain: What’s new in LangChain v1 ,
create_agent, middleware, structured output, and the simplified package. - LangChain overview , model + harness, LangGraph, and LangSmith guidance.
- Structured output ,
response_format, provider strategy, and tool strategy. - Prebuilt middleware , retries, fallbacks, call limits, PII, and human-in-the-loop.
- LangSmith observability , tracing and evaluation.
- LangChain and LangGraph v1.0 announcement.
- Related Sesame Disk guides: RAG evaluation and CI/CD testing, chunking methods, and RAG stack comparison.
