15  The Functional API

Count what Chapter 12’s doc-bot needed to say “search the docs; if that misses, search the web; then answer”: an agent node, a route_after_agent router, three conditional edges, two back-edges, and a recursion_limit fuse (Chapter 6) to stop a confused model from circling. Written as a script, the same plan is three function calls and one if. Chapter 13 already set a hand-written while loop beside the graph-based agent. This chapter removes the graph from the doc-bot altogether.

@entrypoint and @task run plain Python control flow — if, for, function calls — on the LangGraph runtime. The checkpointer, interrupt(), and .stream() work as before; there is no StateGraph. Use this API when the control flow reads more clearly as Python than as edges.

The chapter is the same doc-bot on the same local model, written as the Python you would have written anyway, with two decorators added.

15.1 Connecting a model

The model connection is the one Chapter 12 established, unchanged:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="http://localhost:1234/v1",  # your local server, not the OpenAI cloud
    api_key="lm-studio",                   # the local server ignores the key
    model="qwen/qwen3.8-27b",              # a capable open model that follows instructions
    temperature=0,                         # 0 = as reproducible as a real model gets
    reasoning_effort="none",               # Qwen3.8 thinks by default; off for now
)

The model in this chapter is the one you already have; what is new is entirely how we orchestrate around it.

15.2 What we’re building

The flow is the doc-bot you already know: search the local docs first, fall back to the web only on a miss, then generate an answer from whatever came back.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> search("search_docs")
    search --> decide{"if not docs"}
    decide -.->|miss| web("web_search")
    decide -.->|hit| generate("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>generate")
    web --> generate
    generate --> END(["END"])

Hold this next to Chapter 12’s diagram and the shapes match, with one difference at the diamond. In the graph version it was an agent node that called the model, wrote a route, and handed control to add_conditional_edges. Here the diamond is a plain if not docs: in a Python function. That makes the diagram documentation: no code assembles it, so editing the if can leave it stale with nothing to warn you.

15.3 Two decorators, no graph

A unit of work becomes a @task. Its body is ordinary Python — but call it only from inside an @entrypoint (or a graph node), where the call returns a future; call it anywhere else and you get a RuntimeError. The decorator gives it two properties that matter:

  • Its return value is checkpointed, so it must be serializable (a list, a str, a dict of those; fine here). The inputs need not be — the cache keys on call position, not on re-serialized arguments.
  • On resume it replays from that cache instead of running again, which we will lean on hard in a moment.

Our three tasks are the doc-bot’s three jobs. search_docs and web_search are the same stubs from Chapter 7; generate is the same real model call from Chapter 12:

from langgraph.func import entrypoint, task   # the two decorators live here


@task
def search_docs(question: str) -> list[str]:
    q = question.lower()
    hits: list[str] = []
    for topic, docs in KNOWLEDGE_BASE.items():
        if topic in q:
            hits.extend(docs)
    print(f"   [search_docs] {len(hits)} hit(s)")   # a side effect — deduped on replay
    return hits                                      # may be empty — a real answer too


@task
def web_search(question: str) -> list[str]:
    print("   [web_search] falling back to a web search")
    return [f"[web] community thread about “{question}”"]


@task
def generate(question: str, docs: list[str], web: list[str]) -> str:
    sources = docs + web
    sources_text = "\n".join(f"- {s}" for s in sources) or "(no sources)"
    prompt = f"""
        Answer the user's question concisely, using only the sources
        below. Do not invent anything.

        Question: {question}

        Sources:
        {sources_text}

        Answer:"""
    answer = llm.invoke(prompt).content.strip()      # a real model call
    print("   [generate] the model wrote an answer")
    return answer

These functions take plain arguments and return plain values. There is no State TypedDict, no state.get("docs", []), no delta to merge. Data moves the way it moves in any Python program, as arguments and return values.

15.4 The flow is plain Python

@entrypoint marks where a run begins. Its body is the control flow, written as the if and function calls it was in the first place. A task call returns a future, and .result() blocks for its value — that one method is the only unusual punctuation in an otherwise ordinary function:

from langgraph.checkpoint.memory import InMemorySaver


@entrypoint(checkpointer=InMemorySaver())
def doc_bot(question: str) -> str:
    docs = search_docs(question).result()
    web = web_search(question).result() if not docs else []
    return generate(question, docs, web).result()

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart TD
    START(["START"]) --> search("search_docs")
    search --> decide{"if not docs"}
    decide -.->|miss| web("web_search")
    decide -.->|hit| generate("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>generate")
    web --> generate
    generate --> END(["END"])

