Writing

LangChain Fundamentals: Models, Prompts, Output Parsers, and LCEL Chains

While consumer web interfaces like ChatGPT and Claude are versatile, managing repetitive engineering workflows—such as automated code reviews, structured document extraction, and API integrations—through copy-paste chat windows introduces friction.

LangChain bridges this gap by providing an abstraction layer over diverse model providers, prompt templates, structured outputs, and composable execution pipelines.

[!NOTE] LangChain Architecture Update (0.2 / 0.3+) Modern LangChain code organizes functionality into modular packages (langchain-core, langchain-community, and provider-specific libraries like langchain-openai, langchain-anthropic). The pipe operator syntax (|) known as LCEL (LangChain Expression Language) replaces legacy class-based chains (LLMChain).

1. Unified Model Interfaces

Switching between foundation model providers requires zero architectural changes when using unified chat wrappers:

pip install langchain-core langchain-openai langchain-anthropic langchain-google-genai
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import SystemMessage, HumanMessage

# Models expose the exact same .invoke() and .stream() methods
llm_openai = ChatOpenAI(model="gpt-4o-mini", temperature=0)
llm_claude = ChatAnthropic(model="claude-3-5-sonnet-20241022", temperature=0)
llm_gemini = ChatGoogleGenerativeAI(model="gemini-1.5-pro", temperature=0)

messages = [
    SystemMessage(content="You are a senior software architect."),
    HumanMessage(content="Explain dependency injection with a brief example.")
]

response = llm_openai.invoke(messages)
print(response.content)

2. Reusable Prompt Templates (ChatPromptTemplate)

Rather than concatenating raw Python f-strings, ChatPromptTemplate structures multi-turn conversations and enforces variable type expectations:

from langchain_core.prompts import ChatPromptTemplate

review_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are an expert code reviewer specializing in {language} and architectural patterns."),
    ("human", """Review the following code snippet for potential concurrency issues and edge cases:

{code}


Provide prioritized bullet points with code improvements.""")
])

formatted_messages = review_prompt.format_messages(
    language="Python",
    code="def update_balance(acc_id, amount): balance[acc_id] += amount"
)

3. Strict Structured Output with Pydantic

Unstructured markdown or conversational prose is difficult to parse programmatically. LangChain pairs language models with Pydantic schemas using native tool calling (or JsonOutputParser):

from pydantic import BaseModel, Field
from langchain_core.output_parsers import JsonOutputParser

class CodeReviewSummary(BaseModel):
    has_bugs: bool = Field(description="Whether critical security or concurrency bugs exist")
    vulnerabilities: list[str] = Field(description="List of identified issues")
    suggested_diff: str = Field(description="Unified git diff or refactored replacement snippet")

parser = JsonOutputParser(pydantic_object=CodeReviewSummary)

prompt = ChatPromptTemplate.from_messages([
    ("system", "Review the code and format your response strictly as JSON matching schema:\n{format_instructions}"),
    ("human", "{code}")
]).partial(format_instructions=parser.get_format_instructions())

4. Composing Pipelines with LCEL (|)

LangChain Expression Language (LCEL) uses the Unix pipe operator | to chain runnables together. Outputs from the preceding stage feed directly into inputs of the next stage:

# Prompt | Model | Parser Pipeline
chain = prompt | llm_openai | parser

result: dict = chain.invoke({
    "code": "def divide(a, b): return a / b"
})

print(result["has_bugs"])        # True
print(result["vulnerabilities"]) # ['ZeroDivisionError if b == 0']

LCEL chains automatically support:

  • Synchronous and Asynchronous execution (.invoke(), .ainvoke())
  • Real-time token streaming (.stream(), .astream())
  • Batch processing with concurrency pools (.batch())

Next in the series: Building AI Assistants with LangChain Tools, Agents, and LangGraph.