LangChain building blocks

Topic 1 of 4 in LangChain & agent fundamentals26 min readBeginnerFree course

Overview

In the previous lesson, you learned how function and tool calling allows language models to request operations beyond ordinary text generation. Before building an agent that executes those operations, you need a reliable way to communicate with models, construct their instructions, and process their responses.

LangChain is an open-source framework that provides these application-level building blocks through consistent Python interfaces.

Without LangChain, developers frequently write provider-specific API requests, manually construct conversation histories, parse JSON responses, and implement repetitive integration logic. LangChain reduces this work while allowing applications to retain control over their behavior.

The five building blocks covered in this lesson are:

  • Models: Generate responses, classifications, decisions, and structured data.
  • Messages: Represent instructions, conversation turns, and tool interactions.
  • Prompt templates: Construct reusable instructions from dynamic inputs.
  • Output parsers: Convert model responses into application-friendly formats.
  • LCEL: Compose individual components into executable pipelines.

These components are not exclusive to agents. They can power document summarizers, information extraction services, customer support applications, and individual LangGraph nodes.

The following diagram illustrates a typical model-processing pipeline.

Overview diagram: Application Input to Prompt Template; Prompt Template to Chat Messages; Chat Messages to Chat Model; Chat Model to AI Message; AI Message to Output Parser; Output Parser to Application Output.

Environment setup

Use Python 3.10 or later and install the LangChain 1.x packages required for this lesson.

Terminal
python -m pip install -U "langchain[openai]>=1,<2" "langchain-core>=1,<2" "langgraph>=1,<2" "pydantic>=2,<3"

Configure your OpenAI API key through an environment variable.

For Linux and macOS:

Terminal
export OPENAI_API_KEY="your-api-key"

For Windows PowerShell:

POWERSHELL
$env:OPENAI_API_KEY="your-api-key"

Never commit API keys to source control. Production applications should retrieve credentials from an appropriate secrets management system.

The examples use LangChain 1.x public interfaces and the gpt-5.4-mini model. They require an API-enabled OpenAI account for live model calls. Generated outputs are illustrative rather than captured execution results.

Understanding chat models

A chat model is a language model interface designed to process conversational input.

Unlike a simple text completion interface, a chat model can distinguish between application instructions, user requests, earlier assistant responses, and tool results.

LangChain provides init_chat_model() as a unified initialization interface. The provider prefix in openai:gpt-5.4-mini identifies the integration responsible for communicating with the underlying model API.

The following example performs a basic model invocation.

Python
from langchain.chat_models import init_chat_model

model = init_chat_model("openai:gpt-5.4-mini")

response = model.invoke(
    "Explain what an API is in one sentence."
)

print(type(response).__name__)
print(response.text)

Possible output:

Text
AIMessage
An API is an interface that allows software applications
to communicate and exchange information.

Notice that invoke() returns an AIMessage, not an ordinary Python string.

The object can contain generated text, token usage, response metadata, and tool-call requests. The text property provides the textual portion of the response.

Internally, the integration translates LangChain input into the provider’s request format, sends the API request, and converts the returned response into LangChain message objects.

The abstraction standardizes the programming interface, but it does not guarantee identical capabilities or behavior across providers.

See the official LangChain models documentation for supported model operations.

Messages

Messages are the fundamental communication units of a chat-based application.

A message contains both content and information about its purpose. This distinction matters because an application instruction should not be treated exactly like an ordinary customer question.

Message types

LangChain provides several standard message classes through langchain.messages.

Message class Purpose
SystemMessage Defines application instructions, behavior, or constraints.
HumanMessage Represents input from a user.
AIMessage Represents a model response or tool-call request.
ToolMessage Represents the result of an executed tool.
RemoveMessage Signals message removal when processed by a compatible state reducer.

A typical message may contain content, an identifier, and metadata. An AIMessage additionally supports fields such as tool_calls and usage_metadata.

