🌐 EN | 🇯🇵 JP

Chapter 5: Production Deployment

LangSmith, LangGraph, and Best Practices

📖 Reading Time: 15-20 minutes 📊 Difficulty: Intermediate 💻 Code Examples: 4 📝 Exercises: 1

Learning Objectives

5.1 LangSmith: Observability for LLM Applications

LangSmith is LangChain's platform for tracing, debugging, and monitoring LLM applications in production.

graph TB subgraph App["Your Application"] A[LangChain Code] end subgraph LS["LangSmith Platform"] B[Tracing] C[Debugging] D[Evaluation] E[Monitoring] end A -->|Auto-logged| B B --> C B --> D B --> E style A fill:#667eea,color:#fff style LS fill:#f8f9fa

Setting Up LangSmith

Code Example 1: LangSmith Configuration
import os

# Set environment variables (or use .env file)
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-langsmith-api-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"  # Optional: organize traces

# Now all LangChain operations are automatically traced!
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

llm = ChatOpenAI(model="gpt-4")
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant."),
    ("human", "{question}")
])

chain = prompt | llm

# This invocation is automatically logged to LangSmith
response = chain.invoke({"question": "What is the capital of France?"})
print(response.content)

# View traces at: https://smith.langchain.com

What LangSmith Shows You

LangSmith Pricing (2025)

  • Free tier: 5,000 traces/month, 1 seat
  • Paid plans: Higher limits, team features
  • Self-hosted: Enterprise plan for on-premise deployment

5.2 When to Use LangGraph

LangGraph is LangChain's framework for building complex, stateful agent workflows. Use it when you outgrow simple LCEL chains.

LCEL vs LangGraph Decision Matrix

Use Case LCEL LangGraph
Simple prompt → model → parser
RAG with retrieval
Basic agent with tools
Complex branching logic
Multi-agent collaboration
Human-in-the-loop approval
Persistent conversation state
Workflows with cycles/loops
Code Example 2: LangGraph Agent Preview
# LangGraph enables complex workflows with state
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated
import operator

# Define state schema
class AgentState(TypedDict):
    messages: Annotated[list, operator.add]
    next_step: str

# Create graph
workflow = StateGraph(AgentState)

# Add nodes (each node is a function)
workflow.add_node("research", research_node)
workflow.add_node("write", write_node)
workflow.add_node("review", review_node)

# Add edges (define flow)
workflow.add_edge("research", "write")
workflow.add_conditional_edges(
    "write",
    should_continue,  # Function that returns next node
    {"review": "review", "end": END}
)

# Compile and run
app = workflow.compile()
result = app.invoke({"messages": ["Write a blog post about AI"]})

5.3 MCP (Model Context Protocol) Integration

MCP is an open protocol for standardizing how applications provide tools to LLMs. LangChain supports MCP through adapters:

Code Example 3: Using MCP Tools
from langchain_mcp_adapters import MultiServerMCPClient
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

# Connect to MCP servers
async with MultiServerMCPClient(
    {
        "filesystem": {
            "command": "npx",
            "args": ["-y", "@anthropic/mcp-filesystem", "/path/to/allowed/dir"]
        },
        "web": {
            "url": "http://localhost:8080/mcp"  # HTTP-based MCP server
        }
    }
) as client:
    # Get tools from all connected servers
    tools = client.get_tools()

    # Create agent with MCP tools
    agent = create_agent(
        model=ChatOpenAI(model="gpt-4"),
        tools=tools,
        system_prompt="You can read files and browse the web."
    )

    result = await agent.ainvoke({
        "messages": [{"role": "user", "content": "Read the README.md file"}]
    })

MCP (Model Context Protocol)

An open protocol (donated to Linux Foundation in 2025) that standardizes how applications expose tools to LLMs. Major adopters include OpenAI, Anthropic, and Google. By 2026, most major APIs are expected to ship MCP servers alongside REST APIs.

5.4 Production Best Practices

Performance Optimization

Code Example 4: Caching and Streaming
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.globals import set_llm_cache
from langchain_community.cache import SQLiteCache

# Enable caching to avoid redundant API calls
set_llm_cache(SQLiteCache(database_path=".langchain.db"))

# Use streaming for better UX
llm = ChatOpenAI(model="gpt-4", streaming=True)

# Async for better throughput
async def process_many(questions):
    tasks = [llm.ainvoke(q) for q in questions]
    return await asyncio.gather(*tasks)

Error Handling

from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableWithFallbacks

# Create fallback chain
primary = ChatOpenAI(model="gpt-4")
fallback = ChatOpenAI(model="gpt-3.5-turbo")

robust_llm = primary.with_fallbacks([fallback])

# Will try gpt-4, then gpt-3.5-turbo if it fails
response = robust_llm.invoke("Hello")

Security Checklist

5.5 Next Steps

Congratulations on completing this introduction! Here's where to go next:

Deepen Your Knowledge

Resources

Exercise

Exercise: Production-Ready RAG

Take your RAG system from Chapter 4 and make it production-ready:

  1. Enable LangSmith tracing
  2. Add caching for embeddings and LLM calls
  3. Implement a fallback model
  4. Add input validation
  5. Deploy as an API endpoint (FastAPI recommended)

Summary

Disclaimer

This content is provided for educational purposes. LangChain is developed and maintained by LangChain Inc.