| Name | Type | Description |
|---|---|---|
name | str | None | Default: NoneAn optional name for the task. If not provided, the function name will be used. |
retry_policy | RetryPolicy | Sequence[RetryPolicy] | None | Default: NoneAn optional retry policy (or list of policies) to use for the task in case of a failure. |
cache_policy | CachePolicy[Callable[P, str | bytes]] | None | Default: None |
timeout | float | timedelta | TimeoutPolicy | None | Default: None |
Define a LangGraph task using the task decorator.
The task decorator supports both sync and async functions. To use async
functions, ensure that you are using Python 3.11 or higher.
Tasks can only be called from within an entrypoint or
from within a StateGraph. A task can be called like a regular function with the
following differences:
StateGraph.Sync Task:
from langgraph.func import entrypoint, task
@task
def add_one_task(a: int) -> int:
return a + 1
@entrypoint()
def add_one(numbers: list[int]) -> list[int]:
futures = [add_one_task(n) for n in numbers]
results = [f.result() for f in futures]
return results
# Call the entrypoint
add_one.invoke([1, 2, 3]) # Returns [2, 3, 4]
Async Task:
import asyncio
from langgraph.func import entrypoint, task
@task
async def add_one_task(a: int) -> int:
return a + 1
@entrypoint()
async def add_one(numbers: list[int]) -> list[int]:
futures = [add_one_task(n) for n in numbers]
return asyncio.gather(*futures)
# Call the entrypoint
await add_one.ainvoke([1, 2, 3]) # Returns [2, 3, 4]An optional cache policy to use for the task. This allows caching of the task results.
Timeout for each task attempt. A number or timedelta is a hard
wall-clock cap and is not refreshed. Use TimeoutPolicy to configure
both a wall-clock run_timeout and an idle_timeout refreshed by
progress signals. For long-running work that doesn't naturally emit
progress, call runtime.heartbeat() from inside the task. When the
timeout fires, NodeTimeoutError is raised and the retry policy (if
any) decides whether to retry. Supported only for async tasks; sync
tasks cannot be safely cancelled in-process.