Put this side by side with the compiled graph in Chapter 12. The entrypoint replaces the routing loop with if not docs: it searches once, uses the web only after a miss, then generates. None of what made the graph version a graph survives — no builder, no edges, no router, no recursion limit — because a straight-line function never needs to loop back to ask “what now?” The next line is what’s next.

One field disappeared with the graph. In Chapter 12 the agent needed a "docs" in state check to tell “searched and found nothing” from “haven’t searched yet.” Here, by the time control reaches the if, search_docs has already run, so an empty docs can only mean “searched, found nothing.” Position in the code carries the state the graph had to store in a field.

The checkpointer=InMemorySaver() on the decorator is the same checkpointer from Chapter 8, wired in the same spirit — hand the runtime a place to save, and every step is persisted (in-memory here, with the usual caveats — Chapter 8). That place to save is what the next two sections use.

15.5 Running it

We run the same two questions as Chapter 12 — one the local docs answer, one they don’t — but the call is a plain .invoke(question, config), and each question rides its own thread_id, the thread or timeline identifier from Chapter 8:

for i, q in enumerate(
    ["How do I configure Kafka batch consumers?",
     "How do I write a Python decorator?"],
    start=1,
):
    print(f"\n===== question: {q} =====")
    config = {"configurable": {"thread_id": f"a{i}"}}
    answer = doc_bot.invoke(q, config)   # no __interrupt__ -> returns the answer
    print("--- answer ---")
    print(excerpt(answer))               # first line only; the full text is in answer

(excerpt: first line, trimmed — Chapter 12.)

===== question: How do I configure Kafka batch consumers? =====
   [search_docs] 2 hit(s)
   [generate] the model wrote an answer
--- answer ---
To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` and tune the `max-poll-records` setting.

===== question: How do I write a Python decorator? =====
   [search_docs] 0 hit(s)
   [web_search] falling back to a web search
   [generate] the model wrote an answer
--- answer ---
The provided source is a community thread about the topic, but it does not contain the specific steps or code for writing a Python ...

The Kafka question hits the docs (2 hit(s)) and generates; the Python question misses (0 hit(s)), falls back to the web, and then generates — the same two paths as Chapter 12, now walked by an if instead of a router. This is one representative run (Chapter 12’s caveat applies), but one thing no longer varies: in Chapter 12 the route itself could wobble, because a model chose it; here the branch is if not docs, so the path is as fixed as any Python if, and only the prose inside generate is the model’s to vary.

15.6 Persistence, interrupts, and streaming without a graph

@entrypoint and @task give ordinary Python functions the three capabilities you built a graph for in Part I — persistence, interrupts, and streaming — without the graph. Persistence is already there: the checkpointer is on the decorator. Interrupts and streaming are the same calls as in the graph chapters, placed in a function body instead of a node.

Human-in-the-loop is the interrupt() / Command(resume=...) pair from Chapter 9. Add an approval gate before the model writes anything:

from langgraph.types import interrupt, Command


@entrypoint(checkpointer=InMemorySaver())
def doc_bot_with_approval(question: str) -> str:
    docs = search_docs(question).result()
    web = web_search(question).result() if not docs else []

    approved = interrupt(f"Generate an answer from {len(docs + web)} source(s)? (yes/no)")
    if approved != "yes":
        return "Declined by a human — no answer generated."

    return generate(question, docs, web).result()

Invoke it, then resume it with the human’s decision:

q = "How do I configure Kafka batch consumers?"
config = {"configurable": {"thread_id": "b1"}}
1paused = doc_bot_with_approval.invoke(q, config)
2print("paused, waiting for a human:", paused["__interrupt__"][0].value)
3answer = doc_bot_with_approval.invoke(Command(resume="yes"), config)
1
Runs up to the interrupt, saves a checkpoint, and hands control back.
2
The result carries an __interrupt__ entry holding the prompt text.
3
Resumed with the human’s decision on the same thread, it picks up where it paused.
===== with an approval gate =====
   [search_docs] 2 hit(s)
paused, waiting for a human: Generate an answer from 2 source(s)? (yes/no)
--- human approves; resuming (search_docs is silent = cache hit) ---
   [generate] the model wrote an answer
--- answer ---
To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` and tune the `max-poll-records` setting.

The interesting line is the one that is missing. On the first call, search_docs ran and logged 2 hit(s). On resume the entrypoint body runs again from the top (there is no other way to reach the line after the interrupt), yet search_docs printed nothing: its checkpointed result was replayed from cache, and only generate, which had not run before the pause, ran at all. That replay from cache is why a @task is the right home for anything with a side effect.

WarningGotcha: a task’s return must be serializable, and replay dedupes — it is not exactly-once

Two rules travel together, and both come from the same fact — a completed task’s return value goes into the checkpoint, keyed by where the call sits in the entrypoint’s body.

