Complete Guide to LangChain in Production
Run LangChain in production: LCEL chains, agents, memory, streaming, RAG, retries, observability and FastAPI deployment patterns that survive real traffic.
Introduction
Your chain works in the notebook. Then you deploy it and three things break in the first week: an agent loops on a tool call and burns through your token budget, a chain that felt instant locally takes 40 seconds under concurrency, and a routine pip install -U breaks half your imports because LangChain moved a class between packages.
LangChain is a framework that wraps LLM calls behind composable abstractions — Runnable objects you chain together with the | operator, swap, stream, and batch. It trades a thick abstraction layer for composition speed: you get chains, agents, memory, retrievers, and callbacks out of the box, at the cost of an extra dependency that changes fast and hides the network calls it makes on your behalf.
This guide covers what the tutorials skip: which abstraction to reach for (and when LangChain itself is the wrong choice), how to keep agents from looping on your credit card, how to stream and fall back under load, and how to test chains without paying for API calls. It assumes you know Python and have made at least one direct call to an LLM API.
How LangChain Fits in Production
Everything in modern LangChain speaks the Runnable protocol — a standard interface with invoke, stream, batch, and their async variants. A prompt template is a Runnable. A chat model is a Runnable. An output parser is a Runnable. LCEL (LangChain Expression Language) is the | operator that wires them into pipelines:
That uniform interface is the whole point. Because chain.stream() works on every Runnable, streaming, retries, fallbacks, tracing, and batching all come free once you compose with | instead of writing your own orchestration.
The cost shows up elsewhere. LangChain is a fast-moving target: classes migrate between langchain, langchain_core, langchain_community, and partner packages like langchain_openai or langchain_chroma. Pin your versions and read the release notes before upgrading — the FAQ covers the strategy. There’s also a real overhead tax: a direct openai SDK call is one HTTP request, while a composed chain serializes inputs, runs callbacks, and adds milliseconds of framework work per step. For most applications that’s noise; for a hot path doing thousands of simple calls per minute, it’s a reason to skip the framework.
Choosing Your Abstraction
The most common production mistake is reaching for an agent when a chain would do. Use this table before you write code:
| Need | Reach for | Skip |
|---|---|---|
| Fixed sequence: prompt → model → parse | LCEL ` | ` chain |
| Fan-out over many inputs | abatch / RunnableParallel | Sequential loops |
| Model chooses tools dynamically | Tool-calling agent + AgentExecutor | Hand-rolled loops |
| Multi-step workflows with state, cycles, humans-in-the-loop | LangGraph | AgentExecutor |
| One-off single completion | Direct provider SDK | LangChain entirely |
Two honest notes on that table. First, the LangChain team itself steers new agent work toward LangGraph — a lower-level graph runtime where you model the agent loop explicitly. AgentExecutor is still fine for simple “LLM + a few tools” cases, which is what this guide covers, but if your agent needs loops, branches, or human checkpoints, go straight to LangGraph. Second, if your entire use case is “send a prompt, get text back,” LangChain is overhead you don’t need — call the API directly.
LangChain Expression Language (LCEL)
Basic Chains
A chain is prompt, model, parser. Each piece is swappable — change the model and the rest of the pipeline doesn’t care.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# Create components
model = ChatOpenAI(model="gpt-4o", temperature=0.7)
parser = StrOutputParser()
# Define prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful coding assistant."),
("user", "{input}")
])
# Compose chain using LCEL pipe operator
chain = prompt | model | parser
# Invoke
result = chain.invoke({"input": "Explain async/await in Python"})
print(result)
Prefer ChatPromptTemplate over string templates in production — the system/user split survives model swaps better, and few-shot examples slot in as extra message pairs without string surgery.
Multi-Step Chains
Real pipelines run two or three model calls in sequence. Keep each step a separate Runnable so you can test and cache them independently:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
model = ChatOpenAI(model="gpt-4o")
# Step 1: Extract topics
extract_prompt = ChatPromptTemplate.from_template(
"Extract 3 key topics from this text as a JSON list: {text}"
)
extract_chain = extract_prompt | model | JsonOutputParser()
# Step 2: Summarize each topic
summary_prompt = ChatPromptTemplate.from_template(
"Write a 2-sentence summary about: {topic}"
)
summary_chain = summary_prompt | model | StrOutputParser()
# Step 3: Combine summaries
combine_prompt = ChatPromptTemplate.from_template(
"Combine these summaries into a coherent paragraph: {summaries}"
)
combine_chain = combine_prompt | model | StrOutputParser()
text = "Long article about Python concurrency..."
topics = extract_chain.invoke({"text": text})
summaries = [summary_chain.invoke({"topic": t}) for t in topics]
final = combine_chain.invoke({"summaries": " ".join(summaries)})
print(final)
Notice the sequential for loop — that’s three LLM round trips you pay for in latency. If the steps are independent, make them concurrent instead.
Parallel Execution
RunnableParallel fans out independent branches and gathers the results into a dict:
from langchain_core.runnables import RunnableParallel
# Define each branch explicitly
keyword_chain = ChatPromptTemplate.from_template(
"Extract keywords from: {input}"
) | model | StrOutputParser()
sentiment_chain = ChatPromptTemplate.from_template(
"Sentiment (positive/negative/neutral) of: {input}"
) | model | StrOutputParser()
parallel_chain = RunnableParallel(
summary=summary_chain,
keywords=keyword_chain,
sentiment=sentiment_chain
)
result = parallel_chain.invoke({"input": "Some text to analyze"})
# {"summary": "...", "keywords": "...", "sentiment": "..."}
Branches run concurrently in async contexts, so three parallel calls cost roughly the latency of the slowest one — not the sum. This is the cheapest latency win available in LangChain.
Memory
History with RunnableWithMessageHistory
Memory is where most LangChain examples are stuck in 2023. The old ConversationBufferMemory and friends are all deprecated now; the current pattern is RunnableWithMessageHistory, which injects chat history from any store (in-memory, Redis, Postgres) keyed by session_id:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
model = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("user", "{input}")
])
chain = prompt | model
# Store per session; swap for Redis in production
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
chat = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history",
)
config = {"configurable": {"session_id": "user-42"}}
print(chat.invoke({"input": "Hi, my name is Alice"}, config=config).content)
print(chat.invoke({"input": "What is my name?"}, config=config).content)
For production, replace the dict with RedisChatMessageHistory or a SQL-backed store — the guide on LLM application architecture covers session stores that survive restarts and multi-replica deployments.
Token-Buffer Memory
Unbounded history is a token-cost bug waiting to happen. Cap the context window by trimming old messages:
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, trim_messages
# trim_messages keeps the most recent messages within a token budget
trimmed = trim_messages(
messages,
max_tokens=2000,
strategy="last",
token_counter=len, # or a real tokenizer like tiktoken
include_system=True, # never drop the system prompt
)
The token_counter argument takes any callable — pass a model-specific tokenizer for accurate counts, since the len(msg.content) // 4 heuristic underestimates code and non-English text.
Summary Memory
When conversations run long, summarize the old part and keep the recent tail verbatim:
summarize_prompt = ChatPromptTemplate.from_template(
"Summarize this conversation in 2-3 sentences:\n{conversation}"
)
summarize_chain = summarize_prompt | ChatOpenAI(model="gpt-4o-mini")
class SummaryMemory:
def __init__(self, summarize_chain, max_recent: int = 6):
self.summarize_chain = summarize_chain
self.summary = "No conversation yet."
self.recent_messages: list = []
self.max_recent = max_recent
def add_message(self, message):
self.recent_messages.append(message)
if len(self.recent_messages) > self.max_recent:
self._summarize()
def _summarize(self):
conversation = "\n".join(
f"{'User' if isinstance(m, HumanMessage) else 'AI'}: {m.content}"
for m in self.recent_messages
)
result = self.summarize_chain.invoke({"conversation": conversation})
self.summary = result.content
self.recent_messages = []
def get_context(self) -> str:
return f"Summary: {self.summary}\nRecent: {self.recent_messages}"
Summarizing costs one extra cheap-model call every N messages — worth it only when sessions routinely exceed your token budget.
Agents
Tool-Calling Agent
An agent is an LLM in a loop: it reads the input, decides which tool to call, gets the result, and repeats until it can answer. Always bound that loop — max_iterations and max_execution_time are the difference between a quirky agent and a surprise $200 invoice:
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
@tool
def search_database(query: str) -> str:
"""Search the product database for items matching the query."""
return f"Found 3 products matching '{query}': Widget A, Widget B, Widget C"
@tool
def get_weather(location: str) -> str:
"""Get the current weather for a location."""
return f"Weather in {location}: 72°F, sunny"
@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression like '15 * 23'."""
try:
# asteval parses math safely — never eval() untrusted expressions
from asteval import Interpreter
return str(Interpreter()(expression))
except Exception as e:
return f"Error: {e}"
tools = [search_database, get_weather, calculate]
model = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant. Use tools when needed."),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad")
])
agent = create_tool_calling_agent(model, tools, prompt)
# Bound the loop before it burns your budget
executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=5, # stop after 5 tool rounds
max_execution_time=60, # hard timeout in seconds
handle_parsing_errors=True # recover from malformed model output
)
result = executor.invoke({"input": "What's the weather in Madrid and what's 15 * 23?"})
print(result["output"])
Three production rules here. Every tool needs a clear docstring — the model reads it to decide when to call the tool, and a vague one means missed or wrong calls. Never expose eval, shell execution, or raw SQL as a tool: the model’s output is untrusted input. And tool results count as prompt tokens on the next iteration, so cap what tools return — a 50-row SELECT result silently inflates every subsequent call.
Custom Tools with Pydantic
When a tool takes more than one argument, define the schema with Pydantic so the model gets exact types and descriptions:
from langchain_core.tools import tool
from pydantic import BaseModel, Field
from typing import Optional
class SearchInput(BaseModel):
query: str = Field(description="The search query")
category: Optional[str] = Field(default=None, description="Product category filter")
max_results: int = Field(default=10, description="Maximum results to return")
@tool(args_schema=SearchInput)
def search_products(query: str, category: str = None, max_results: int = 10) -> str:
"""Search for products in the catalog."""
results = f"Searching for '{query}'"
if category:
results += f" in category '{category}'"
results += f" (max {max_results} results)"
return results
The agent tool selection pattern goes deeper on designing tool surfaces that models pick correctly.
Streaming
Streaming with LCEL
Users judge LLM apps by time-to-first-token, not total latency. Any Runnable streams with .stream() / .astream():
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
model = ChatOpenAI(model="gpt-4o", streaming=True)
prompt = ChatPromptTemplate.from_template("Tell me about {topic}")
chain = prompt | model | StrOutputParser()
# Stream tokens
for chunk in chain.stream({"topic": "Python asyncio"}):
print(chunk, end="", flush=True)
# Async streaming — what production endpoints use
import asyncio
async def async_stream():
async for chunk in chain.astream({"topic": "Python asyncio"}):
print(chunk, end="", flush=True)
asyncio.run(async_stream())
One subtlety: streaming only helps if every link in the chain supports it. StrOutputParser passes chunks through, but a step that needs the full response (like a JsonOutputParser or a summarizer) will buffer silently — you’ll get one big chunk at the end. If the UX depends on streaming, keep parsers lightweight or stream partial JSON.
Streaming with Callbacks
Callbacks let you observe tokens and lifecycle events without consuming the stream yourself:
from langchain_openai import ChatOpenAI
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.prompts import ChatPromptTemplate
class StreamingHandler(BaseCallbackHandler):
def on_llm_new_token(self, token: str, **kwargs):
print(token, end="", flush=True)
def on_llm_start(self, serialized, prompts, **kwargs):
print("\n--- LLM Start ---")
def on_llm_end(self, response, **kwargs):
print("\n--- LLM End ---")
handler = StreamingHandler()
model = ChatOpenAI(model="gpt-4o", streaming=True, callbacks=[handler])
prompt = ChatPromptTemplate.from_template("Explain {topic}")
chain = prompt | model
result = chain.invoke({"topic": "docker containers"})
In production you’ll rarely print from a callback — the real use is forwarding tokens to a websocket or SSE channel, or recording metrics. That pattern is next.
RAG with LangChain
Retrieval-augmented generation is where LangChain earns its keep: loaders, splitters, embeddings, vector stores, and retrievers all implement the same Runnable interfaces, so the whole pipeline composes. For retrieval depth — chunking strategy, hybrid search, reranking — see the RAG production guide; this section covers the LangChain plumbing.
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma # partner package, not langchain_community
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
# 1. Load and split documents
loader = TextLoader("docs/handbook.txt")
documents = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
separators=["\n\n", "\n", ". ", " "]
)
chunks = splitter.split_documents(documents)
# 2. Create vector store
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_documents(chunks, embeddings, persist_directory="./chroma_db")
# 3. Create retriever
retriever = vectorstore.as_retriever(
search_type="similarity",
search_kwargs={"k": 5}
)
# 4. Build RAG chain
def format_docs(docs):
return "\n\n".join(f"[Source {i+1}]: {doc.page_content}" for i, doc in enumerate(docs))
rag_prompt = ChatPromptTemplate.from_template("""
Answer the question based on the context below. Cite source numbers.
Context:
{context}
Question: {question}
""")
model = ChatOpenAI(model="gpt-4o", temperature=0.3)
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| model
| StrOutputParser()
)
# 5. Query
answer = rag_chain.invoke("What is the vacation policy?")
print(answer)
Two things changed from older tutorials. Integrations moved to partner packages — langchain_chroma, langchain_openai, langchain_pinecone — so from langchain_community.vectorstores import Chroma now emits deprecation warnings. And {"context": retriever | format_docs, "question": RunnablePassthrough()} is a RunnableParallel under the hood: the retriever runs while the question passes through unchanged.
For production RAG, k=5 and chunk_size=500 are starting points, not defaults to ship. Tune them against your embedding model’s context window and measure with the evaluation loop below.
Error Handling and Retries
LLM calls fail in ways normal services don’t: rate limits, context overflows, malformed JSON, and occasional provider outages. LangChain gives you three layers of defense.
Fallbacks
with_fallbacks switches to a backup Runnable when the primary throws — typically a cheaper or different-provider model:
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template("Summarize: {text}")
primary = prompt | ChatOpenAI(model="gpt-4o")
backup = prompt | ChatAnthropic(model="claude-sonnet-4-5")
chain = primary.with_fallbacks([backup])
result = chain.invoke({"text": "Long text..."})
Provider-level fallback also covers the “OpenAI is down” scenario — the LLM fallback pattern covers circuit breakers and health-based routing.
Retries
with_retry retries the whole Runnable on transient errors, with exponential backoff plus jitter so concurrent workers don’t stampede the API together:
model = ChatOpenAI(model="gpt-4o", max_retries=3, timeout=30)
chain = prompt | model
chain_with_retry = chain.with_retry(
stop_after_attempt=3,
wait_exponential_jitter=True
)
result = chain_with_retry.invoke({"text": "Long text to summarize..."})
Note the distinction: max_retries on the model handles HTTP-level failures inside the client; with_retry wraps the entire chain, so it also catches parser errors and downstream exceptions. Use both — they’re different layers. And always set timeout: the SDK default waits far longer than any user will.
Observability with Callbacks
When a chain misbehaves in production you need to see which step failed and what the model actually received. The callback interface fires on every lifecycle event:
from langchain_core.callbacks import BaseCallbackHandler
import json
import time
class LoggingCallbackHandler(BaseCallbackHandler):
def __init__(self):
self.logs = []
def on_chain_start(self, serialized, inputs, **kwargs):
self.logs.append({
"event": "chain_start",
"inputs": str(inputs)[:200],
"timestamp": time.time()
})
def on_llm_error(self, error, **kwargs):
self.logs.append({
"event": "llm_error",
"error": str(error),
"timestamp": time.time()
})
def on_tool_start(self, serialized, input_str, **kwargs):
self.logs.append({
"event": "tool_start",
"tool": serialized.get("name", "unknown"),
"input": input_str[:200],
"timestamp": time.time()
})
handler = LoggingCallbackHandler()
result = chain.invoke(
{"input": "test"},
config={"callbacks": [handler]}
)
for log in handler.logs:
print(json.dumps(log))
Rolling your own works, but most teams end up on LangSmith — it traces every Runnable step with inputs, outputs, latency, and token counts, and it’s built by the same team so the instrumentation is automatic. Set LANGSMITH_TRACING=true and an API key and every chain call shows up in a searchable trace. For cost attribution across models, the LLM cost tracking template pairs well with callback metrics.
Testing and Evaluation
Testing Chains Without API Calls
Never hit a real LLM in CI. FakeListChatModel returns canned responses so you can test prompt construction, parsing, and routing deterministically:
from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
fake_model = FakeListChatModel(responses=["This is a summary."])
prompt = ChatPromptTemplate.from_template("Summarize: {text}")
chain = prompt | fake_model | StrOutputParser()
result = chain.invoke({"text": "Long article..."})
assert result == "This is a summary."
Test the seams, not the model: verify your prompt template fills correctly, your parser handles the model’s output shape, and your fallback triggers on errors. For integration tests use the cheapest model (gpt-4o-mini) and assert on response structure — never on exact wording.
Evaluating Output Quality
Regression-testing a chain means checking that prompt or model changes don’t degrade answers. The practical loop: keep a golden dataset of inputs with expected criteria, run the chain against it after every change, and grade with a strong model as judge (or LangSmith’s evaluators). The LLM evaluation guide covers grading rubrics and dataset design; for RAG specifically, the RAG evaluation checklist has the metrics worth tracking (faithfulness, context recall).
Deployment
FastAPI Integration
LCEL’s async methods drop into FastAPI almost directly. This endpoint streams tokens over SSE — the pattern behind most “typing effect” UIs:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from pydantic import BaseModel
app = FastAPI()
model = ChatOpenAI(model="gpt-4o", streaming=True)
prompt = ChatPromptTemplate.from_template("Answer: {question}")
chain = prompt | model | StrOutputParser()
class ChatRequest(BaseModel):
question: str
@app.post("/chat")
async def chat(request: ChatRequest):
async def stream():
async for chunk in chain.astream({"question": request.question}):
yield f"data: {chunk}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(stream(), media_type="text/event-stream")
@app.post("/chat/sync")
async def chat_sync(request: ChatRequest):
result = await chain.ainvoke({"question": request.question})
return {"answer": result}
Always use the async variants (ainvoke, astream) in async endpoints — the sync invoke blocks the event loop and serializes all your requests. And set a timeout on the upstream call; a slow provider otherwise holds your worker hostage.
Batch Processing
For offline jobs — nightly summarization, bulk classification — abatch runs inputs concurrently with a cap so you don’t trip rate limits:
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
model = ChatOpenAI(model="gpt-4o-mini")
prompt = ChatPromptTemplate.from_template("Summarize in 1 sentence: {text}")
chain = prompt | model
async def batch_process(texts: list[str], batch_size: int = 10) -> list[str]:
inputs = [{"text": t} for t in texts]
results = await chain.abatch(inputs, config={"max_concurrency": batch_size})
return [r.content for r in results]
texts = [f"Article {i} content..." for i in range(50)]
summaries = asyncio.run(batch_process(texts, batch_size=5))
Keep max_concurrency below your provider’s requests-per-minute tier divided by tokens-per-request — bursting against the rate limit just converts into retried, slower requests. For hard limits, ChatOpenAI accepts an InMemoryRateLimiter via rate_limiter= that throttles at the client.
Best Practices
- Pin every langchain package —
langchain,langchain-core,langchain-openai, partner packages all version independently and move fast. - Bound every agent:
max_iterations,max_execution_time,handle_parsing_errors— no exceptions. - Never expose dangerous primitives as tools — no
eval, shell, or raw SQL; model output is untrusted input. - Set timeouts and retries at both layers — model
max_retries/timeoutfor HTTP,with_retry/with_fallbacksfor chain-level failures. - Stream whenever users wait — time-to-first-token matters more than total latency; avoid buffering parsers in streamed paths.
- Cap tool output and memory size — every token you return or store is re-sent on the next call.
- Test with fake models in CI —
FakeListChatModelfor unit tests, cheap models for integration, golden datasets for quality.
See Also
- Companion project — runnable chain, RAG, agent, FastAPI app and tests from this guide
- Official docs: LangChain Python, LCEL, Agents, LangGraph, LangSmith
- Complete Guide to LLM Application Architecture
- Complete Guide to AI Agents in Production
- Complete Guide to RAG in Production
- Complete Guide to LLM Evaluation
- Complete Guide to LLM Security
Frequently Asked Questions
Should I use LCEL or LLMChain?
LCEL. LLMChain is deprecated; LCEL gives you the pipe operator, native streaming, batching, async, retries, and fallbacks on every Runnable. Any new code should compose with |.
How do I handle LangChain version updates?
Pin versions in requirements.txt and upgrade deliberately — read the changelog, since classes move between langchain, langchain_core, langchain_community, and partner packages regularly. Prefer imports from langchain_core and partner packages (langchain_openai, langchain_chroma) over langchain_community, which deprecates the fastest.
How do I test LangChain chains?
Mock the LLM with FakeListChatModel or FakeMessagesListChatModel from langchain_core.language_models.fake_chat_models. Test the seams — prompt construction, parsing, fallback behavior — separately from the model. For integration tests, use gpt-4o-mini and assert on structure, not exact content.
What's the difference between agents and chains?
Chains run a fixed sequence you define; agents let the model pick tools dynamically inside a loop. Reach for chains when the workflow is predictable — they're faster, cheaper, and testable. Agents trade that predictability for flexibility, so bound them with max_iterations and max_execution_time.
Should I use LangChain, LangGraph, or call the API directly?
LangChain for composed pipelines — chains, RAG, simple tool agents. LangGraph when the workflow needs explicit state, cycles, or human checkpoints; the LangChain team recommends it for serious agent work. Direct SDK calls when your use case is a single prompt-in-text-out call — the framework is overhead there.
How do I reduce latency in LangChain?
Stream for perceived speed, RunnableParallel for independent branches, cheaper models for simple steps, abatch for bulk jobs, and set_llm_cache for repeated queries. The biggest win is usually architectural: fewer sequential LLM calls.
Can I use LangChain with providers other than OpenAI?
Yes — that's a core reason to use it. Partner packages exist for Anthropic (langchain_anthropic), Google (langchain_google_genai), Mistral, Groq, Ollama for local models, and more. Swap the model class and the rest of the chain stays identical; the local LLM deployment guide covers self-hosted setups.
Related Resources
Complete Guide to LLM Application Architecture
Build production LLM applications end to end: API layers, prompt management, streaming, caching, guardrails, observability, evaluation and deployment patterns.
GuideComplete Guide to RAG in Production
Take RAG to production: chunking strategies, vector store selection, hybrid retrieval, reranking, RAGAS evaluation, and deployment patterns.
GuideComplete Guide to AI Agents in Production
Design, deploy, and operate LLM agents that survive real traffic: architectures, tools, memory, human-in-the-loop, safety, and observability.
GuideComplete Guide to LLM Evaluation
Evaluate LLM apps in production: RAGAS, LLM-as-judge, hallucination detection, human eval, A/B testing and CI/CD regression pipelines.
PatternLLM Fallback Pattern
Fall back to alternative LLM providers or models when the primary fails. Handle rate limits, timeouts, and errors gracefully with a provider chain.
DocAI LLM Incident Response Runbook
Operational runbook for LLM production incidents: hallucination events, model outages, cost spikes, safety failures, and degraded quality. Includes severity levels, escalation paths, diagnostic steps, and recovery procedures.