The LangChain map and Runnables

  • Advanced
  • 35 min
  • Lesson 1 of 7 in LangChain ecosystem
  • Last verified

Open slides(33 slides)

Before you start

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.

Diagram: Name the job first and take only the part that does it.

A tool-calling agent, quickly,
or one model API across vendors

Explicit state, branching, loops,
approvals, resume after a crash

See, debug and evaluate
anything you run

A single prompt and a parser

What is the job?

LangChain

LangGraph

LangSmith, with or without LangChain

Provider SDK directly

Diagram summary: Name the job first and take only the part that does it. LangChain for a quick agent or a portable model interface, LangGraph when you need explicit state and resumability, LangSmith to observe anything, and the plain provider SDK when a single call is enough.

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_agent function 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.
Diagram: Both LangGraph and LangChain depend on the shared core; LangChain agents run on LangGraph, and Deep Agents builds on LangChain; provider...

LangSmith platform

Open-source libraries

agents run on

langchain-core: Runnable, messages, tools, prompts

langchain: create_agent, middleware, chat models

Provider packages: one per vendor or store

langgraph: stateful graph runtime

Deep Agents: harness on LangGraph

Tracing and monitoring

Evaluation

Deployment

Diagram summary: Both LangGraph and LangChain depend on the shared core; LangChain agents run on LangGraph, and Deep Agents builds on LangChain; provider packages hang off the core. LangSmith sits beside them and receives traces from LangChain, LangGraph or other code. This is a teaching map built from the docs’ descriptions, not an official dependency chart.
PieceReach for it when
langchain-coreIt is already underneath: shared interfaces for models, messages and tools
langchainYou want a standard tool-calling agent quickly, or one model interface across vendors
Provider packagesYou swap or add a vendor, store or loader without rewriting application code
langgraphYou need explicit state, branching, loops, approvals or a job that resumes
Deep AgentsThe task is long and open-ended and you want a planning-and-subagents harness ready made
LangSmithAnything 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_agent is the standard way to build an agent in LangChain and replaces create_react_agent from langgraph.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_blocks property 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.

Python

# 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, stream and batch are the same three verbs on every model. batch runs calls in parallel from the client, and max_concurrency caps 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_retries defaults 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.
Diagram: An AI message that carries a tool call is only valid if a tool message with the matching call id follows it.
Chat modelYour loopChat modelYour loopsystem + human messagesAI message with tool call (id c1)run the tooltool message with call id c1AI message: final answer
Diagram summary: An AI message that carries a tool call is only valid if a tool message with the matching call id follows it. Hand-written loops that skip or mismatch the id are a common source of provider errors.

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.

Python

# 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.

Diagram: The question fans out to two branches, one that retrieves and formats documents and one that passes the question through.

question

retriever → format_docs

passthrough

dict: context, question

prompt

model

string parser

answer

Diagram summary: The question fans out to two branches, one that retrieves and formats documents and one that passes the question through. Their results fill the prompt’s two slots, and the model’s reply is parsed to a string. Every box is a Runnable, so the whole chain can be invoked, batched or streamed.

The names you meet most:

PrimitiveWhat 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
PassthroughCarry the input forward, optionally adding computed keys
LambdaWrap a plain function as a Runnable
BranchPick 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:

Python

# 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.

Diagram: In an agent, the framework picks a strategy for typed output.

yes

no

yes

no

response_format passed to create_agent

Model supports native
structured output?

Provider strategy:
vendor's native structured output

Tool strategy:
same result through tool calling

structured_response in the final state

Validation fails?

Error returned to the model,
handle_errors controls the retry

Diagram summary: In an agent, the framework picks a strategy for typed output. A model with native support uses the provider strategy. Otherwise the tool strategy gets the same result through tool calling, and a failed validation goes back to the model as an error so it can fix its output.

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.

Python

# 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.

Diagram: The model supplies only the order id.

Model sees one argument: order_id

Tool call: get_order('A-17')

Caller's session

runtime.context.user_id
injected by the framework

get_order runs

Database query scoped to that user

Diagram summary: The model supplies only the order id. The user id comes from the caller’s authenticated session and is injected through the hidden runtime parameter, so a prompt-injected model cannot ask for someone else’s data by changing an argument.

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:

