🌐 EN | πŸ‡―πŸ‡΅ JP

Chapter 1: What is LangChain?

Understanding the LLM Application Framework

πŸ“– Reading Time: 15-20 minutes πŸ“Š Difficulty: Beginner πŸ’» Code Examples: 4 πŸ“ Exercises: 2

Learning Objectives

1.1 The Challenge of Building LLM Applications

Large Language Models (LLMs) like GPT-4, Claude, and Gemini have revolutionized what's possible with AI. However, building production-ready applications with these models presents several challenges:

graph TB subgraph Challenges["Common Challenges"] C1[Multiple LLM Providers
Different APIs] C2[Prompt Management
Templates & Versioning] C3[Memory & State
Conversation History] C4[Tool Integration
External APIs & Data] C5[Error Handling
Retries & Fallbacks] end C1 --> Problem[Complex, Fragmented Code] C2 --> Problem C3 --> Problem C4 --> Problem C5 --> Problem style Problem fill:#e74c3c,color:#fff

Without a Framework

Building an LLM application without a framework requires you to:

The Pain of Raw API Calls

# Without LangChain: Handling just OpenAI and Anthropic
import openai
import anthropic

def call_llm(prompt, provider="openai"):
    if provider == "openai":
        client = openai.OpenAI()
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content
    elif provider == "anthropic":
        client = anthropic.Anthropic()
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=1024,
            messages=[{"role": "user", "content": prompt}]
        )
        return response.content[0].text
    # ... more providers, more code, more maintenance

This approach quickly becomes unmanageable as you add more providers, features, and complexity.

1.2 Enter LangChain

LangChain is an open-source framework that simplifies building applications powered by Large Language Models. It provides:

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides a unified interface for working with any LLM, composable components for building complex workflows, and production-ready features like streaming, caching, and observability.

Core Value Propositions

Feature Benefit
Unified Interface Switch between LLM providers with a single line of code
Composability Build complex workflows by chaining simple components
Built-in Memory Conversation history management out of the box
Tool Integration Easily connect LLMs to external tools and APIs
Production Features Streaming, caching, retries, and observability included

The LangChain Difference

Code Example 1: The Power of Unified Interfaces
# With LangChain: Simple, unified interface
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI

# Switch providers with one line - same interface!
llm = ChatOpenAI(model="gpt-4")
# llm = ChatAnthropic(model="claude-sonnet-4-20250514")
# llm = ChatGoogleGenerativeAI(model="gemini-pro")

# Same code works for all providers
response = llm.invoke("Explain quantum computing in simple terms")
print(response.content)

1.3 The LangChain Ecosystem

LangChain is more than just a libraryβ€”it's an ecosystem of tools designed for different aspects of LLM application development:

graph TB subgraph Ecosystem["LangChain Ecosystem"] LC[πŸ”— LangChain
Core Framework] LG[🌐 LangGraph
Agent Orchestration] LS[πŸ” LangSmith
Observability] end LC -->|Build| Apps[Applications] LG -->|Complex Workflows| Apps LS -->|Monitor & Debug| Apps style LC fill:#667eea,color:#fff style LG fill:#11998e,color:#fff style LS fill:#f093fb,color:#fff style Apps fill:#28a745,color:#fff

LangChain (Core)

The main framework providing:

LangGraph

A separate library for building stateful, multi-actor applications:

LangSmith

A platform for LLM application observability:

1.4 LangChain v1.0: What's New

LangChain reached its first stable release (v1.0) in October 2025. This milestone brought significant changes:

Major Changes in v1.0

  • New create_agent API: Simplified agent creation replacing create_react_agent
  • content_blocks property: Unified access to multimodal content across providers
  • Simplified namespace: Core functionality in langchain, legacy in langchain-classic
  • TypedDict state: Agents now use TypedDict instead of Pydantic models
Code Example 2: The New create_agent API (v1.0)
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

# Define tools (we'll cover this in Chapter 3)
def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Results for: {query}"

# Create an agent with the new v1.0 API
agent = create_agent(
    model=ChatOpenAI(model="gpt-4"),
    tools=[search_web],
    system_prompt="You are a helpful research assistant."
)

# Invoke the agent
result = agent.invoke({
    "messages": [
        {"role": "user", "content": "What's the weather like today?"}
    ]
})
print(result)

1.5 Installing LangChain

LangChain uses a modular installation approach. Install only what you need:

Basic Installation
# Core LangChain package
pip install langchain

# Provider-specific packages (install as needed)
pip install langchain-openai      # For OpenAI models
pip install langchain-anthropic   # For Anthropic Claude
pip install langchain-google-genai # For Google Gemini

# Community integrations
pip install langchain-community

# Verify installation
python -c "import langchain; print(f'LangChain {langchain.__version__} installed!')"

Current Versions (January 2026)

  • langchain-core: 1.2.6
  • langchain: 1.2.0
  • Python requirement: >= 3.9

Setting Up API Keys

Most LLM providers require API keys. Set them as environment variables:

Environment Setup
# Linux/macOS
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"

# Windows (PowerShell)
$env:OPENAI_API_KEY="your-openai-key"
$env:ANTHROPIC_API_KEY="your-anthropic-key"

Or use a .env file with python-dotenv:

Code Example 3: Loading API Keys from .env
# .env file:
# OPENAI_API_KEY=your-openai-key

from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env

from langchain_openai import ChatOpenAI
llm = ChatOpenAI()  # Automatically uses OPENAI_API_KEY

1.6 Your First LangChain Application

Let's build a simple chatbot to verify everything works:

Code Example 4: Hello LangChain
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

# Initialize the model
llm = ChatOpenAI(
    model="gpt-4",
    temperature=0.7  # Controls randomness (0=deterministic, 1=creative)
)

# Create messages
messages = [
    SystemMessage(content="You are a helpful assistant who explains things simply."),
    HumanMessage(content="What is machine learning?")
]

# Get response
response = llm.invoke(messages)
print(response.content)

Expected Output:

Machine learning is a type of artificial intelligence where computers learn
from data instead of being explicitly programmed. Think of it like teaching
a child: instead of giving them rules, you show them examples, and they
figure out the patterns themselves.

For example, to teach a computer to recognize cats in photos, you'd show it
thousands of cat pictures. The computer finds patterns (pointy ears,
whiskers, etc.) and uses them to identify cats in new photos it's never
seen before.

Exercises

Exercise 1: Installation Verification

Install LangChain and at least one provider package. Run this code to verify:

import langchain
from langchain_core.messages import HumanMessage

print(f"LangChain version: {langchain.__version__}")
print("Installation successful!")

Exercise 2: Multi-Provider Comparison

If you have API keys for multiple providers, try asking the same question to different models and compare their responses. What differences do you notice in style, length, or content?

Summary

Disclaimer

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