The Functional API — @entrypoint and @task

Topic 4 of 4 in Streaming, async & Functional API24 min readAdvancedFree course

Overview

Throughout this course, you have built agentic applications by defining state schemas, registering nodes, connecting edges, and compiling graphs. This approach provides explicit control over complex workflows.

However, production applications frequently contain orchestration logic that already exists as ordinary Python functions.

Consider a research assistant that retrieves documents, generates a report, requests human approval, and publishes the approved result. Its logic might naturally be expressed using function calls, conditional statements, and loops.

Ordinary Python can implement this workflow, but several engineering challenges emerge:

  • What happens when the application crashes after generating an expensive report?
  • How can execution pause for human approval without keeping a server request open?
  • How can independent retrieval operations run concurrently?
  • How can the frontend receive progress updates and generated tokens?
  • How can information survive between successive invocations?

LangGraph’s Functional API addresses these requirements without forcing you to describe every operation as an explicit graph node and edge.

It introduces two decorators:

  • @entrypoint establishes a managed workflow.
  • @task identifies an individual operation within that workflow.

Both the Functional API and Graph API execute on LangGraph’s underlying runtime. They are different programming interfaces rather than independent execution engines.

In the previous lesson, you built a real-time streaming assistant. Here, you will apply those streaming capabilities to imperative Python workflows while introducing durable execution, replay, and thread-scoped memory.

Environment setup

Use Python 3.11 or later and install the following packages:

Terminal
python -m pip install -U "langgraph>=1.2,<2" "langchain>=1,<2" langchain-openai

For examples involving an OpenAI model, configure your API key:

Terminal
export OPENAI_API_KEY="your-api-key"

Most examples use deterministic mock operations, allowing you to understand workflow behavior without consuming LLM tokens.

Note: This lesson targets the late-2026 LangGraph 1.x API, including v2 streaming and v3 event streaming. Examples have been checked against the current API documentation but have not been execution-tested in the authoring environment.

The building blocks

Understanding @entrypoint

An entrypoint defines the public execution boundary of a functional workflow.

When Python applies the @entrypoint() decorator, LangGraph creates a managed workflow object backed by its Pregel runtime. Instead of calling the original function directly, you interact with this object through methods such as invoke(), ainvoke(), stream(), and astream().

An entrypoint accepts one positional workflow input. Multiple business inputs should therefore be grouped into a dictionary or another supported input structure.

The following example demonstrates a simple order-processing workflow.

Python
from langgraph.func import entrypoint

@entrypoint()
def calculate_order(order: dict) -> dict:
    subtotal = order["price"] * order["quantity"]
    tax = round(subtotal * 0.18, 2)

    return {
        "subtotal": subtotal,
        "tax": tax,
        "total": round(subtotal + tax, 2)
    }

result = calculate_order.invoke({
    "price": 100,
    "quantity": 3
})

print(result)

Expected output:

Text
{'subtotal': 300, 'tax': 54.0, 'total': 354.0}

Although the calculation remains ordinary Python, the decorated function now participates in LangGraph execution.

This workflow does not configure a checkpointer, so it has no durable thread history or resumable task results.

Understanding @task

A task represents an operation scheduled by LangGraph.

Unlike an ordinary function call, calling a decorated task returns a future-like object. The caller obtains the actual result through .result() in synchronous code or await in asynchronous code.

Tasks are particularly useful for:

  • External API requests and database queries.
  • LLM invocations.
  • Expensive computations.
  • Operations involving randomness or timestamps.
  • External writes and other side effects.

A task must execute within a managed LangGraph execution context, such as an entrypoint, another task, or a Graph API node.

The following workflow separates document retrieval from response generation.

Python
from langgraph.func import entrypoint, task

@task
def retrieve_document(topic: str) -> str:
    print("Retrieving document...")
    return f"{topic} supports durable agent workflows."

@task
def generate_answer(document: str) -> str:
    return f"According to the document: {document}"

@entrypoint()
def assistant(topic: str) -> str:
    document = retrieve_document(topic).result()
    answer = generate_answer(document).result()
    return answer

