The LangChain map and Runnables
- Advanced
- 35 min
- Lesson 1 of 7 in LangChain ecosystem
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Function and tool callingTools and agents
- Completed:Agentic patterns: ReAct, planning and memoryTools and agents
You will be able to
- Say what LangChain, LangGraph, LangSmith and Deep Agents are each for, and how they relate.
- Explain what the Runnable interface gives a component, how a pipe and a dict compose Runnables, and where that style stops being enough.
- Get typed output and tool calls from a chat model, and explain why identity values reach a tool by injection and not as model-chosen arguments.
- Decide for a given job whether to use LangChain, LangGraph or a plain provider SDK call, and whether retrieval should be a fixed step or a tool.
The team opens the documentation for their agent toolkit. One section shows pieces that snap together in a row. Beside it is a long list of other packages, each with its own page.
Vihaan has today’s ticket in hand. “Right away,” he says. Nobody has told him what the job is for.
Which part does today’s job need, and which do you leave alone?
Concept
The toolkit in the story is LangChain, a widely used open-source framework for building applications on language models. It is a toolbox, not a method. Using it well means knowing which part holds the piece you need and leaving the rest alone.
The word covers several things that are easy to blur: a core of shared interfaces, an agent builder, a separate graph runtime called LangGraph, a hosted platform called LangSmith, and a harness product called Deep Agents. This lesson draws the map, then looks at the two pieces you touch first: the Runnable (the common shape of every component) and the chat model with its structured output and tools. It ends with the question interviewers actually ask: when should you not use any of it?
Why It Matters
Most teams that build an agent need the same plumbing: a model interface that survives a vendor change, tool calling, retries, streaming, state that outlives one request, and a way to see what happened. A framework sells that plumbing. It also sells its abstractions, its release history and its learning surface. Knowing which part you are buying is the difference between “we used LangChain” and an architecture you can defend.
It is also the most common orientation question for agent roles that use this stack: “How do LangChain, LangGraph and LangSmith fit together?” A one-minute answer with a clear stance on when not to use them is a strong start to the rest of the interview.
Mental Model
The toolkit has three parts. LangChain offers pieces that fit together and a ready-made agent: quick, with sensible defaults. LangGraph is the workflow map: you draw steps and the paths between them, and a shared state carries information along, so the job can pause, resume and loop. LangSmith is the recorder you attach to any application, which also works on applications built with a different toolkit.
You rarely need the whole shop. Name the job first, then take the one part that does it.
The ecosystem map
The official overview describes the pieces this way, and this lesson follows it (read 2026-10-21):
- LangChain is an agent framework. Its
create_agentfunction is described as a minimal, configurable harness: the prompt, tools and middleware around a model loop. It also offers a standard model interface, one API across chat models and embeddings from many providers. - LangGraph is a low-level orchestration framework and runtime for long-running, stateful agents. It does not prescribe prompts or an architecture. The docs say LangChain’s agents are built on it, which is where durable execution, human-in-the-loop and persistence come from. It also works without LangChain.
- LangSmith is the observability platform for tracing, debugging and evaluating agents built with any framework. Tracing is switched on through environment variables. A later pair of lessons covers it.
- Deep Agents is described as a harness with planning, subagents, filesystem tools and context management on top of LangGraph. If you read what an agent harness is, this is one packaged example.
| Piece | Reach for it when |
|---|---|
| langchain-core | It is already underneath: shared interfaces for models, messages and tools |
| langchain | You want a standard tool-calling agent quickly, or one model interface across vendors |
| Provider packages | You swap or add a vendor, store or loader without rewriting application code |
| langgraph | You need explicit state, branching, loops, approvals or a job that resumes |
| Deep Agents | The task is long and open-ended and you want a planning-and-subagents harness ready made |
| LangSmith | Anything you will run in production and have to debug, with or without LangChain |
Two relationships to remember. A LangChain agent is built on LangGraph, so moving to LangGraph later is a step down a level, not a rewrite. And LangSmith is separate: it can watch code that never imported LangChain.
What 1.0 changed
Old tutorials still circulate, and an answer built on them dates you. The 1.0 release notes, read 2026-10-21, list these changes:
create_agentis the standard way to build an agent in LangChain and replacescreate_react_agentfromlanggraph.prebuilt. It runs the basic loop: call the model, let it choose tools, finish when it picks none.- Middleware is the extension mechanism for that loop. Lesson 2 covers it.
- Structured output is produced inside the main loop, not in an extra model call, which the notes say reduces cost.
- Standard content blocks: a
content_blocksproperty gives a provider-neutral view of text, reasoning and tool calls. The notes list the providers supported at the time and say broader support is coming. - A smaller namespace: legacy chains, retrievers, the indexing API, the hub module and other deprecated pieces moved to a package called
langchain-classic.
On stability, the versioning page says breaking changes arrive only in major releases and that deprecated APIs are removed in a later major version. Treat names such as LLMChain, AgentExecutor and the old memory classes as legacy.
Chat models and messages
One entry point creates a model from a string. The provider can be inferred, or written as a prefix.
# Illustrative: model names change often. Check your provider's current list.
from langchain.chat_models import init_chat_model
model = init_chat_model("provider:model-name", temperature=0, max_retries=6)
reply = model.invoke("Explain a KV cache in one sentence.")
print(reply.content)
for chunk in model.stream("Explain a KV cache in one sentence."):
print(chunk.content, end="")
answers = model.batch(["question one", "question two"], config={"max_concurrency": 5})What to notice:
invoke,streamandbatchare the same three verbs on every model.batchruns calls in parallel from the client, andmax_concurrencycaps how many at once. Leave it unset against a rate-limited provider and you invite 429 errors.- Messages come in kinds: system, human, AI and tool. An AI message can carry tool calls. A tool call is only valid if a tool message with the matching call id follows. Hand-written loops that skip this are a common source of provider errors.
max_retriesdefaults to 6 in the version of the docs read, with backoff. Client errors such as a bad key are not retried. A retry that works is not free: it adds latency and, for a write, may repeat a side effect.
What the abstraction costs. One interface across vendors means features that only one vendor has arrive late or through escape hatches. If you depend on such a feature, test that the wrapper exposes it.
Runnables and composition
Every component in langchain-core (a model, a prompt template, a parser, a retriever) is a RunnableRunnableLangChain's common interface for a component such as a model, prompt, parser or retriever: the same calls for one input, a batch, an async call or a stream, so components can be composed with a pipe.Open the glossary entry: an object with a shared set of methods for calling it once, in a batch, asynchronously, or as a stream. Because they share a shape, they compose. The pipe operator joins two Runnables into a sequence, and a dict of Runnables runs its branches in parallel and gathers their results under the keys.
# Illustrative: a retrieval chain written in the pipe style (LCEL).
chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
answer = chain.invoke("What is a KV cache?")Read it left to right. The dict fans the question out: one branch retrieves and formats documents, the other passes the question through. The prompt fills its two slots, the model answers, the parser turns the message into a string. You wrote one definition and got synchronous, asynchronous, batch and streaming calls from it, and a LangSmith trace if tracing is on.
The names you meet most:
| Primitive | What it does |
|---|---|
| Sequence (the pipe) | Run left to right, passing each output to the next |
| Parallel (a dict) | Run branches on the same input and collect a dict |
| Passthrough | Carry the input forward, optionally adding computed keys |
| Lambda | Wrap a plain function as a Runnable |
| Branch | Pick one of several paths from a condition on the input |
Where it stops. A pipe chain is a one-way flow with no loops and no state that survives the call. That is fine for prompt, model, parse. It is the wrong tool the moment you need to try again until a check passes, branch on something learned midway, wait for a person, or resume after a crash. The docs point those jobs at LangGraph, and you can still use a chain inside a single graph step. Debugging also gets harder as pipes grow: a three-step pipeline is often clearer as three plain function calls.
Typed output from a model
Free text is hard to use in code. Two routes give you typed data.
On a bare model, with_structured_output takes a schema (a Pydantic model, a typed dict or a JSON schema) and returns data in that shape:
# Illustrative.
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: str = Field(description="billing, bug or how-to")
priority: int = Field(ge=1, le=5)
typed = model.with_structured_output(Ticket)
ticket = typed.invoke("My card was charged twice, please help.")The method accepts options for the mechanism and for returning the raw reply with a parse error, so you can inspect failures instead of guessing.
In an agent built with create_agent, you pass response_format instead. The docs describe two strategies. A provider strategy uses the vendor’s native structured output when the model supports it. A tool strategy gets the same result through tool calling, so it works on models without native support. A bare schema picks one for you, and the result appears under the structured_response key of the final state. With the tool strategy, a failed validation is returned to the model as an error message so it can fix its output, and handle_errors controls that retry.
Do not read “typed” as “guaranteed”. A schema reduces malformed output; it does not remove it. A long answer can be cut off at the token limit and arrive as broken JSON, a loose schema lets the model fill fields with filler, and a value can be valid and still wrong. Validate, retry with the error a bounded number of times, and decide what the program does when it still fails. For the general technique, see structured outputs and reasoning.
Tools
A tool is a function plus a description the model can read. The decorator builds the schema from the function: the docstring becomes the description and the type hints become the input schema (the docs say hints are required). So the docstring is part of your prompt, and the quality of a tool description matters more than clever code inside it. See function and tool calling for the design rules.
# Illustrative.
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime
@dataclass
class UserContext:
user_id: str
@tool
def get_order(order_id: str, runtime: ToolRuntime[UserContext]) -> dict:
"""Look up one order by id. Use when the user asks where their order is."""
return db.fetch(order_id, owner=runtime.context.user_id)Look at what the model sees: one argument, order_id. The runtime parameter is hidden from the model and filled in by the framework at call time. Through it a tool can read the conversation state, per-call context such as a user id, the long-term store, the call id and a stream writer. The user id comes from the caller’s session and is passed with the invocation, never from the model’s output.
This is a security rule, not a style choice. If user_id were an ordinary argument, a prompt-injected document or a persuasive user could make the model call the tool with someone else’s id. Anything that decides whose data or which tenant should be injected. See guardrails and prompt injection.
Two more habits. Return errors the model can read and act on, and keep real exceptions for bugs. In create_agent, tool-call middleware is the documented place to turn an exception into a message for the model. And make write tools safe to repeat: lesson 4 shows why a step can run twice.
Retrieval in LangChain terms
LangChain’s retrieval building blocks are the pieces you already know: loaders, splitters, embeddings, a vector store, and a retriever, defined in the docs as an interface that returns documents for an unstructured query. A retriever is a Runnable, so it drops into a pipe chain. It can also be wrapped as a tool.
That gives the two shapes the docs name, plus a middle one:
| Shape | How it works | Control and latency | Fits |
|---|---|---|---|
| Two-step RAG | Always retrieve, then generate | High control; predictable latency | FAQ and documentation bots |
| Agentic RAG | Retrieval is a tool; the model decides when and how often | Low control; latency varies | Assistants with several tools |
| Hybrid | Two-step plus query rewriting, retrieval checks and answer checks, possibly looping | Medium control; latency varies | Ambiguous queries, quality-sensitive flows |
The framework provides the plumbing. Whether the answers are good still depends on chunking, retrieval quality, reranking and evaluation, covered in the RAG module. Pick the shape from the variety of questions and your latency budget, not from what the framework makes easiest.
Memory in 1.x, in one paragraph
Older tutorials use memory classes. In the current model, a conversation’s history is part of the agent’s state, kept between calls by a persistence layer keyed on a thread id, and knowledge that should outlive a conversation goes in a separate store. Lessons 3 and 4 build that up. The practical rule for today: if new code imports an old memory class, check whether it came from a pre-1.0 tutorial.
When not to use it
An honest answer to “isn’t LangChain over-engineered?” is more convincing than a defence. Early versions drew criticism for heavy abstractions and breaking changes, and a framework is still a dependency you maintain. The framework earns its place when you can point to something concrete it provides.
| Option | Strength | Cost | Pick when |
|---|---|---|---|
| LangChain with LangGraph | Provider portability, a resumable runtime, human approval, streaming, tracing | A large API surface and a release history to follow | Multi-step, stateful agents on a team that wants one stack |
| Provider SDK and plain Python | Transparent, few dependencies, newest vendor features first | You write retries, state, streaming and tracing yourself | One model call or a simple feature; maximum control |
| A workflow engine such as Temporal | Proven durable execution | Not model-aware | Your company already runs it and reliability is strict |
| Another agent framework or a vendor’s agent SDK | Ergonomics for a style such as role-based teams, or tight vendor integration | Different state model; vendor alignment | A fast prototype, or a single-vendor product |
A usable answer: “I use it where I can name the benefit: one model interface across vendors, a checkpointed runtime with approvals, streaming and tracing. For a single prompt and a parser I call the SDK directly, and I do not wrap everything in a pipe chain for its own sake.”
Real-World Application
A support team wants an assistant that answers from its help centre and can look up an order. Walk the choices. Retrieval over a fixed document set is the two-step shape: always retrieve, then answer. The order lookup is a tool that receives the user id by injection. Output is typed so the ticket system can route it. The first version is a create_agent call with those two pieces. Nothing needs a graph yet. Once the team adds refund approval by a person, which must pause and resume across hours, the runtime question arrives, and the graph is the next step down.
Keep a record of why each part is there. If the answer to “what is this for?” is “the tutorial had it”, remove it.
Interview Perspective
Expect: “How do LangChain, LangGraph and LangSmith fit together?”, “What is a Runnable?”, “Why would you not use LCEL for a retry-until-valid loop?”, “Is LangChain over-engineered?”, “How do you stop the model passing a user id to a tool?”
A good first answer: LangChain is the quick path to an agent and a common model interface; the agent is built on LangGraph, which is the control path for state, loops and approvals; LangSmith is observability, evaluation and deployment, and works with other frameworks. Then name one case where you would use none of it.
Common mistakes: using the old chain, executor and memory classes in new code; building a loop out of pipes; letting the model supply identity arguments; treating typed output as a guarantee; passing a whole retrieved corpus instead of a few top results; leaving max_concurrency unset on a batch.
Provenance: Common industry pattern. These are the questions this topic tends to draw for agent roles; none is verified for a named company. The ecosystem changes quickly, so say which version you last read.
Practice Questions
- Basic: What does
prompt | model | parsergive you that three separate function calls do not? - Intermediate: A teammate’s tool takes
user_idas a normal argument. Explain the risk and show the fix. - Advanced: Your pipe chain must regenerate until a validator passes, at most three times. Why is the pipe style the wrong shape, and what replaces it?
- Product-Company: Design a fallback from a primary model to a secondary one with caching and a rate limit. Which behaviours could silently lower quality?
Activity
Draw the map from memory in under a minute: three counters, what each sells, and one arrow from LangChain to LangGraph and one from LangSmith to “any framework”. Then take a feature you have built or want to build and write one line for each piece: use it, or leave it, and why.
Homework
Write a one-page decision note for a team about to adopt the stack for a support assistant. Cover which pieces you would use on day one, which you would defer, the first signal that would move you from create_agent to a graph, and one reason you would keep a direct SDK call somewhere.
Quick Revision
- LangChain: quick agent and common model interface. LangGraph: stateful runtime that LangChain agents run on. LangSmith: tracing, evaluation and deployment, for any framework. Deep Agents: a packaged harness on LangGraph.
- Every component is a Runnable, so
invoke,batchandstreamlook the same; pipes compose them and a dict runs branches in parallel. - A pipe chain has no loops and no durable state. Use a graph for those.
- Typed output reduces malformed output. It does not remove it.
- Inject identity into tools. Do not let the model choose it.
- Two-step retrieval is predictable; agentic retrieval is flexible and variable.
- Name the job before the part.
Check yourself
- Walk-through: In sixty seconds, explain how the three products fit together and when you would use none of them.
- Variation: Repeat it for a team that already runs a workflow engine.
- Common misconception: “LangSmith needs LangChain.” It does not; it traces other frameworks and plain code.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Agents (LangChain documentation) (opens in a new tab)Essential
The page that defines an agent as a model calling tools in a loop and lists every create_agent parameter; read it before the next lesson.
Workflows and agents (LangGraph documentation) (opens in a new tab)
Shows the same job written as a fixed workflow and as an agent, which helps when deciding whether a pipe, an agent or a graph fits.
The validation library behind the typed-output examples; field constraints such as the priority range are defined here.
Middleware overview (LangChain documentation) (opens in a new tab)
A short preview of the extension mechanism that the next lesson uses to put limits and approvals around the agent loop.
Further reading
Building effective agents (opens in a new tab)Essential
Argues for the simplest design that works, which is the reasoning behind choosing a plain SDK call over a framework.
LLM06:2025 Excessive Agency (opens in a new tab)
Explains the risk behind letting a model choose powerful arguments, which is the reason identity is injected.
More for this module: LangChain ecosystem resources
Practice
Test what you just read. Quizzes and cards are grouped by module: LangChain ecosystem.
Check yourself12 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.