Client API
Autonomous agents and tasks are managed through the ComponentClient. This page covers how to start agents, assign tasks, query results, and observe execution from the outside.
Running a single task
The simplest pattern: create a task, start an agent, and automatically stop the agent when done. runSingleTask handles all of this in one call.
var taskId = componentClient
.forAutonomousAgent(QuestionAnswerer.class, agentInstanceId)
.runSingleTask(QuestionTasks.ANSWER.instructions(request.question()));
This returns the task id for later status checks. Each call starts an independent agent instance.
runSingleTask only constrains how the work starts. It provides exactly one task to the agent. Once the agent is running, its capabilities can still create more tasks during the loop. A coordinator with a Delegation capability creates subtasks for its workers, and a team lead with TeamLeadership creates tasks in the team’s shared list. The agent stops automatically once its task queue is fully drained, including the original task and anything spawned along the way.
Managing tasks and agents separately
For more control over multiple tasks, pipelines, or long-lived agents, create tasks and assign them separately.
Create tasks:
var taskId = UUID.randomUUID().toString();
componentClient
.forTask(taskId)
.create(PipelineTasks.COLLECT.instructions("Collect data on: " + topic));
Creating a task with an id that already exists succeeds and returns that id, without an error. Akka discards the new definition, and the existing task keeps its name, description, instructions and result type. A caller that declares a different result type therefore gets the id of a task with the original result type. This makes it safe to repeat create with an id that you stored before the call, for example after a crash, but it also means that each id must belong to one task definition only.
Assign tasks to an agent:
componentClient
.forAutonomousAgent(ReportAgent.class, agentInstanceId)
.assignTasks(collectTaskId, analyzeTaskId, reportTaskId);
Tasks are queued if the agent is busy. A single agent instance processes one task at a time. Only one task is IN_PROGRESS, and the rest stay ASSIGNED until they reach the head of the queue and their dependencies are met. Parallelism comes from fanning out to other agent instances, not from a single agent running multiple tasks concurrently.
The maxParallelWorkers option on a Delegation capability (see Delegation) caps how many worker instances a coordinator can run in parallel. It does not change the single-task-at-a-time behavior of any one instance.
If the agent uses dynamic configuration, call setup(…) on the same forAutonomousAgent(…) chain before runSingleTask or assignTasks so the runtime applies the per-instance instructions and capabilities before iteration begins.
Terminate an agent:
componentClient.forAutonomousAgent(ReportAgent.class, agentInstanceId).terminate();
When you manage tasks and agents separately, you are responsible for the agent’s lifecycle. Call terminate() when an agent is permanently done. The runSingleTask shortcut handles this automatically. The explicit assignTasks flow does not. Idle agents are passivated automatically to release memory, and reactivates transparently on the next command (e.g. assignTask). An agent that holds access to a shared backlog stays resident rather than passivating, so it does not miss new claimable tasks pushed to it.
|
Termination is permanent for that instance id. A stopped agent instance rejects resume(), task assignment, and any other command with an error. To retry the work, start a new agent instance with a new instance id, do not reuse the old one. Terminating an agent does not apply any result its current iteration was still producing, so a task the agent was actively working on can be left IN_PROGRESS rather than reaching a terminal state. Because a task is a separate entity from the agent, an orphaned task can still be resolved directly, for example by calling fail(…) on it through forTask(…), independent of the terminated agent instance.
Task lifecycle operations
Beyond create and get, the forTask(…) client exposes the operations that drive a task through its lifecycle: assign, complete, and fail. The runtime calls these on the agent’s behalf as it picks up, completes, or fails tasks during iteration. Application code calls the same operations when an external actor (typically a human) drives a task that no agent is assigned to. See External input for the human-approval pattern that uses them end to end.
Assign a task to an owner:
componentClient.forTask(taskId).assign("[email protected]");
A task must be assigned before it can be completed or failed. The assignee is a free-form identifier (a user id, team name, or process identifier) that records who took ownership.
Complete a task with a typed result:
componentClient
.forTask(taskId)
.complete(PublishingTasks.APPROVAL, new ApprovalDecision("alice", "Looks good"));
The result is validated against the task definition’s result type. The task transitions to COMPLETED and any dependents become eligible to start.
Fail a task with a reason:
componentClient.forTask(taskId).fail("Approval rejected: tone is too informal");
The task transitions to FAILED. Any dependents are cancelled automatically.
Suspend and resume
A running agent can be suspended and later resumed. While suspended, the agent stops iterating: it will not start new model calls or process queued tasks. Tasks already assigned remain in the queue and are processed when the agent resumes.
Suspend takes effect at the next iteration boundary. A single iteration can include several model calls and tool-call rounds before it completes, and suspending during an iteration does not interrupt that iteration, it only prevents the next one from starting. If the current iteration reaches a result that satisfies the task, the task still completes normally even though the agent is suspended. To stop a task without waiting for its current iteration to finish, call terminate() instead.
// Suspend the agent
componentClient.forAutonomousAgent(ReportAgent.class, agentInstanceId).suspend();
// Resume the agent
componentClient.forAutonomousAgent(ReportAgent.class, agentInstanceId).resume();
Both suspend(…) and terminate(…) accept an optional reason string, recorded on the corresponding Suspended and Stopped notifications.
Sending a message to a running agent
Send a message to a running agent to add a constraint or to correct the course of the agent while it works on a task. The message is an AgentMessage: text with optional attachments. sendMessage returns a MessageAcknowledgement that says where the message went.
var acknowledgement = componentClient
.forAutonomousAgent(ReportAgent.class, agentInstanceId)
.sendMessage(
AgentMessage.of("Use the figures of the third quarter.").messageId(requestId)
);
switch (acknowledgement.status()) {
case MessageStatus.ForCurrentTask s -> log.info("For task {}", s.taskId());
case MessageStatus.Held s -> log.info(
"Held until {} starts",
s.taskId().orElse("the next task")
);
case MessageStatus.Consumed s -> log.info("Seen in {}", s.interactionId());
case MessageStatus.Dropped s -> log.info("Dropped, task {} ended", s.taskId());
case MessageStatus.Rejected s -> log.info("Rejected: {}", s.reason());
case MessageStatus.Unknown s -> log.warn("Status from a newer runtime");
}
A message is for one task of the agent:
-
With a task id, set with
taskId(…), the message is for that task. When the task is queued or waits for its dependencies, the agent holds the message until the task starts. -
Without a task id, the message is for the current task. When no task runs, the agent holds the message until the next task starts.
When the model sees a message
The model sees the message in its next request for the task of the message. That request is at the start of an iteration, or after the tool calls of a round when the model call continues. While a tool call runs, the message waits for it.
A coordinator that waits for its workers in a blocking delegation makes no model call. Its model sees the message when the workers finish.
The model sees that the message comes from an external sender, not who sent it.
Message statuses
The status() of the acknowledgement is one of the records of MessageStatus:
| Status | Meaning |
|---|---|
|
The message is for the current task. The model sees it in its next request for that task. |
|
The agent holds the message until its task starts, or until the next task starts when |
|
The agent stored the outcome of the model call that saw the message. |
|
The task ended before the agent consumed the message. |
|
The agent did not store the message. |
|
A newer runtime reported a status that this version of the SDK does not know. The agent may have stored the message. |
The agent rejects a message when:
-
the task of the message ended, or is not one of the tasks of the agent
-
the agent accepts no tasks
-
the agent already holds the maximum number of pending messages
Consumed and Dropped are only the status of a retry and of a message in the agent state. A new message never has them.
The agent consumes a message when it stores the outcome of the model call that saw the message. Consumed holds the id of that model call in interactionId(), and the ledger records the model call under that id. Read the record with getInteraction(interactionId) of the ledger client, see The ledger client. The agent drops a message whose task ends before the agent consumes it.
Retrying a message with a message id
Set a message id with messageId(…) when the call can run again, for example from a Workflow step or a Consumer. A message with the id of a known message gets the status of that message, with duplicate() set to true, and the agent stores nothing new. The agent knows an id while its message is pending, and while the message is among the 100 most recent consumed or dropped messages. The agent does not store a rejected message, so a retry of a rejected message is a new message. Without a message id, the runtime generates one, and a retry is a new message.
Message limits and failures
An agent holds at most 100 pending messages by default. All pending messages count, also the messages held for a queued task or for the next task. At the limit, the agent rejects a new message, and a retry of a known message still gets its status.
Reference images and PDFs by URI. attach(…) throws an IllegalArgumentException for content with inline bytes.
The call fails when the agent instance does not exist yet, and when the agent is stopped. An instance exists after its first setup(…) or task.
Following a message after you send it
getState() lists the pending messages and the most recent consumed or dropped messages with their status, see Agent state. The MessagesConsumed notification reports messages that the agent consumed, and the MessagesDropped notification reports messages that the agent dropped, see Agent notifications.
Agent state
Query the current state of an agent instance with getState(). The returned AgentState provides a snapshot of the agent’s execution status.
var state = componentClient
.forAutonomousAgent(ReportAgent.class, agentInstanceId)
.getState();
state.phase(); // "idle", "advance", "model", "tools", or "stopped"
state.suspended(); // whether the agent is suspended
state.instructions(); // the agent's current instructions
state.totalTokenUsage(); // cumulative token usage (inputTokens, outputTokens)
state.currentTask(); // Optional<TaskKey> with the task currently being worked on
state.pendingTaskIds(); // List<String> with ids of tasks queued but not yet started
state.pendingMessages(); // List<MessageState> with client messages that wait for the model
state.recentMessages(); // List<MessageState> with the latest consumed or dropped messages
The currentTask() returns an Optional<TaskKey> containing the id and name of the task the agent is actively processing. When the agent is idle or between tasks, it is empty.
pendingMessages() and recentMessages() list the messages of Sending a message to a running agent with their status.
Querying task results
Task results are typed based on the task definition’s resultConformsTo type. Two forms are available: get(…) returns a snapshot of the current state, while result(…) blocks until the task reaches a terminal state and returns the typed result directly.
Read a snapshot:
var snapshot = componentClient.forTask(taskId).get(ResearchTasks.BRIEF);
if (snapshot.status() == TaskStatus.COMPLETED) {
ResearchBrief brief = snapshot.result().orElseThrow();
var title = brief.title();
var findings = brief.keyFindings();
}
Wait for the terminal result:
ResearchBrief brief = componentClient.forTask(taskId).result(ResearchTasks.BRIEF);
result(…) blocks the calling thread until the task is COMPLETED, FAILED, or CANCELLED. It returns the typed result on success, or throws TaskException.Failed / TaskException.Cancelled on failure or cancellation. Use it when the caller wants to wait for the outcome rather than poll. In non-blocking code paths, prefer the async variant covered in Asynchronous execution.
Agent notifications
Subscribe to notifications for an agent instance to observe its execution progress in real time. Notifications are published by the runtime, not by user code, as the agent moves through its execution loop and participates in coordination patterns.
componentClient
.forAutonomousAgent(QuestionAnswerer.class, agentInstanceId)
.notificationStream()
.runForeach(System.out::println, materializer);
Subscribe before triggering the agent to avoid missing early events. The stream stays open as long as the agent instance exists. Use it for dashboards, logging, cost tracking, or coordinating external processes with agent progress.
Every notification implements the Notification sealed interface and exactly one capability-grouped marker sub-interface. Pattern-match on a marker to handle a whole family generically:
agentClient
.notificationStream()
.runForeach(
n -> {
switch (n) {
case Notification.LifecycleNotification lifecycle -> renderLifecycle(lifecycle);
case Notification.TaskNotification task -> renderTask(task);
case Notification.TeamNotification team -> renderTeam(team);
default -> {} // ignore
}
},
materializer
);
For the full set of notification types and their fields, see Notifications.
| The notification stream is a live stream that emits events only after the client creates the stream. It does not replay historical notifications. While the stream is running, it delivers events in order without loss. If the stream detects missing events it fails, allowing clients to reconnect and recover. |
Notifications should not be used to drive business logic. Akka does not guarantee delivery of every notification: events may be lost due to network issues, client disconnections, or other transient failures. If your application requires reliable state, query the task snapshot or agent state through the ComponentClient. Use notifications for observability, dashboards, and progress UIs, not as the source of truth.
|
Asynchronous execution
The ComponentClient calls in this page use the synchronous form, which is the right default for most code. Each call has an *Async variant that returns a CompletionStage<T> instead. Use the async form when you want to start work and continue without blocking, fan out several calls in parallel, or compose with other asynchronous code:
var stateF = componentClient
.forAutonomousAgent(ReportAgent.class, agentInstanceId)
.getStateAsync();
stateF.thenAccept(state -> log.info("Phase: {}", state.phase()));
The same shape applies to suspendAsync(), resumeAsync(), terminateAsync(), assignTasksAsync(…), runSingleTaskAsync(…), sendMessageAsync(…), and the forTask operations. Each returns a CompletionStage that completes once the runtime acknowledges the operation. Mixing styles is fine: use synchronous calls where they read more clearly, async ones where the call needs to compose with other futures.
See also
-
Notifications for the full notification reference