print(assistant.invoke("LangGraph"))

Expected output:

Text
Retrieving document...
According to the document: LangGraph supports durable agent workflows.

The first task must finish before the second can begin because answer generation depends on the retrieved document.

The following diagram illustrates this dependency.

The building blocks diagram: START to Entrypoint; Entrypoint to Retrieve document; Retrieve document to Generate answer; Generate answer to Return output; Return output to END.

Tasks versus ordinary functions

Not every function needs to become a task.

Characteristic Ordinary function LangGraph task
Invocation Direct call Managed scheduling
Return value Immediate result Future-like object
Concurrent scheduling Manually implemented Supported by runtime
Individual checkpointed result No Yes, with persistence
Task-level retry policy No built-in policy Supported
Best use Lightweight deterministic logic Significant workflow operations

Formatting strings, validating simple values, and performing inexpensive arithmetic can remain ordinary functions.

Decorating every trivial operation introduces unnecessary scheduling and serialization overhead.

A useful design principle is to establish task boundaries around operations that are expensive, nondeterministic, independently observable, or capable of failing.

How execution works internally

When an entrypoint runs, LangGraph establishes an execution context. Decorated task calls use this context to register and schedule work.

The entrypoint coordinates dependencies by deciding when to wait for task results.

When persistence is configured, the runtime can associate completed task results with the current execution and record them through the checkpointer. During replay, recorded results can replace fresh task execution.

The entrypoint’s local variables are not preserved as a suspended Python stack frame. Instead, they are reconstructed by rerunning the function and retrieving previously completed results.

This distinction becomes essential when implementing interrupts and recovery.

For the current signatures and execution contracts, consult the Functional API reference.

Runtime context

Functional workflows can also access run-scoped application dependencies without storing them in checkpointed workflow inputs.

The context_schema argument defines this context, and Runtime provides access inside the entrypoint.

The following example supplies a user’s preferred language at invocation time.

Python
from dataclasses import dataclass
from langgraph.func import entrypoint
from langgraph.runtime import Runtime

@dataclass
class Context:
    user_id: str
    language: str

@entrypoint(context_schema=Context)
def personalized_reply(
    name: str,
    *,
    runtime: Runtime[Context]
) -> str:
    if runtime.context.language == "es":
        return f"Hola, {name}!"

    return f"Hello, {name}!"

result = personalized_reply.invoke(
    "Alex",
    context=Context(
        user_id="user-101",
        language="es"
    )
)

print(result)

Expected output:

Text
Hola, Alex!

Runtime context is appropriate for request-scoped settings and dependencies. It is different from checkpointed memory, and applications should supply the necessary context again when resuming a workflow.

Parallel tasks

Sequential execution is necessary when operations depend on earlier results. However, independent operations can overlap to reduce latency.

Imagine an assistant that retrieves product information, customer history, and inventory availability from three different services.

Executing these calls sequentially wastes time whenever one service is waiting for network I/O.

Synchronous concurrent execution

To execute independent synchronous tasks concurrently, schedule them before resolving their futures.

The following example simulates three independent service requests.

Python
import time
from langgraph.func import entrypoint, task

@task
def fetch_service(service: str) -> dict:
    time.sleep(1)

    return {
        "service": service,
        "status": "available"
    }

@entrypoint()
def gather_information(services: list[str]) -> list[dict]:
    futures = [
        fetch_service(service)
        for service in services
    ]

    return [future.result() for future in futures]

start = time.perf_counter()

result = gather_information.invoke([
    "products",
    "customers",
    "inventory"
])

print(result)
print(f"Elapsed: {time.perf_counter() - start:.2f}s")

Expected output:

Text
[
    {'service': 'products', 'status': 'available'},
    {'service': 'customers', 'status': 'available'},
    {'service': 'inventory', 'status': 'available'}
]
Elapsed: 1.02s

The elapsed time is illustrative. Actual performance depends on executor capacity, machine resources, and runtime overhead.

With sufficient concurrency, three one-second I/O operations should finish in approximately one second rather than three.

Compare the scheduling patterns:

Python
results = [fetch_service(s).result() for s in services]