Content is not necessarily plain text. Supported integrations can represent images, reasoning summaries, and other information through content blocks.

Working with conversation history

The following example demonstrates how to maintain a short conversation using explicit message objects.

Python
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage

model = init_chat_model("openai:gpt-5.4-mini")

messages = [
    SystemMessage(
        content="You are a Python instructor. Explain concepts simply."
    ),
    HumanMessage(
        content="What is a Python dictionary?"
    ),
]

first_response = model.invoke(messages)
messages.append(first_response)

messages.append(
    HumanMessage(
        content="Show me an example of accessing one of its values."
    )
)

second_response = model.invoke(messages)
messages.append(second_response)

print(second_response.text)

Possible output:

Python
student = {"name": "Anita", "age": 22}
print(student["name"])  # Anita

The model understands that “its values” refers to the dictionary discussed in the previous turn because the earlier messages were included in the second request.

A standalone chat model invocation does not automatically maintain application-level conversation history. Your application must supply the necessary context or use a higher-level component that manages it.

Later, LangGraph will help manage these messages as part of graph state.

Tool calls and tool messages

The previous lesson introduced the distinction between requesting a function call and executing that function.

LangChain represents a model’s tool requests through AIMessage.tool_calls. After execution, the corresponding result is represented by a ToolMessage.

This example manually constructs a simplified calculator interaction without making an API request.

Python
from langchain.messages import (
    HumanMessage,
    AIMessage,
    ToolMessage,
)

messages = [
    HumanMessage(content="What is 12 multiplied by 8?"),
    AIMessage(
        content="",
        tool_calls=[
            {
                "name": "multiply",
                "args": {"a": 12, "b": 8},
                "id": "call_001",
                "type": "tool_call",
            }
        ],
    ),
    ToolMessage(
        content="96",
        tool_call_id="call_001",
        name="multiply",
    ),
]

print(messages[1].tool_calls[0]["args"])
print(messages[2].content)

Expected output:

Text
{'a': 12, 'b': 8}
96

The tool_call_id connects the result to the original request. When multiple tools are requested, these identifiers allow the integration to associate each result with the correct call.

The example constructs messages only; it does not execute a calculator. Actual tool definition and execution are covered in the next lesson.

RemoveMessage serves a different purpose. In LangGraph, a compatible message reducer such as add_messages can interpret it as an instruction to remove a stored message by ID. It is not a conversational message that should be sent directly to a model.

Inspecting model responses

For debugging, inspect the original response rather than immediately discarding everything except its text.

Useful attributes include:

  • response.text for textual output.
  • response.content_blocks for standardized content blocks.
  • response.tool_calls for requested tool operations.
  • response.usage_metadata for token usage when available.
  • response.response_metadata for integration-specific information.

Note: A valid model response can contain tool calls without ordinary answer text. Converting every response to a string too early can silently discard information required by an agent.

Additional message behavior is documented in the LangChain messages guide.

Prompt templates

A prompt is the information supplied to a model to guide its response. Real applications often need to construct prompts using customer questions, retrieved documents, conversation histories, and other runtime data.

Writing every prompt manually produces repetitive code and makes behavior harder to maintain.

Prompt templates separate stable instructions from changing inputs.

ChatPromptTemplate

ChatPromptTemplate is designed for chat models. It defines message roles and placeholders that are populated when the template is invoked.

The following example creates a reusable technical explanation prompt.

Python
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate

model = init_chat_model("openai:gpt-5.4-mini")

prompt = ChatPromptTemplate.from_messages([
    (
        "system",
        "You are a {subject} instructor. "
        "Explain concepts for {level} learners."
    ),
    ("human", "Explain {topic} in three sentences."),
])

inputs = {
    "subject": "Python",
    "level": "beginner",
    "topic": "list comprehensions",
}

prompt_value = prompt.invoke(inputs)

for message in prompt_value.to_messages():
    print(message.type, message.content)

response = model.invoke(prompt_value)
print(response.text)