First, in a checkpointed workflow that return value must be serializable. A list, str, int, or dict of those is fine; a live database handle, an open socket, or a ChatOpenAI client is not, and returning one will fail when the runtime tries to save it. Return data, not live objects.

Second, put your side effects inside a task, and be precise about what that buys. On resume the entrypoint body replays from the top, so any bare print, HTTP POST, or row insert sitting loose in the entrypoint runs again. Move that work into a @task and, once the task has completed and its result is checkpointed, deterministic replay reuses the cached result instead of re-running the body — the side effect with it. That is replay deduplication, not an exactly-once guarantee: if the process crashes after the effect fires but before its result reaches the checkpoint, the resumed run finds no cached value and runs the task again — the POST or the insert happens twice. The cache narrows the window; it cannot close it. So this is the idempotency worry from Chapter 9, not a repeal of it — wrap the effect in a task to dedupe the common case, and make the external effect idempotent (an upsert, a natural key, an idempotency key on the request) so a second execution is harmless.

NoteDeep Dive: what to return vs. what to remember — entrypoint.final

Persistence has one more trick on a thread: declare a previous parameter and the checkpointer hands the entrypoint whatever it saved on the last run with this thread_id. By default that’s the return value. The moment “what the caller should get” and “what the next turn should remember” differ, wrap the return in entrypoint.final:

@entrypoint(checkpointer=InMemorySaver())
def doc_bot_session(question: str, *, previous: list[str] | None = None):
    asked = (previous or []) + [question]      # questions so far, this thread
    docs = search_docs(question).result()
    answer = generate(question, docs, []).result()
    return entrypoint.final(value=answer, save=asked)

value is what invoke returns; save is what lands in the checkpoint and arrives as previous on the next call. That’s the functional API’s slice of cross-turn memory — the full story (message history, summarization, long-term facts in the Store) is Chapter 17’s.

TipTry it: stream the steps as they finish

Streaming is Chapter 18’s subject; the taste here is what the functional API adds to it: each @task is a streaming unit, the way each node is in a graph. Swap .invoke for .stream and you get one chunk per task as it completes, keyed by the task’s name, then a final chunk keyed by the entrypoint:

config = {"configurable": {"thread_id": "s1"}}   # a fresh thread — a replayed one stays silent
for chunk in doc_bot.stream("How do I configure Kafka batch consumers?", config):
    # each chunk is {name: value}; shorten the model's prose, keep the lists whole
    print({name: excerpt(v) if isinstance(v, str) else v for name, v in chunk.items()})
===== streaming the steps =====
   [search_docs] 2 hit(s)
{'search_docs': ['Kafka Manual: use spring.kafka.listener.type=batch to enable batch consumption.', 'Kafka FAQ: batch consumers need max-poll-records tuning.']}
   [generate] the model wrote an answer
{'generate': 'To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` to enable batch consumption and tune the `max-poll-records` ...'}
{'doc_bot': 'To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` to enable batch consumption and tune the `max-poll-records` ...'}

Each finished task announces itself the moment it returns — a live progress feed for a UI, from the same runtime and no extra wiring. (For the Kafka question web_search never runs, so it never appears; run the Python question and watch a web_search chunk slot in between.)

15.7 When to use which

You now have two ways to build the same doc-bot, and neither is a beginner’s version of the other — they are two front doors to the same runtime. The choice is about what you want to be explicit.

Reach for the Graph API when the topology is the point: when you want the state machine drawn out and inspectable, when a diagram of nodes and edges is how you reason about the system, when you need to enforce a shape a model cannot wander out of (an approval that stands in the topology, where draw_mermaid() and a reader of the graph can both see it), or when subgraphs (Chapter 11), or parallel fan-out and reducers (Section 10.5), are doing load-bearing work. The compiled graph is a value you can hold, print, and draw — the topology is a first-class object, not just behavior you watch at runtime. (State inspection isn’t the divider: an @entrypoint is a Pregel app under the hood, so it exposes get_state/get_state_history too.)

Reach for the Functional API when the control flow reads more clearly as Python than as a graph: a script that calls some functions in order, with an if or a for where the graph would need a router and a back-edge, that you want to survive a crash, pause for a human, and stream its progress. The cost is the one named above: the flow is no longer a drawing you can print, so the diagram lives in a comment or a doc and drifts unless someone maintains it.

15.8 The operational rules

Three rules are what the chapter leaves you with:

  • Put every side effect inside a @task, so a resume replays it from the checkpoint instead of firing it again — and still make the effect idempotent, because a crash between the effect and its checkpoint re-runs the task, the same idempotency rule from Chapter 9.
  • Return data from a task, never a live object: the return value is serialized into the checkpoint, and a client handle fails at save time.
  • Choose the API by how the flow reads: the Graph API when the topology is the point and you want it drawn and enforced, the Functional API when three calls and an if say it more clearly than a router and a back-edge would.

