Skip to content

Tasks

Model runs and standalone work share the task lifecycle: TaskStarted, optional TaskProgress, and one terminal event — TaskCompleted, TaskFailed, TaskExpired, or TaskCancelled. Observers, network mirrors, and UIs consume the same events in each case.

Model Runs#

Pass capability or ttl_seconds to enable lifecycle events for an agent invocation:

from ag2 import Agent
from ag2.config import OpenAIResponsesConfig

agent = Agent("researcher", config=OpenAIResponsesConfig(model="gpt-5"))

reply = await agent.ask(
    "Research deployment patterns",
    capability="research",
    ttl_seconds=60,
)

capability tags the work for network observations. The task title (TaskStarted.objective) is the agent's name, never the prompt, because task events are mirrored to the network hub; a delegation uses its objective. ttl_seconds carries an absolute expiry deadline on TaskStarted; an external observer owns expiry. It does not set a local execution timeout. Omitting both options leaves ordinary runs without task lifecycle events.

The observable form accepts the same options:

from ag2 import Agent
from ag2.config import OpenAIResponsesConfig
from ag2.events import TaskCompleted, TaskStarted

agent = Agent("researcher", config=OpenAIResponsesConfig(model="gpt-5"))

def show_task(event):
    print(type(event).__name__, event.task_id)

async with agent.run("Research deployment patterns", capability="research") as run:
    run.stream.where(TaskStarted | TaskCompleted).subscribe(show_task, sync_to_thread=False)
    reply = await run.result()

Entering run opens the scope. TaskStarted is emitted when start() or result() drives it; leaving an undriven run emits no task events. Repeated result() calls share one invocation and one lifecycle. The terminal is emitted after middleware and observer cleanup when the run scope closes. ask() completes that cleanup before it returns. Subscribe directly to the stream to observe the terminal after run-scoped observers have been released.

A model or tool exception produces TaskFailed and propagates to the caller. Cancelling the turn or leaving a running scope produces TaskCancelled after running tools and descendants have settled. Setup errors produce a start/failure pair even if the model never runs. Cleanup errors, including a storage failure while usage is recorded, produce a failure terminal and propagate to the caller; cleanup cancellation produces TaskCancelled. Before publishing its terminal, an opted-in run waits for delegations it left running in the background, so ask() returns once they have settled.

Waiting for a shared stream's turn lock happens before the run scope opens. Cancelling an ordinary invocation during that wait emits no task events. A delegation also reports a rejected attempt to its parent as a start/cancellation pair, using the same lifecycle transitions without entering the busy stream.

AgentReply.ask(), AgentReply.run(), and Agent.resume() accept the same options. Each continuation gets a fresh task identity when opted in; capability and TTL are supplied per invocation. Recovery of model work uses the recorded trajectory and resume().

Delegations through Agent.as_tool() use this lifecycle automatically, with the delegation's task ID and parent tool-call ID. Ancestors receive the same events with their source path, without duplicate starts or terminals. See Subagents.

Standalone Work#

Construct Task directly for arbitrary coroutines outside the model loop. Tasks are owner-driven; the framework does not assign or schedule them.

When to Use a Standalone Task#

Use a Task whenever a unit of work has a beginning, an end, and observable progress that you want to surface beyond your own function's return value:

  • Long-running pipelines where downstream consumers want progress checkpoints.
  • HITL approvals where a UI needs to know the task is waiting on a human.
  • Test harnesses that assert a sequence of lifecycle events.

Standalone Example#

from ag2 import Agent
from ag2.task import Task, TaskSpec

agent = Agent("indexer")

async with Task(owner_id=agent.name, spec=TaskSpec(title="index documents")) as task:
    await task.progress({"stage": "discover", "files": 12})
    await task.progress({"stage": "index", "indexed": 12})
    await task.complete({"indexed": 12})

print(task.state)        # TaskState.COMPLETED
print(task.metadata.result)  # {'indexed': 12}

The async with block opens the lifecycle. On clean exit the task auto-completes with result=None if you didn't call complete() or fail() yourself.

Lifecycle States#

CREATED -> RUNNING -> COMPLETED   (terminal, success)
                   -> FAILED      (terminal, exception or explicit fail)
                   -> EXPIRED     (terminal, externally observed expiry)
                   -> CANCELLED   (terminal, explicit or coroutine cancellation)
State Meaning
CREATED The Task object exists but __aenter__ has not run. task.task_id and task.metadata raise.
RUNNING Inside the async with block. Progress events allowed.
COMPLETED Reached complete() or clean block exit.
FAILED Reached fail() or block exited via exception.
EXPIRED An external observer marked the task expired.
CANCELLED Reached cancel() or the coroutine exited with asyncio.CancelledError.