futures = [fetch_service(s) for s in services]
results = [future.result() for future in futures]

These snippets belong inside a managed workflow.

The order in which results are collected does not determine the order in which tasks finish. The futures allow each scheduled operation to progress independently.

Asynchronous concurrent execution

For applications built with asynchronous HTTP clients, databases, or LLM providers, asynchronous tasks are often preferable.

Use async def, await task results, and invoke the entrypoint using ainvoke().

The following example concurrently retrieves information from simulated knowledge sources.

Python
import asyncio
import time
from langgraph.func import entrypoint, task

@task
async def search_source(source: str, query: str) -> dict:
    await asyncio.sleep(1)

    return {
        "source": source,
        "content": f"{source} information about {query}"
    }

@entrypoint()
async def research(query: str) -> list[dict]:
    futures = [
        search_source("documentation", query),
        search_source("knowledge_base", query),
        search_source("database", query)
    ]

    return await asyncio.gather(*futures)

async def main():
    start = time.perf_counter()

    results = await research.ainvoke("LangGraph")

    for result in results:
        print(result)

    print(f"Elapsed: {time.perf_counter() - start:.2f}s")

if __name__ == "__main__":
    asyncio.run(main())

All three operations overlap, and asyncio.gather() collects their results in submission order.

Avoid blocking an asynchronous task using time.sleep() or synchronous network clients. Use asynchronous libraries or explicitly offload blocking operations.

Fan-out and fan-in

The preceding examples demonstrate the fan-out/fan-in pattern.

An entrypoint distributes work to independent tasks and then combines their outputs.

An entrypoint distributes work to independent tasks and then combines their outputs.

This pattern appears frequently in multi-agent research, document processing, retrieval-augmented generation, and batch classification.

Concurrency does not guarantee faster CPU-intensive Python execution. It primarily improves workloads dominated by waiting.

In production, also consider provider rate limits, connection pool capacity, memory consumption, and retry amplification. Process large collections in bounded batches rather than scheduling thousands of external requests simultaneously.

Interrupts and resuming

Adding persistence

Durable execution requires a checkpointer.

In the Functional API, configure it directly on the entrypoint rather than passing it to StateGraph.compile().

Every persisted workflow must have a thread identifier that allows LangGraph to locate its execution history.

Python
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint

checkpointer = InMemorySaver()

@entrypoint(checkpointer=checkpointer)
def workflow(value: int) -> int:
    return value * 2

config = {
    "configurable": {
        "thread_id": "workflow-001"
    }
}

print(workflow.invoke(10, config))

Expected output: 20.

InMemorySaver is suitable for development and testing. Its contents do not survive process termination.

For durable production execution, use an appropriate database-backed checkpointer, such as PostgresSaver or AsyncPostgresSaver, initialize its schema with setup(), and manage its connection lifecycle correctly.

Human-in-the-loop execution

The interrupt() function allows workflows to pause and request external input.

When execution encounters an interrupt, LangGraph records the pending interruption and returns control to the caller.

A later invocation supplies the response using Command(resume=...).

The following example implements a support-response approval workflow.

Python
from langgraph.func import entrypoint, task
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

checkpointer = InMemorySaver()

@task
def generate_response(question: str) -> str:
    print("Generating response...")
    return f"We are investigating your request: {question}"

@task
def send_response(response: str) -> str:
    print("Simulating response delivery...")
    return f"Sent: {response}"

@entrypoint(checkpointer=checkpointer)
def support_workflow(question: str) -> dict:
    response = generate_response(question).result()

    approved = interrupt({
        "question": "Approve this response?",
        "draft": response
    })

    if approved is not True:
        return {"status": "rejected"}

    receipt = send_response(response).result()

    return {
        "status": "approved",
        "receipt": receipt
    }

config = {
    "configurable": {
        "thread_id": "support-001"
    }
}

paused = support_workflow.invoke(
    "Where is my order?",
    config,
    version="v2"
)

print(paused.interrupts[0].value)

completed = support_workflow.invoke(
    Command(resume=True),
    config,
    version="v2"
)

print(completed.value)

Expected output:

Text
Generating response...
{'question': 'Approve this response?', 'draft': 'We are investigating your request: Where is my order?'}
Simulating response delivery...
{'status': 'approved', 'receipt': 'Sent: We are investigating your request: Where is my order?'}

With the default v1 invocation format, interrupts in dictionary-shaped graph results are exposed through result["__interrupt__"]. Using version="v2" provides the more explicit .interrupts and .value attributes, including for functional workflows.

Understanding replay

Notice that Generating response... appears only once.

When the workflow resumes, execution begins again at the top of the entrypoint. However, LangGraph restores the completed generate_response task result instead of calling its implementation again.

The runtime then reaches interrupt() and supplies the previously submitted approval value.

This makes it possible to reconstruct workflow execution without repeating successfully recorded expensive operations.

The same replay principle applies to recovery after failures. When an execution fails, invoking the workflow with None and the same thread configuration can resume it from persisted progress.

Side effects and idempotency

A task boundary is not an exactly-once execution guarantee.

Consider a payment task that successfully charges a customer but crashes before its result is checkpointed. LangGraph may execute that task again during recovery.

An idempotent operation produces the same intended effect when repeated.

For external writes, use stable operation identifiers, database uniqueness constraints, provider-supported idempotency keys, or transactional outbox patterns.

Keep nondeterministic operations, such as UUID generation, timestamp retrieval, and LLM calls, inside tasks when their results affect replayed control flow.

Tip: Replay must encounter compatible task and interrupt sequences. Avoid changing the order of interrupts or making replayed branches depend on unrecorded randomness, mutable global state, or the current time.

Also avoid broad exception handlers around interrupt(), because interruption relies on an internal control-flow exception.

LangGraph supports configurable persistence durability through durability="sync", "async", or "exit". Stronger persistence boundaries reduce potential lost progress, while asynchronous persistence can improve throughput. None eliminates the need for idempotent external writes.

See the interrupt documentation for additional resume and validation rules.

Short-term memory

Interrupt persistence preserves progress within an unfinished workflow. Short-term memory preserves information between completed invocations on the same thread.

The Functional API exposes previous saved information through an injected parameter named previous.

Using previous

By default, the value returned by an entrypoint becomes available as previous during its next invocation on the same thread.

The following example implements a persistent accumulator.

Python
from langgraph.func import entrypoint
from langgraph.checkpoint.memory import InMemorySaver

@entrypoint(checkpointer=InMemorySaver())
def accumulate(
    amount: int,
    *,
    previous: int | None = None
) -> int:
    return (previous or 0) + amount

config = {
    "configurable": {"thread_id": "account-001"}
}

print(accumulate.invoke(10, config))
print(accumulate.invoke(20, config))
print(accumulate.invoke(5, config))

other_config = {
    "configurable": {"thread_id": "account-002"}
}

print(accumulate.invoke(7, other_config))

Expected output:

Text
10
30
35
7

Each thread maintains independent memory.

The previous parameter is initially None. It subsequently contains the last saved entrypoint value for that thread.

Separating output from saved memory

An assistant normally needs to return a user-facing answer while retaining additional information for future interactions.

Returning the entire conversation history on every invocation is unnecessary.

Use entrypoint.final(value=..., save=...) to separate the public output from the memory stored for subsequent invocations.

The following example remembers facts provided by a user.

Python
from langgraph.func import entrypoint
from langgraph.checkpoint.memory import InMemorySaver

@entrypoint(checkpointer=InMemorySaver())
def remember_fact(
    inputs: dict,
    *,
    previous: dict | None = None
) -> entrypoint.final[str, dict]:

    memory = dict(previous or {})

    if inputs["action"] == "remember":
        memory[inputs["key"]] = inputs["value"]
        answer = "Fact remembered."
    else:
        answer = memory.get(
            inputs["key"],
            "I do not remember that."
        )

    return entrypoint.final(
        value=answer,
        save=memory
    )

config = {
    "configurable": {"thread_id": "user-001"}
}

print(remember_fact.invoke({
    "action": "remember",
    "key": "favorite_language",
    "value": "Python"
}, config))