The rendered messages are:

Text
system You are a Python instructor. Explain concepts for beginner learners.
human Explain list comprehensions in three sentences.

The model subsequently generates an explanation.

The template invocation performs formatting locally. It does not contact the language model or consume model tokens until the formatted prompt is submitted.

The returned prompt value can be passed directly to a compatible model or inspected using to_messages().

PromptTemplate versus ChatPromptTemplate

LangChain also provides PromptTemplate for string-oriented prompt construction.

Feature PromptTemplate ChatPromptTemplate
Representation Formatted text Role-based messages
Conversation roles Not explicitly represented Explicitly represented
Message history Must be manually represented Supports message placeholders
Typical use Simple text transformation Conversational AI and agents
Import module langchain_core.prompts langchain_core.prompts

For most applications in this course, prefer ChatPromptTemplate because it preserves the distinction between instructions and conversation content.

Dynamic conversation history

A conversation can contain a variable number of messages. MessagesPlaceholder inserts that message sequence into a chat prompt.

The following example combines fixed application instructions with dynamic conversation history.

Python
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, AIMessage
from langchain_core.prompts import (
    ChatPromptTemplate,
    MessagesPlaceholder,
)

model = init_chat_model("openai:gpt-5.4-mini")

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful programming tutor."),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{question}"),
])

history = [
    HumanMessage(content="I am learning SQL."),
    AIMessage(content="Great! SQL is used to query databases."),
]

prompt_value = prompt.invoke({
    "history": history,
    "question": "How do I retrieve every row from a table?",
})

response = model.invoke(prompt_value)

print(response.text)

Possible output:

Text
Use SELECT * FROM table_name; to retrieve every row and column.

The placeholder inserts existing messages without flattening them into one large string.

This is particularly useful when a LangGraph node receives conversation history from graph state.

Designing reliable prompts

Effective application prompts describe the task, provide relevant context, specify constraints, and communicate the expected response.

Keep application-controlled instructions separate from untrusted user content. Do not allow users to supply arbitrary template source.

Literal braces in the default template format must be escaped as {{ and }} when they are part of the template itself rather than variable placeholders.

Prompt templates improve maintainability, but they are not security boundaries. A model can still be influenced by malicious instructions embedded in user input or retrieved documents. Authorization and business constraints must be enforced in application code.

The ChatPromptTemplate API reference also documents partial variables, optional placeholders, and formatting methods.

Output parsers

Language models generate responses that may be suitable for humans but inconvenient for software.

For example, a customer support classifier might return:

Text
This appears to be a billing issue and should receive high priority.

An application that routes tickets needs predictable fields instead:

JSON
{
  "category": "billing",
  "priority": "high"
}

Output parsers transform model responses into representations that downstream components can consume.

StrOutputParser

StrOutputParser extracts textual output from a model response.

This example converts an AIMessage into a Python string.

Python
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser

model = init_chat_model("openai:gpt-5.4-mini")
parser = StrOutputParser()

response = model.invoke(
    "Suggest a short title for a Python tutorial."
)

result = parser.invoke(response)

print(type(result).__name__)
print(result)

Possible output:

Text
str
Python Made Simple

This parser is useful when a pipeline’s final result is intended for display, document generation, or further text processing.

It does not validate factual correctness or enforce a data schema.

JSON and Pydantic output parsers

JsonOutputParser converts suitable generated JSON into Python data structures. PydanticOutputParser goes further by parsing and validating the response against a Pydantic model.

The following example demonstrates local parsing and validation without making a model request.

Python
from typing import Literal
from pydantic import BaseModel, Field
from langchain.messages import AIMessage
from langchain_core.output_parsers import PydanticOutputParser

class Review(BaseModel):
    sentiment: Literal["positive", "negative", "neutral"]
    score: int = Field(ge=1, le=5)

parser = PydanticOutputParser(pydantic_object=Review)

