Chain

we are using “Chain” to connect components together so output from one step can flow into the next step.

Chain is a sequence of steps where the output of one step feeds into the next. It lets you build pipelines — for example: format a prompt → call the LLM → parse the output. Chains are the core building block of LangChain apps.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

# Step 1: define Prompt Template 
prompt = ChatPromptTemplate.from_template(
    "Explain {topic} in simple terms."
)

# Step 2: Wrap LLM Wrapper
llm = ChatOpenAI(model="gpt-4o")

# Step 3: Output Parser
parser = StrOutputParser()

# Chain them together with | pipe operator 
chain = prompt | llm | parser

# Run it! 
result = chain.invoke({"topic": "LangChain"})

note: different LLM, OpenAI, Calude, Gemini, DeepSeek, have different package. DeepSeek’s API is OpenAI-compatible, just use OpenAI’s package.

</> bash
# Each needs its own package
pip install langchain-openai
pip install langchain-anthropic
pip install langchain-google-genai
pip install langchain-ollama          # local models

python
%pip install langchain-openai
%pip install langchain-anthropic
%pip install langchain-google-genai
%pip install langchain-ollama          # local models
# OpenAI (GPT)
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
    model="gpt-4o",
    api_key="sk-...",
    temperature=0.7
)

# DeepSeek reuse ChatOpenAI
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
    model="deepseek-chat",           # or "deepseek-reasoner" for R1
    api_key="sk-...",                # DeepSeek API key
    base_url="https://api.deepseek.com/v1",  # ← 关键!point to DeepSeek
    temperature=0.7
)

# Anthropic (Claude) 
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
    model="claude-sonnet-4-6",
    api_key="sk-ant-...",
    temperature=0.7
)

# Google (Gemini)
from langchain_google_genai import ChatGoogleGenerativeAI
llm = ChatGoogleGenerativeAI(
    model="gemini-2.0-flash",
    api_key="AIza...",
    temperature=0.7
)

# Ollama ( run locally — FREE!)
from langchain_ollama import ChatOllama
llm = ChatOllama(
    model="llama3.2",   # no API key needed!
    temperature=0.7
)

After install individual or related packages,

# llm = ChatAnthropic(model="claude-sonnet-4-6")
# llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
# llm = ChatOllama(model="llama3.2")
# llm = ChatOpenAI(model="deepseek-chat", base_url="https://api.deepseek.com/v1", api_key="sk-...")

chain = prompt | llm | parser          # ← this never changes!
result = chain.invoke({"topic": "LangChain"})