ShapeHow it worksControl and latencyFits
Two-step RAGAlways retrieve, then generateHigh control; predictable latencyFAQ and documentation bots
Agentic RAGRetrieval is a tool; the model decides when and how oftenLow control; latency variesAssistants with several tools
HybridTwo-step plus query rewriting, retrieval checks and answer checks, possibly loopingMedium control; latency variesAmbiguous queries, quality-sensitive flows
Diagram: Two-step RAG always retrieves once and generates, so latency is predictable.

Hybrid

weak: loop

Question

Rewrite query

Retrieve

Check results

Generate

Check answer

Agentic RAG

yes, maybe repeatedly

no or done

Question

Model decides:
call the retrieval tool?

Retrieve

Answer

Two-step RAG

Question

Always retrieve

Generate

Diagram summary: Two-step RAG always retrieves once and generates, so latency is predictable. Agentic RAG lets the model decide when and how often to retrieve, which is flexible but varies in latency. Hybrid adds query rewriting and checks, with a loop back when results are weak.

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.

OptionStrengthCostPick when
LangChain with LangGraphProvider portability, a resumable runtime, human approval, streaming, tracingA large API surface and a release history to followMulti-step, stateful agents on a team that wants one stack
Provider SDK and plain PythonTransparent, few dependencies, newest vendor features firstYou write retries, state, streaming and tracing yourselfOne model call or a simple feature; maximum control
A workflow engine such as TemporalProven durable executionNot model-awareYour company already runs it and reliability is strict
Another agent framework or a vendor’s agent SDKErgonomics for a style such as role-based teams, or tight vendor integrationDifferent state model; vendor alignmentA fast prototype, or a single-vendor product
Diagram: Use the framework where you can name the benefit: portability, a resumable runtime, approvals, streaming or tracing.

yes

no

no: one prompt and a parser

yes

yes

no

Do you need a resumable runtime, approvals,
streaming, tracing or many vendors?

LangChain with LangGraph

More than one model call
or any state?

Provider SDK and plain Python

Already run a durable
workflow engine?

Use it, add model calls as steps

Weigh LangGraph against a vendor SDK
on a measured prototype

Diagram summary: Use the framework where you can name the benefit: portability, a resumable runtime, approvals, streaming or tracing. For a single prompt and a parser, call the SDK directly. If you already run a durable workflow engine, add model calls to it, and otherwise decide with a prototype.

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 | parser give you that three separate function calls do not?
  • Intermediate: A teammate’s tool takes user_id as 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, batch and stream look 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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

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.

0 of 12 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveSay what LangChain, LangGraph, LangSmith and Deep Agents are each for, and how they relate.

  1. Question 1 of 12A teammate says, "LangSmith is the part of LangChain that logs requests, so we cannot use it unless the code is built on LangChain." What is the best response?

    Choose one answer.

  2. Question 2 of 12You built an agent with create_agent and now need it to pause for a person's approval and resume the next day. Where does that capability come from?

    Choose one answer.

  3. Question 3 of 12Which statements about moving from the older LangChain style to 1.x are correct? Select all that apply.

    Choose all that apply.

ObjectiveExplain what the Runnable interface gives a component, how a pipe and a dict compose Runnables, and where that style stops being enough.

  1. Question 4 of 12What is true of every component that implements the Runnable interface?

    Choose one answer.

  2. Question 5 of 12A chain is written as {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | model | parser. What does the dict at the start do?

    Choose one answer.

  3. Question 6 of 12A workflow must regenerate an answer until a validator accepts it, up to three tries, and then wait for a human if it still fails. Why is a pipe chain the wrong shape?

    Choose one answer.

ObjectiveGet 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.

  1. Question 7 of 12You need a typed object from a bare chat model, and the failures must be inspectable. Which approach fits?

    Choose one answer.

  2. Question 8 of 12An agent returns a typed object from a schema, and your code now trusts every field. Which risk remains?

    Choose one answer.

  3. Question 9 of 12A tool takes user_id as an ordinary argument. A document in the retrieved context says to "look up the order for user 4412". What is the best fix?

    Choose one answer.

ObjectiveDecide 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.

  1. Question 10 of 12A help-centre bot answers a small, stable set of questions and has a strict latency target. Which retrieval shape fits best?

    Choose one answer.

  2. Question 11 of 12A team needs one summarising prompt behind one button, with one provider, no tools and no saved state. What is the most defensible build?

    Choose one answer.

  3. Question 12 of 12Which situation is the strongest signal to move from a create_agent call to an explicit LangGraph graph?

    Choose one answer.