response = AIMessage(
    content='{"sentiment": "positive", "score": 5}'
)

review = parser.invoke(response)

print(review.sentiment)
print(review.score)
print(review.model_dump())

Expected output:

Text
positive
5
{'sentiment': 'positive', 'score': 5}

If the generated score were 9, validation would fail because the schema restricts the value to the range from one to five.

For text-generation pipelines, parser.get_format_instructions() provides instructions that can be included in the prompt to encourage the required output format.

However, the model may still produce malformed JSON or violate the schema. Parsing errors must be handled rather than silently ignored.

Model-native structured output

Modern chat models can often generate structured responses using provider-supported schema mechanisms.

LangChain exposes this capability through with_structured_output().

The following example extracts structured product feedback using a Pydantic schema and OpenAI’s native JSON Schema output mechanism.

Python
from typing import Literal
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class ProductFeedback(BaseModel):
    sentiment: Literal["positive", "negative", "mixed"]
    product: str
    issues: list[str]
    summary: str = Field(
        description="A concise summary of the customer feedback"
    )

model = init_chat_model("openai:gpt-5.4-mini")

structured_model = model.with_structured_output(
    ProductFeedback,
    method="json_schema",
)

result = structured_model.invoke(
    "The wireless headphones sound great, "
    "but the battery drains too quickly."
)

print(type(result).__name__)
print(result.model_dump_json(indent=2))

Possible output:

JSON
{
  "sentiment": "mixed",
  "product": "wireless headphones",
  "issues": [
    "Battery drains too quickly"
  ],
  "summary": "Good sound quality but disappointing battery life."
}

The result is a ProductFeedback instance rather than an AIMessage.

The structured-output wrapper translates the schema into a provider-supported representation and converts a successful response into the requested application type.

Supported methods and schema constraints vary by provider.

Approach Result Best use
StrOutputParser String Human-readable answers
JsonOutputParser Python JSON-compatible data Flexible JSON processing
PydanticOutputParser Validated Pydantic object Schema validation of generated text
with_structured_output() Schema-dependent result Model-supported structured generation

For supported models, prefer native structured output when downstream logic depends on specific fields.

Setting include_raw=True on with_structured_output() returns a dictionary containing raw, parsed, and parsing_error, which is useful when debugging structured responses or inspecting model metadata.

Tip: Schema validity is not factual validity. A structurally correct response may still contain incorrect information. Validate important facts and business rules independently.

LCEL: piping runnables together

LangChain Expression Language, or LCEL, is a Python-based composition mechanism for constructing executable pipelines.

Instead of manually invoking each component, you can describe how data flows between components using the pipe operator, |.

Understanding runnables

A runnable is a component that exposes standardized execution methods.

Prompt templates, chat models, output parsers, and runnable wrappers around Python functions can participate in these pipelines.

The principal execution methods are:

Method Purpose
invoke() Process one input synchronously.
ainvoke() Process one input asynchronously.
batch() Process multiple independent inputs.
abatch() Process multiple inputs asynchronously.
stream() Produce synchronous output chunks.
astream() Produce asynchronous output chunks.

This common interface allows different components to be composed without custom integration code for every connection.

Building your first LCEL chain

The following example creates a reusable summarization pipeline.

Python
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = init_chat_model("openai:gpt-5.4-mini")

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a technical content summarizer."),
    ("human", "Summarize this in one sentence:\n{text}"),
])

chain = prompt | model | StrOutputParser()

result = chain.invoke({
    "text": (
        "LangGraph allows developers to build stateful "
        "AI applications using nodes, edges, and "
        "controlled execution flows."
    )
})

print(result)

Possible output:

Text
LangGraph builds stateful AI applications using graph-based execution.

The expression creates a RunnableSequence.

During invocation, the sequence performs three transformations:

  1. The prompt converts the input dictionary into a formatted prompt value.
  2. The model converts the prompt value into an AIMessage.
  3. The parser converts the message into a string.

