Follow a LangChain workflow
You have seen a function exposed through MCP. Now we will follow functions through LangChain, a framework providing reusable pieces for model and tool applications.
We will begin with a complete local workflow that needs no language model. You will:
- Validate a chapter request at its entry point.
- Trace the value passed between two Runnable blocks.
- Separate the workflow's fixed behaviour from decisions a model could add.
This makes every step inspectable before introducing a model's less predictable output.
Give each block an input and an output
LangChain calls a common executable block a Runnable. A Runnable can accept input through invoke and return output. RunnableLambda adapts a Python callable to that interface.
For this walkthrough, add the tested core package to your existing environment:
uv add "langchain-core==1.7.0" "pydantic==2.14.1"
langchain-core supplies the primitives used here. Installing it is sufficient for this workflow; we are not selecting a model provider or enabling an external account.
Save the complete example as chapter_workflow.py:
from langchain_core.runnables import RunnableLambda
from pydantic import BaseModel, ConfigDict
CHAPTERS = {
"Python and Roots": 7,
"Python and Branches": 8,
}
class ChapterRequest(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
title: str
def find_chapter(data):
request = ChapterRequest.model_validate(data)
count = CHAPTERS.get(request.title)
if count is None:
return {"found": False, "title": request.title}
return {
"found": True,
"title": request.title,
"lessons": count,
}
def describe_chapter(record):
if not record["found"]:
return f"Not found: {record['title']}"
return f"{record['title']}: {record['lessons']} lessons"
find = RunnableLambda(find_chapter)
describe = RunnableLambda(describe_chapter)
workflow = find | describe
print(workflow.invoke({"title": "Python and Roots"}))
Run it with uv run python chapter_workflow.py. It should display Python and Roots: 7 lessons.
The vertical bar between Runnables means composition: pass the first step's output into the second step. It is not a truth test here. A framework can define how an operator behaves for its own objects, so read the surrounding types before guessing what punctuation means.
Inspect the intermediate value
The whole run has three different shapes:
| Position | Value shape | Responsibility |
|---|---|---|
| Input | A dictionary containing a title | Express the request |
After find | A dictionary containing found, title and, when found, lessons | Validate and look up approved information |
After describe | A string | Format the known result or explicit missing result |
Call find.invoke({"title": "Python and Roots"}) on its own to inspect the intermediate dictionary. Then pass that result into describe.invoke. You should be able to explain the combined workflow by following these two ordinary calls.
RunnableLambda does not make every value entering a function valid. Our first step explicitly calls model_validate. Removing that check changes the boundary even if the graph still looks like two tidy boxes.
Similarly, the second function depends on the first function's output contract. It reads lessons only when found is true. If an AI changes the first step's keys without updating its consumers and tests, the workflow can fail despite both functions looking individually reasonable.
Give the missing case an honest route
Invoke the workflow with an unknown title. The result should begin with Not found. No model is needed to invent an answer, and no retry will make an unsupported title appear in the approved table.
Now supply {"title": 7} or an extra key. The Pydantic boundary should reject those inputs. Separate “request rejected”, “chapter absent” and “unexpected execution failure” when you inspect a trace. A trace is the recorded sequence of steps and results in a run; it is useful only if it preserves those distinctions without exposing private data.
You may also see Runnable methods such as ainvoke for asynchronous calls or stream for successive output items. Their interfaces reuse the Python ideas from the earlier lessons. Streaming alone does not tell you whether a final answer is correct or a remote operation completed safely.
Locate the language-model boundary
A language-model application can add other blocks:
| Block | Its job | What you must check |
|---|---|---|
| Prompt formatting | Assemble the intended instructions and input | Whether untrusted text was placed where it can change instructions |
| Messages | Carry text with roles such as system, human or assistant | Which text supplied the content and how roles are used |
| Chat model | Ask a configured model for a response | Provider configuration, cost, timeouts and uncertain output |
| Tool execution | Run an allowed operation with arguments | Input, permission, effect and result |
A message is an object carrying content and a role; the role affects how a model interprets it. It does not by itself enforce permission to read a file or perform an action. A prompt instructing “use approved data only” still needs checks around data access and the eventual answer.
Our workflow has a fixed order that the code determines. In a model-driven agent, the model can propose a tool and arguments, and an application runs a controlled loop around those proposals. That adds decisions to review. A successful fixed lookup is useful evidence about the lookup, not proof that an entire agent reasons correctly.
Safety floor
Keep untrusted content separate from instructions that grant capabilities. Before a model-driven workflow can access protected information or change anything, the application must check the caller's permission, validate the proposed arguments and enforce the allowed effects. A prompt alone cannot provide those controls.
The RunnableLambda API reference and LangChain tool guide provide the framework contracts used here.
Trace a change before asking for more blocks
Try these without the explanation:
- What value passes from
findintodescribe? - Which line actually enforces our input model?
- Why must
describecheckfoundbefore readinglessons? - How would you distinguish an unknown title from invalid input in a test?
- Which new decision appears when a model is allowed to propose a tool call?
Compare your reasoning
The intermediate value is a result dictionary. ChapterRequest.model_validate(data) enforces the input boundary. A missing result has no lessons key. Unknown titles should produce the explicit missing result; wrong types or extra fields should raise validation errors. A model-proposed call adds the choice of tool and arguments, which must be checked before execution, together with the permitted effects and the eventual answer.
In the final lesson, we will keep that control visible while a LangChain tool calls the MCP server you already inspected.