print(remember_fact.invoke({
    "action": "recall",
    "key": "favorite_language"
}, config))

Expected output:

Text
Fact remembered.
Python

The first invocation returns a confirmation string but saves a dictionary. The second receives that dictionary through previous.

For conversational assistants, the saved value could contain message history, a conversation summary, preferences, or recently retrieved facts.

Keep memory bounded. Unrestricted accumulation increases checkpoint size and, when passed into an LLM, token consumption.

Thread-scoped memory is also not equivalent to long-term memory. Information shared across multiple threads should generally reside in a LangGraph store, accessed through runtime.store.

Streaming functional workflows

The streaming interfaces introduced earlier in this chapter are also available on functional entrypoints.

The most useful streaming modes are:

Mode Functional API behavior
updates Reports completed task and entrypoint outputs
values Exposes the workflow’s final output rather than a shared state after every task
messages Streams LLM message chunks and metadata
custom Emits application-defined progress events
tasks Reports task lifecycle events

Combining token streaming and custom progress

The following example extends the previous streaming assistant project using an asynchronous functional workflow.

It emits retrieval progress, streams generated tokens, and reports completed task outputs.

Python
import asyncio
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.func import entrypoint, task
from langgraph.config import get_stream_writer

model = init_chat_model("openai:gpt-5.4-mini")

@task
async def retrieve_context(question: str) -> str:
    writer = get_stream_writer()
    writer({"stage": "retrieval_started"})

    await asyncio.sleep(0.5)

    context = (
        "LangGraph supports checkpointing, "
        "interrupts, and durable execution."
    )

    writer({"stage": "retrieval_completed"})
    return context

@task
async def answer_question(
    question: str,
    context: str
) -> str:
    response = await model.ainvoke([
        SystemMessage(
            content=f"Answer using this context: {context}"
        ),
        HumanMessage(content=question)
    ])

    return response.text

@entrypoint()
async def streaming_assistant(question: str) -> str:
    context = await retrieve_context(question)
    return await answer_question(question, context)

async def main():
    async for chunk in streaming_assistant.astream(
        "What is durable execution?",
        stream_mode=["updates", "messages", "custom"],
        version="v2"
    ):
        if chunk["type"] == "custom":
            print("\nProgress:", chunk["data"])

        elif chunk["type"] == "messages":
            message, metadata = chunk["data"]
            print(message.text, end="", flush=True)

        elif chunk["type"] == "updates":
            print("\nCompleted:", list(chunk["data"]))

if __name__ == "__main__":
    asyncio.run(main())

Illustrative output:

Text
Progress: {'stage': 'retrieval_started'}

Progress: {'stage': 'retrieval_completed'}

Completed: ['retrieve_context']

Durable execution allows a workflow to preserve its
progress and resume after an interruption or failure.

Completed: ['answer_question']

Completed: ['streaming_assistant']

Generated text and event ordering can vary.

Although the model uses ainvoke(), LangGraph’s message streaming integration can surface generated chunks while the model call is executing.

Event streaming

The newer event streaming interface offers higher-level projections over execution events.

For example, a synchronous entrypoint can expose model text through stream.messages while making its final output available through stream.output.

This complete example demonstrates the interface.

Python
from langchain.chat_models import init_chat_model
from langgraph.func import entrypoint, task

model = init_chat_model("openai:gpt-5.4-mini")

@task
def generate(question: str) -> str:
    return model.invoke(question).text

@entrypoint()
def assistant(question: str) -> str:
    return generate(question).result()

stream = assistant.stream_events(
    "Explain checkpointing in one sentence.",
    version="v3"
)

for message in stream.messages:
    for token in message.text:
        print(token, end="", flush=True)

print("\nFinal output:", stream.output)

The generated answer appears progressively, followed by the completed output. Other projections include stream.values for value snapshots and stream.interrupts for pending human-input requests.

See the event streaming documentation for the projection interfaces.

Remember that streamed progress events are observations, not durable business records. Clients reconnecting after a failure should reconcile their display with persisted workflow status rather than assuming every prior event will be delivered again.

Graph API vs Functional API