Constructing the chain does not immediately execute it. Execution begins when an execution method is called.

Every component must produce an output compatible with the next component’s input.

Batch, asynchronous, and streaming execution

The same runnable sequence can be reused through different execution methods.

The following complete example demonstrates all three modes.

Python
import asyncio

from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = init_chat_model("openai:gpt-5.4-mini")

prompt = ChatPromptTemplate.from_messages([
    ("human", "Define {topic} in one short sentence."),
])

chain = prompt | model | StrOutputParser()

results = chain.batch(
    [
        {"topic": "REST API"},
        {"topic": "JSON"},
        {"topic": "SQL"},
    ],
    config={"max_concurrency": 2},
)

for result in results:
    print(result)

async def main():
    result = await chain.ainvoke({"topic": "LangGraph"})
    print(result)

asyncio.run(main())

for chunk in chain.stream({"topic": "Python"}):
    print(chunk, end="", flush=True)

print()

The batch produces three definitions, the asynchronous invocation produces one definition, and streaming displays the final definition incrementally when supported.

Batch execution generally processes independent inputs concurrently. It is not necessarily equivalent to a provider’s discounted offline batch API.

Streaming behavior depends on the components in the sequence. A component requiring the complete response before processing can introduce buffering.

The RunnableSequence reference explains these execution semantics.

Adding custom Python logic

Not every pipeline operation requires artificial intelligence. Input normalization, validation, and formatting can often be implemented more reliably using ordinary Python.

RunnableLambda wraps a Python callable as a runnable.

Python
from langchain_core.runnables import RunnableLambda

def normalize(text: str) -> str:
    return " ".join(text.strip().split())

def count_words(text: str) -> dict:
    return {
        "text": text,
        "word_count": len(text.split()),
    }

chain = RunnableLambda(normalize) | RunnableLambda(count_words)

result = chain.invoke("  Learn    LangChain   today.  ")

print(result)

Expected output:

Text
{'text': 'Learn LangChain today.', 'word_count': 3}

This pipeline requires no model, credentials, or network requests.

LCEL also supports parallel composition through RunnableParallel and conditional selection through RunnableBranch.

Use deterministic Python operations whenever the desired behavior is already known. Reserve model calls for tasks requiring language understanding, generation, or judgment.

When LCEL is not enough

LCEL is particularly effective when the application has a well-defined data transformation pipeline.

However, agentic applications frequently need more than a predefined sequence.

Consider an assistant that must decide whether a calculator or search tool is required, execute the selected operation, inspect its result, and potentially request another operation before answering.

The following diagram illustrates this repeating execution pattern.

When LCEL is not enough diagram: START to Model Node; Model Node to Tool needed?; Tool needed? to Execute Tool (Yes); Execute Tool to Update State; Update State to Model Node; Tool needed? to Final Answer (No); Final Answer to END.

LCEL can express branching, parallel operations, retries, and custom functions. Nevertheless, complex cyclic execution becomes harder to manage when these behaviors are hidden inside nested runnable functions.

LangGraph provides an explicit orchestration model for these requirements.

Requirement LCEL LangGraph
Sequential processing Built-in Built-in
Conditional branching Supported Explicit routing
Cyclic execution Custom implementation Native graph cycles
Shared workflow state Application-managed Graph-managed state
Durable checkpoints External implementation Checkpointer integration
Pause and resume Custom implementation Native interrupt support

Using LCEL inside a LangGraph node

LCEL and LangGraph are complementary rather than competing technologies.

A LangGraph node can use an LCEL chain to perform a specific transformation while the graph manages the broader execution flow.

The following example embeds a summarization chain inside a minimal LangGraph application.

Python
from typing import TypedDict

from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    article: str
    summary: str

model = init_chat_model("openai:gpt-5.4-mini")

prompt = ChatPromptTemplate.from_messages([
    ("system", "You summarize technical articles."),
    ("human", "Summarize this article in one sentence:\n{article}"),
])

