Sub topic 8
LangChain: components and integrations
This chapter assumes you can write basic Python, have called a chat API such as the OpenAI SDK, and know what a Pydantic model is. Earlier chapters showed the hand-written versions of structured output, tool calling, and retrieval. Here you see what LangChain does with the same tasks, and where its abstractions help or get in the way.
What LangChain is
LangChain is a Python (and JavaScript) library of interchangeable parts for building LLM applications. Its core idea is a shared interface. A chat model from OpenAI, one from Anthropic, and one running locally all accept the same input and return the same kind of message object. Prompts, output parsers, retrievers, and tools follow the same pattern.
The library is split into packages:
| Package | Contents |
|---|---|
| `langchain-core` | Base interfaces (messages, prompts, runnables, tools) and the pipe syntax |
| `langchain-openai`, `langchain-anthropic`, and others | One package per provider, holding the chat model and embedding classes |
| `langchain-community` | Many third-party integrations, such as vector stores and document loaders |
| `langchain` | Higher-level chains and agent helpers built on the core |
| `langgraph` | A separate library for stateful, multi-step agent workflows |
Because of this split, installing langchain-openai pulls in the core interfaces but not every integration. Check what each package contains before you assume an import path. Module locations have moved between releases.
Components and the Runnable interface
The central abstraction is the Runnable. A Runnable is any object with a common set of methods:
invoke(input)runs once and returns the result.batch(inputs)runs over a list of inputs.stream(input)yields output in pieces as it is produced.ainvoke,abatch, andastreamare the async versions.
Chat models, prompt templates, output parsers, retrievers, and tools are all Runnables. Because they share these methods, you can connect them with the | operator. This syntax is called the LangChain Expression Language (LCEL).
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a concise assistant."),
("user", "Explain {topic} in one sentence."),
]
)
llm = ChatOpenAI(model="gpt-4o-mini") # reads OPENAI_API_KEY from the environment
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"topic": "an API client library"}))Each piece does one job:
- The prompt template fills
{topic}and produces a list of messages. - The chat model sends those messages to the provider and returns an
AIMessage. - The string parser pulls the text out of that message.
The result of prompt | llm | StrOutputParser() is itself a Runnable. You get stream, batch, and async support on the whole chain without writing it. Compare that with the bare SDK, where you would write each of those variations yourself.
Swapping providers
The earlier chapter on SDK limits pointed out provider lock-in. LangChain's answer is the shared chat model interface. To move the chain above to Anthropic, you install langchain-anthropic and change the model class and name. The prompt and parser stay the same.
LangChain also offers init_chat_model, which picks the provider class from a string. That helps when the provider is read from configuration.
Do not read "portable" as "identical". Providers differ in how they handle system messages, token limits, tool-call formats, and which sampling parameters they accept. LangChain hides some of these differences and exposes others as provider-specific arguments. Always run your own tests after a swap.
Structured output
The raw SDK version in an earlier chapter used JSON mode, a hand-written schema description, and model_validate_json. LangChain wraps that pattern in with_structured_output.
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: str
urgency: int = Field(ge=1, le=5, description="1 is low, 5 is critical")
llm = ChatOpenAI(model="gpt-4o-mini")
structured_llm = llm.with_structured_output(Ticket)
ticket = structured_llm.invoke("The site is down for all customers.")
print(ticket)with_structured_output returns a new Runnable. It converts your Pydantic class to a schema, tells the provider to follow it, and parses the reply into a Ticket instance. For providers that support native structured output or tool calling, LangChain picks whichever mechanism fits that provider. You do not write the system prompt that describes the JSON shape.
The cost is visibility. You no longer see the exact request unless you look for it (see the debugging section). If validation fails, the error surfaces from inside the library, and you decide whether to retry.
Tools
A LangChain tool is a Python function plus the metadata a model needs. The @tool decorator builds that metadata from the function name, type hints, and docstring.
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"Sunny and 21 C in {city}" # stand-in for a real weather lookup
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools([get_weather])
message = llm_with_tools.invoke("What is the weather in Paris?")
print(message.tool_calls)message.tool_calls is a list of dictionaries with name, args (already parsed into a dict), and id. In the raw SDK, arguments is a JSON string that you parse yourself. This is a small but real convenience.
As in the SDK, the model does not run the function. Your code, or an agent helper, must call the tool and send a ToolMessage back. LangChain provides pre-built agent constructors for that loop. Current guidance points to LangGraph for agents that need state, branching, or human approval steps. A hand-written loop from the earlier chapter is often still shorter for a single-tool assistant.
Retrieval components
LangChain also defines interfaces for the retrieval pipeline you wrote by hand:
- Document loaders read files, web pages, and databases into
Documentobjects. - Text splitters cut documents into chunks.
- Embedding classes turn text into vectors.
- Vector store classes wrap databases such as Chroma, FAISS, or pgvector.
- A retriever is a Runnable that takes a query string and returns documents.
Because a retriever is a Runnable, it slots into a chain. A common pattern is to run the retriever, format the documents into a prompt, then call the model. The value is the large catalog of ready-made integrations. The risk is that each integration has its own maintainer and quality level. LlamaIndex, covered next, concentrates more of its design on this part of the problem.
Seeing what is sent
Abstraction layers make one question hard to answer: what exactly did the model receive? LangChain gives you two main tools.
For local debugging, turn on global debug logging:
from langchain_core.globals import set_debug
set_debug(True)Every step of a chain then prints its input and output, including the final messages sent to the model. For production, LangSmith is LangChain's hosted tracing service. You enable it with environment variables, and it records each run as a tree of steps. Other tracing tools can also consume LangChain's callbacks. The observability chapter covers this in more detail.
Common errors
- Import errors after upgrading. Classes have moved between
langchain,langchain_community, and provider packages. Pin versions and read the release notes before upgrading. - Mixing old and new APIs. Older tutorials use
LLMChain,initialize_agent, and.run(). These are deprecated in favor of LCEL and LangGraph. Mixing styles produces confusing errors. - Passing the wrong input shape. A prompt with
{topic}needs a dict with atopickey. Passing a bare string fails with a missing-variable error. - Assuming a tool was executed.
bind_toolsonly lets the model request a tool call. Nothing runs until your code runs it. - Treating
with_structured_outputas a guarantee. Some modes still return malformed or schema-violating data. HandleValidationErrorand refusals. - Forgetting the prompt differences between providers. A chain that works with one model may need prompt changes for another.
What LangChain costs you
The earlier framework chapter described costs in general. For LangChain specifically:
- Dependency weight. The core is modest, but each integration adds packages. Large installs slow down container builds and widen your security review.
- API churn. The library has changed its recommended style several times. Code from a year ago may use deprecated paths.
- Indirection. A bug can sit three layers below the line you wrote. The stack traces are longer and the prompt is built out of sight.
- Surface area. The library does many things. Your project will use a small subset, but you still pay to track the rest.
It earns its place when you need many integrations, expect to switch providers, or want streaming, batching, async, and tracing without building them. If you call one model with one prompt, the SDK is shorter.
Exercise
You have a chain prompt | llm | StrOutputParser() and you switch llm from ChatOpenAI to a different provider's LangChain chat model. The code runs without errors, but the output quality drops. Give two reasons the shared interface did not prevent this, and one step you would take before shipping the change.
Show answer
The shared interface only standardizes the call and the message types. It does not make models behave the same. First, models differ in how they follow the same prompt, so wording tuned for one model can work worse on another. Second, provider-specific behavior such as system message handling, default sampling settings, and context limits can differ, and LangChain exposes some of these as provider-specific arguments you have to set yourself. Before shipping, run a fixed evaluation set of representative inputs through both versions, compare the outputs, and adjust the prompt or parameters. Turning on debug output or tracing to inspect the final messages sent to the new provider also helps.