The terminal states are immutable — once set, further complete() / fail() / progress() calls are silent no-ops. The set is exported as ag2.task.TERMINAL_TASK_STATES.

API Reference#

Task(...)#

from ag2.task import CheckpointStore, Task, TaskSpec

Task(
    owner_id=agent.name,
    spec=TaskSpec(
        title="index documents",
        description="",
        payload={},
        capability=None,
    ),
    context=None,
    ttl_seconds=None,
    checkpoint_store=None,
    resume_from=None,
)
Parameter Type Description
owner_id str Owner identity included in lifecycle events; use agent.name for agent-owned work.
spec TaskSpec Title, description, payload and optional capability tag.
context ConversationContext \| None Events flow on context.stream; TaskInject resolves to this Task for the duration of the block. If omitted, the Task creates a private MemoryStream on entry.
ttl_seconds int \| None Sets metadata.expires_at; an external observer owns expiry.
checkpoint_store CheckpointStore \| None Store for owner-defined checkpoint state.
resume_from str \| None Prior task ID whose checkpoint is loaded into task.resumed_state on entry.

Returns an unentered Task. Construction does not start work or emit events.

TaskSpec describes the work:

Field Type Default Description
title str Required Short objective shown on every event.
description str "" Longer description.
payload dict[str, Any] Fresh {} Owner-defined task data.
capability str \| None None Capability name used by network mirrors.

Task instance methods#

Method Description
await task.progress(payload) Emits TaskProgress; merges payload into metadata.progress and stamps last_progress_at. No-op if already terminal.
await task.complete(result=None) Terminal. Emits TaskCompleted; sets metadata.result and state = COMPLETED.
await task.fail(error) Terminal. Accepts a string (wrapped in RuntimeError) or any BaseException. Emits TaskFailed; sets state = FAILED.
await task.cancel(reason="") Terminal. Emits TaskCancelled; sets state = CANCELLED.
await task.checkpoint(state) Persists owner-defined recovery state through the configured store.
await task.expire() Terminal. Emits TaskExpired; sets state = EXPIRED. Called by external TTL observers.

Properties#

Property Available before __aenter__?
task.state Yes — returns TaskState.CREATED.
task.task_id No — raises RuntimeError.
task.metadata No — raises RuntimeError.
task.context No — raises RuntimeError.

Bound Context vs. Standalone#

1
2
3
4
5
6
7
from ag2.context import ConversationContext
from ag2.stream import MemoryStream

ctx = ConversationContext(stream=MemoryStream())

async with Task(owner_id=agent.name, spec=TaskSpec(title="with-ctx"), context=ctx) as task:
    ...

Passing a ConversationContext shares the stream with the rest of your agent's run, so observers and middleware already attached to that stream see the lifecycle events.

Without a context, the Task creates a private stream on entry. Events still fire — but only observers attached to that private stream see them. Useful for one-off background work that doesn't need to surface anywhere.

Auto-Complete and Auto-Fail#

The async with block has these guarantees:

  • Clean exit, no terminal call -> auto complete(result=None).
  • Exception inside the block -> auto fail(exc), then the exception propagates.
  • Coroutine cancellation -> auto cancel("cancelled"), then cancellation propagates.
  • Already terminal at exit time -> nothing further happens.
1
2
3
4
5
6
try:
    async with Task(owner_id=agent.name, spec=TaskSpec(title="flaky")) as task:
        raise ValueError("boom")
except ValueError as exc:
    print(task.state)            # TaskState.FAILED
    print(task.metadata.error)   # 'boom'

Observing the Lifecycle#

Subscribe directly on the bound stream to capture every lifecycle event in order.

from ag2.events import TaskCompleted, TaskProgress, TaskStarted

stream = MemoryStream()
ctx = ConversationContext(stream=stream)

stream.subscribe(
    lambda ev: print(type(ev).__name__, getattr(ev, "payload", "")),
    sync_to_thread=False,
)

async with Task(owner_id=agent.name, spec=TaskSpec(title="watched"), context=ctx) as task:
    await task.progress({"step": "fetch"})
    await task.complete({"ok": True})

Note

TaskProgress is marked transient — it is delivered live to subscribers but not persisted to the stream's storage. Subscribe before the events fire to capture them. TaskStarted, TaskCompleted, TaskFailed, and TaskExpired are persisted normally.

Reading the Active Task with TaskInject#

Model runs do not inject a standalone Task or replace one supplied by an enclosing block. Use context variables for model-run state.

Code running inside an async with Task(...) block can reach the task without having it passed around: annotate a parameter with TaskInject and the framework injects the task whose block encloses the call.