summary_chain = prompt | model | StrOutputParser()

def summarize(state: State) -> dict:
    summary = summary_chain.invoke({
        "article": state["article"]
    })
    return {"summary": summary}

builder = StateGraph(State)

builder.add_node("summarize", summarize)
builder.add_edge(START, "summarize")
builder.add_edge("summarize", END)

graph = builder.compile()

result = graph.invoke({
    "article": "LangGraph supports controlled, stateful AI workflows.",
    "summary": "",
})

print(result["summary"])

Possible output:

Text
LangGraph enables controlled AI workflows with persistent execution state.

The chain handles prompt construction, model invocation, and text extraction. The graph handles state and node execution. The node returns a partial state update containing the generated summary.

This distinction becomes increasingly important as workflows grow. Durable persistence is not enabled in this example; it requires configuring a checkpointer.

Common mistakes and production best practices

Beginners often encounter problems not because the model is incapable, but because component boundaries are poorly defined.

Avoid these common mistakes:

  • Treating model responses as strings: Inspect the message before extracting text, particularly when tool calling is enabled.
  • Assuming automatic memory: Explicitly manage conversation history or use LangGraph persistence.
  • Trusting generated JSON blindly: Validate structured responses and handle parsing failures.
  • Using models for deterministic calculations: Prefer ordinary Python or dedicated tools for exact operations.
  • Building excessively large chains: Separate independent responsibilities into reusable components.
  • Ignoring operational failures: Handle rate limits, timeouts, invalid responses, and provider errors appropriately.

In production, version prompts and dependency sets, evaluate representative inputs, track latency and token consumption, and avoid logging sensitive customer information unnecessarily.

Test prompt formatting and deterministic transformations independently from live model calls. This makes failures easier to isolate and reduces testing costs.

Connection to the next lesson

Our chapter project is an AI assistant equipped with calculator and search tools.

The components introduced here will become the assistant’s foundation. Its prompt will describe how it should behave, its messages will represent conversation context, and its model will decide what information is needed.

In the next lesson, Tools in LangChain, you will define executable Python tools, expose their schemas to a chat model, inspect generated tool calls, execute those calls, and return results through ToolMessage objects.

Those capabilities will prepare you to combine model reasoning with external operations and eventually orchestrate complete agentic workflows using LangGraph.

Exercise

Build a structured customer support classifier

Build a LangChain pipeline that classifies customer support tickets into billing, technical, account, or general categories. Define a Pydantic schema containing the category, priority, summary, and suggested response. Create a reusable chat prompt template and compose it with a model configured for structured output using LCEL. Test the pipeline with at least three different support tickets.

Python
from typing import Literal

from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate

model = init_chat_model("openai:gpt-5.4-mini")

class SupportTicket(BaseModel):
    # TODO: Define category using Literal
    # TODO: Define priority using Literal
    # TODO: Define summary and suggested_response
    pass

# TODO: Create a ChatPromptTemplate with system
# and human messages.

# TODO: Configure the model for structured output.

# TODO: Compose the pipeline using LCEL.

tickets = [
    "I was charged twice for my monthly subscription.",
    "The application crashes every time I upload a file.",
    "I forgot my password and cannot access my account.",
]

for ticket in tickets:
    # TODO: Invoke the pipeline and print the result.
    pass

Summary

  • LangChain provides reusable abstractions for interacting with language models and composing AI application components.
  • Chat models accept structured messages and return AIMessage objects containing generated content and potentially additional metadata.
  • Prompt templates separate reusable instructions from dynamic application inputs.
  • Output parsers transform generated responses into formats that application code can consume.
  • Native structured output combines model-supported schema constraints with application-level validation.
  • LCEL composes compatible runnables into pipelines supporting synchronous, asynchronous, batch, and streaming execution.
  • LangGraph extends these building blocks with explicit state management, cyclic execution, durable persistence, and workflow orchestration.