Both APIs support sophisticated agentic applications, but their programming models emphasize different engineering concerns.

Dimension Graph API Functional API
Workflow definition Explicit nodes and edges Decorated Python functions
Control flow Edges, conditional edges, Command Python conditions, loops, and calls
State management Shared state schema and reducers Local variables, task outputs, previous
Parallelism Parallel branches and Send Concurrent task futures
Compilation StateGraph.compile() Entrypoint decoration
Persistence Graph super-step checkpoints Entrypoint checkpoints and task results
Resume behavior Replay from graph execution boundaries Replay entrypoint control flow
Visualization Explicit graph topology No equivalent static workflow topology
Typical use Complex stateful agents Imperative workflows and existing applications

Choosing the right API

Prefer the Graph API when building new agents that require explicit state transitions, complex routing, reusable subgraphs, or clearly visualized execution topology.

Prefer the Functional API when integrating LangGraph capabilities into existing Python orchestration code, implementing naturally imperative workflows, or wrapping applications built with other agent frameworks.

These approaches can coexist. For example, a Graph API node can invoke a decorated functional task, while an entrypoint can invoke a compiled graph as part of a larger workflow.

This allows teams to adopt durable orchestration incrementally without rewriting an entire application.

Production engineering considerations

Functional workflows remain subject to normal distributed-system constraints.

Design stable task boundaries, validate external inputs, and use serializable data structures for checkpointed values. Avoid passing open connections, futures, generators, or other process-local objects as durable workflow data.

Bound Python loops explicitly. LangGraph’s recursion limit is not a substitute for application-level termination conditions inside an imperative entrypoint.

Protect thread identifiers through application-level authorization, avoid storing secrets in checkpointed inputs, and prevent overlapping mutations of the same thread unless your execution architecture explicitly coordinates them.

Finally, test interruption, rejection, successful completion, duplicate requests, dependency failures, and recovery after process termination using the same durable checkpointer.

The next lesson, Retry policies, backoff and timeouts, extends these foundations by controlling how individual operations respond to transient failures. Task boundaries introduced here provide a natural place to configure those policies, particularly for unreliable external APIs, asynchronous services, and LLM requests.

Exercise

Build a Resumable Document Approval Workflow

Build a Functional API workflow that generates a document and calculates its word count before requesting human approval. Persist completed task results using a checkpointer so that document generation is not repeated when execution resumes. Publish the document through a simulated publishing task only when approval is granted, and verify both approval and rejection paths.

Python
from langgraph.func import entrypoint, task
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command
from langgraph.config import get_stream_writer

checkpointer = InMemorySaver()

@task
def generate_document(topic: str) -> str:
    # TODO: Generate a sample document.
    raise NotImplementedError

@task
def count_words(document: str) -> int:
    # TODO: Calculate the word count.
    raise NotImplementedError

@task
def publish_document(document: str) -> str:
    # TODO: Simulate publishing the document.
    raise NotImplementedError

@entrypoint(checkpointer=checkpointer)
def approval_workflow(topic: str) -> dict:
    # TODO: Generate the document.
    # TODO: Calculate its word count.
    # TODO: Request human approval using interrupt().
    # TODO: Publish only when approved.
    raise NotImplementedError

config = {"configurable": {"thread_id": "document-001"}}

# TODO: Invoke the workflow.
# TODO: Inspect the interrupt payload.
# TODO: Resume with Command(resume=True).
# TODO: Test rejection using another thread.

Summary

  • The Functional API adds LangGraph runtime capabilities to workflows expressed through ordinary Python control flow.
  • The entrypoint decorator defines the workflow boundary and exposes invocation, streaming, and persistence interfaces.
  • The task decorator creates independently scheduled units of work whose completed results can be restored during replay.
  • Independent tasks execute concurrently when scheduled before waiting for their results.
  • Interrupts suspend execution durably and resume by replaying the entrypoint with previously recorded task results.
  • The previous parameter and entrypoint.final support thread-scoped memory across successive invocations.
  • The Graph API favors explicit state and topology, while the Functional API favors imperative orchestration and integration with existing Python applications.