Here, in both front doors, we are still the ones writing the if — the model decides nothing about the route. That was a choice, not a limit: Chapter 12 and Chapter 13 already let the model route, and Chapter 16 takes the next step, handing model-directed routing to a supervisor that dispatches to worker agents. Even there the legal topology — the nodes and the edges between them — is still one you register; what the run chooses is the path through it: which worker, in what order, how many times.

New pieces in this chapter

Piece Usage
Value
entrypoint.final Wraps an entrypoint’s return to split the caller’s value from what the thread remembers. return entrypoint.final(value=answer, save=asked); save arrives as the previous parameter next call
API
@task Decorator: marks a unit of work; called inside an entrypoint it returns a future. @task on def search_docs(…); its return is checkpointed, so it must be serializable
@entrypoint Decorator: marks where a run begins; the body is plain-Python control flow. @entrypoint(checkpointer=InMemorySaver()); the checkpointer on the decorator is what makes the flow durable
.result() On a task future: block for the task’s value. docs = search_docs(question).result(); call a task outside an entrypoint and you get a RuntimeError
doc_bot.stream() On the entrypoint: yields one chunk per task as it completes. for chunk in doc_bot.stream(q, config); a taste — Chapter 18 covers streaming in depth

Code in this chapter

File What it runs
code/ch13_functional_api.py The Chapter 10 doc-bot again, as plain Python control flow: @entrypoint and @task instead of a StateGraph.
code/ch10_real_llm.py The Chapter 5 doc-bot with a real model behind every node, routing on with_structured_output instead of parsing free text.

Challenge

Find the boundary the decorators draw, then port a graph feature — retry — into the functional entrypoint, make the task cache prove itself with a number you can assert, and show both styles walk the doc-bot down the same two paths.

🥉 Bronze — call a task from the wrong place

Take code/ch13_functional_api.py and call one of its @task functions from module scope — outside any entrypoint — then read what comes back. Do the same for the entrypoint itself, called normally.

You’ve got it when you can say, from the error text alone, what a @task needs that plain module scope cannot give it, and why the entrypoint is the thing that supplies it.

Hints: the failure is a RuntimeError, and its message names what is missing rather than what you did wrong — read it literally. Note where it raises: on the call itself, before any future comes back, so .result() never enters into it. The entrypoint called normally fails differently, and that difference is most of the answer.

office hours Worked solution with tests: code/answers/ch13_task_boundary.py.

🥈 Silver — port retry into the functional doc-bot

The Graph API gives a node a built-in retry (RetryPolicy, Chapter 21). Your job is to port that idea into the functional entrypoint — and in doing so you’ll hit the one place the functional style is freer than the graph, then prove the task cache is real instead of taking it on faith. Start from code/ch13_functional_api.py. Three steps:

1. Retry on a bad answer. Give generate a retry: if the model returns an empty or suspiciously short answer, call it again, up to twice. Inside the entrypoint this is just a for loop around the generate task — each pass is a fresh task call that really re-runs.

Two runs settle whether the loop is doing real work or only looking like it. Truncate the model’s first answer to a stub, then watch whether a second call actually goes out and which of the two answers the entrypoint hands back at the end. Then ask a question whose first answer is already good and count the generate calls — one is the number to look for. Hints: this is a retry on the output, which the Graph API’s RetryPolicy cannot do — a RetryPolicy fires only when a node raises, and a short-but-successful return looks like success, so it never triggers. Getting an output-based retry in a graph would mean making generate raise a retryable exception, or wiring a conditional edge that loops back on the answer. The functional version needs neither — a plain loop is enough.

2. Make the cache prove itself. The Gotcha claimed a completed task replays from its checkpointed result instead of re-running. Turn that claim into a number you can assert: run a workflow whose retry loop takes two real attempts, pause it after the loop, resume — and prove neither attempt ran again. Hints: count real runs with a module-level counter inside the task body; to make the retry fire deterministically, truncate the model’s first answer to a stub (the model stays real, only the failure is injected); and place the interrupt() after the loop, so both attempts are checkpointed before the pause. On resume the counter must not move, and no model call fires.

3. Show the two styles agree. Finally, tie back to Chapter 12: run the same two questions through the graph doc-bot (code/ch10_real_llm.py) and confirm your functional version’s traces take the same two paths the chapter-10 graph took — Kafka to the docs, Python to the web — one steered by a model router, one by an if.

office hours Worked solution with tests: code/answers/ch13_functional_retry.py.