TaskInject annotation#

TaskInject is a fast_depends-resolvable annotation that injects the enclosing task into any function the dependency-injection machinery resolves — most usefully a @tool body.

1
2
3
4
5
6
7
8
from ag2 import TaskInject, tool

@tool
async def report(message: str, task: TaskInject) -> str:
    if task is None:
        return "no active task"
    await task.progress({"tool_message": message})
    return f"reported on task {task.task_id}"

TaskInject resolves to None when no task encloses the call, so always null-check before use.

Which task a tool sees#

Open the block on the stream the agent's turn runs on, and the turn's tools report to that task:

from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.context import ConversationContext
from ag2.stream import MemoryStream
from ag2.task import Task, TaskSpec

agent = Agent("worker", config=AnthropicConfig(model="claude-sonnet-5"), tools=[report])
ctx = ConversationContext(stream=MemoryStream())
async with Task(owner_id=agent.name, spec=TaskSpec(title="work"), context=ctx):
    await agent.ask("Report progress.", stream=ctx.stream)
  • Parallel tool calls. When several calls in one model response each open their own task — for example from tool middleware that wraps every call in Task(...) — each call resolves its own task, whatever the others do.
  • Nested blocks. A nested block resolves to the innermost enclosing task; once it exits, the outer task again.
  • Other conversations. A turn on a different stream started inside the block does not see the task. That includes subagents (as_tool): a delegation runs on its own stream and is its own task scope.
  • Outside the block. Code the block does not enclose — after it exits, or a handler or background task started before it — resolves None, not some other task.

Outside any block, a task you pass yourself as the "ag2.task" dependency is injected — handy for testing a tool on its own:

async with Task(owner_id=agent.name, spec=TaskSpec(title="given")) as task:
    await agent.ask("Report progress.", dependencies={"ag2.task": task})

Direct access#

For direct readers of the dict, context.dependencies["ag2.task"] also holds a task for the duration of the block:

1
2
3
async with Task(owner_id=agent.name, spec=TaskSpec(title="work"), context=ctx) as task:
    active = ctx.dependencies["ag2.task"]
    assert active is task

The slot is best-effort when tasks overlap: with parallel tool calls each opening a task on one conversation, it can only name the most recently entered task still running. Prefer TaskInject, which does not read the slot a block stamped.

TTL and Expiry#

Setting ttl_seconds=N populates metadata.expires_at but does not start a timer. The Task primitive itself never self-expires — that's by design, so a standalone Task with no observer doesn't spawn a background task. Instead, an external observer (e.g. a network hub's TTL sweeper, a periodic watch) checks expires_at and calls task.expire() when due.

For self-contained TTL behaviour, wire up a sweeper in your application:

1
2
3
4
5
6
async def sweep(task: Task, deadline: datetime) -> None:
    while task.state == TaskState.RUNNING:
        if datetime.now(timezone.utc) >= deadline:
            await task.expire()
            return
        await asyncio.sleep(1.0)

Checkpoint and Recovery#

Pass a checkpoint_store to persist owner-defined state with await task.checkpoint(state). To continue that work, construct a new Task with the same store and resume_from set to the prior task ID. On entry, task.resumed_state contains the saved state, or None if no checkpoint is available. The application decides how to continue from that state.

from ag2.task import Task, TaskSpec

async with Task(
    owner_id=agent.name,
    spec=TaskSpec(title="index documents", capability="indexing"),
    context=ctx,
    checkpoint_store=store,
    resume_from=prior_task_id,
) as task:
    next_document = (task.resumed_state or {}).get("next_document", 0)
    await task.progress({"next_document": next_document})
    # Process the next batch, then save where to continue.
    await task.checkpoint({"next_document": next_document + 12})

Without a checkpoint store, checkpoint() is a no-op and resumed_state is None.

TaskSpec and TaskMetadata#

Two small dataclasses surface around a Task:

  • TaskSpec — what the task is doing: title, description, payload, optional capability. Passed to Task(spec=...).
  • TaskMetadata — mutable lifecycle record updated on each transition: task_id, owner_id, spec, state, ISO-8601 timestamps, progress, result, error, optional channel_id.
1
2
3
4
5
6
7
8
async with Task(
    owner_id=agent.name,
    spec=TaskSpec(title="survey", description="probe upstream", payload={"region": "us"}),
) as task:
    print(task.metadata.spec.title)        # 'survey'
    print(task.metadata.spec.payload)      # {'region': 'us'}
    print(task.metadata.owner_id)          # 'researcher'
    print(task.metadata.started_at)        # ISO 8601 string