Struct LlmAgent
pub struct LlmAgent { /* private fields */ }Expand description
A durable LLM tool-calling agent: instructions + a model + a toolset.
Implements [adam_runtime::Agent] with Conversation as its state.
Register it on a Runtime and start runs with a user message (see
user_message).
§One step is one model turn
- Inbox messages are appended to the history (or, when the run was parked on a question, the first one answers it). A run parked on a child run looks at the child instead (see “Child runs” below).
- The model is called in a journaled step
model:<turn>with the history and tool specs. - Each requested tool runs as its own journaled step
tool:<call id>and its result is appended, in the order of the calls. The calls of the turn run at the same time, up toLlmAgentBuilder::max_parallel, except whereTool::accesssays two conflict: a tool that declares nothing runs alone, after the calls before it (ADR 0049). Then the step returnsContinue, so every turn is committed before the next begins. A turn without tool calls returnsDonewith{"text": <final text>, "artifacts": [{name, mime_type}...]}. When a tool announced the answer (ToolOutput::announcing) in this turn of the conversation, the text is the last announcement and not the model’s closing words (see “Announced answers”).
Because steps are journaled, a restarted worker replays recorded model and tool results instead of repeating them.
§Events
All best effort, through Ctx::emit:
TextDeltawhile a model turn that streams (LlmAgentBuilder::stream_text, on by default) writes: the pieces of its words, in a stream whose id is made inside the journaled step and recorded with the answer (see “Streamed text” below);Custom { kind: "agent_text", payload: {text, turn} }for each model turn with text, withstream(the id of the stream the words were sent as) for a turn that goes on to call tools;Stepfor each tool call: aStepEventwith the idtool:<call id>, the kind, label and icon ofTool::step_style(the tool’s name by default),runningbefore the tool runs and, after it,completed(a result),failed(an error result, or a failure the run retries), orwaiting(the tool asked the person a question, or the run parked on a child run or a remote task: the end comes when the answer does). Therunningreport carries the call’s arguments (input) and the report that ends the step the result, or the error it ended with (output), scrubbed and cut by the agent’sStepIo(ADR 0011);Stepagain fromToolCtx::emit_progress(an update of the call’s own step, the text in its detail) and fromToolCtx::report_step(steps that run under the call’s: a command, a tool of the agent the call drives);Usagefor each model call that completed (the provider answered, with or without usage): its tokens (Usage::accounted), the alias, the provider and the context window the model client says, and an id made inside the journaled step and recorded with the answer, so a replay reports the call under the same id. It is an event of the root run (ToolCtx::root_run_id): a child run’s report names the root’s step it works under (Conversation::root_step), so the task’s client counts a subagent apart. The tokens are also counted inConversation::usage_totals, and a child’s totals are added to its parent’s when it answers (ADR 0032);Artifactfor each artifact a tool returns (also durable);Custom { kind: "input_required", payload: {question, call_id} }before parking;Custom { kind: "answer_refused", payload: {call_id, question, rule} }when the tool that asked read the answer and refused it (Tool::read_answer): the run stays parked on the question the tool asked in its place, and the model hears nothing (questionis what the rule was about,*for the whole answer);Custom { kind: "awaiting_run", payload: {call_id, run} }before parking on a child run, followed by the call’s stepwaiting(not final), and later by the finalcompletedorfailedwhen the child’s outcome becomes the result;Custom { kind: "awaiting_remote", payload: {call_id, task} }before parking on a remote task, with the same step sequence.
Step replaces the Custom events tool_start and tool_end that earlier versions emitted
(tool_end’s status words: ok is completed, error and transient_error are failed,
needs_input and waiting are waiting), and Progress from emit_progress.
§Streamed text
A model turn is asked for as a stream (ModelClient::stream) unless
LlmAgentBuilder::stream_text says otherwise, and what the model writes is sent as it arrives
([RunEvent::TextDelta]): a piece when 200 bytes have gathered or 100 ms have passed since the last, at most
MAX_TEXT_DELTA_BYTES at a time, in a stream that opens on the first word
that is not blank and ends with a piece marked last (abandoned when the model failed). The turn is still one
journaled step whose outcome is the assembled response, recorded with the stream’s id (a journal written before
reads as one with no stream): a replay calls no model and sends no piece, but names the same stream, and a
failure, in the middle of the answer too, is the same failure as a failed
complete. The answer that ends the run names its stream in the run’s output
(stream), as agent_text does for the words before a tool call.
§Announced answers
A tool can say “this is my answer” before the model is done: ToolOutput::announcing. The words
are kept in Conversation::announced (journaled with the call’s result, so a replay announces the
same ones), a later announcement replaces them, and an error result announces nothing. When the run
finishes, they are the output’s text, and so the text of the A2A completed status, whatever the
model closes with; the closing words are still said, as agent_text with their stream, and the
output names no stream. A message that reaches the run ends the turn and clears the announcement.
A tool can also end the turn with its announcement (ToolOutput::final_answer): once the
calls of that model turn are answered, the run finishes with the announced text and the model is
not called again, so there are no closing words to say after an answer that was already handed
over (Conversation::announced_final). A message that reached the run meanwhile is read first.
§Child runs
A tool that returns ToolError::AwaitRun has started a child run (with
Runtime::start_child, under ToolCtx::child_run_id) whose outcome is
the answer. The run parks with a timer (LlmAgentBuilder::wait_poll,
60 s by default) and records the wait in Conversation::pending_wait.
When the child finishes, the runtime delivers an adam.run.finished
message and the parent wakes at once; if that message is lost, the timer
wakes it and it reads the child (Ctx::child_status), so a lost message
costs at most one interval. The outcome becomes the tool result: the
child’s text (or its output as JSON), or, for a child that failed or was
cancelled, an error result saying so. The message is matched to the wait by
the child’s run id, and one that matches nothing (a copy of a message
already used, or a stray one) is dropped. User messages that arrive
meanwhile queue behind the owed result. Cancelling the parent does not
cancel the child.
§Remote tasks
A tool that starts a task on another system (an A2A agent) returns
ToolError::AwaitRemote. The run records a PendingWait::Remote and parks with the same
timer as for a child run, but nothing tells it when the task is over, so every time the timer
fires it asks the tool (Tool::poll_remote) in a journaled step named poll:<call id>, and
parks again until the answer is RemotePoll::Ready. A replay after a crash sees the recorded
answers, so the tool is not asked twice for one wake, and the call that started the task is
not repeated. If the tool gave a timeout, the call is answered with an error result once it has
passed (measured by the journaled clock). Cancelling the run does not cancel the remote task.
§A run parked on the model
A model call the endpoint refused, when its provider parks the run on the refusal
(ModelCredentials::parks, ADR 0067), does not fail the
run. The conversation is kept as it was before the call, Conversation::model_wait says why
(ModelWait: the reason, the status, the slug, how it wakes, and since when), and the run
parks. When it wakes, the same call is made again, in a new journaled step; the summary call
of a compaction parks and is made again the same way. The first call that is answered clears the
wait.
- On a timer (a lease not bound yet, a busy gateway, one that cannot be reached): the run
wakes on its own after 30 s, doubling at each park in a row up to
MAX_MODEL_BACKOFF, and never sooner than the provider asked (Retry-After). Parks on a timer in a row are bounded byModelParking::limitfrom the first of them, on the journaled clock: past it the run fails with the last reason, and no wait goes past it. A timer counts against a child run’s time limit, as any timer does. - Until woken (a usage limit reached): the run waits like a question, with no timer and its
deadline paused, and never fails on its own. A run nobody can wake fails instead: a schedule’s
firing (
is_unattended). A local subagent waits for the resume its parent forwards (ADR 0067 decision 5); a parent that is not anLlmAgentforwards none, so the child waits until a cancel. A firing also fails on a refusal of status 401 or 403, since nothing binds a firing at the gateway yet. - Waking. A message wakes either kind: its text is the person’s turn, added before the call. A
message of kind
MODEL_RESUME_KINDwakes it and adds nothing (and one that lands while the run works is no arrival). A run parked on its summary call takes its inbox, the words kept inConversation::deferredfor after the summary. A cancel ends the park as it ends any wait.
The journal, the run’s error and what a front shows hold the reason, the status and the slug, never a header, a body or a credential.
§Failure handling
- Retryable model error (
ModelError::is_retryable),ToolError::TransientorToolError::Retryable:AgentError::Transientof the error’s class, retried by the runtime, under the tool’s policy for a tool that has one (Tool::retry_policy,LlmAgentBuilder::tool_retry, counted undertool_retry_key). AModelError::RateLimitedthat carries aretry_afterbecomes anAgentError::Transientwith that hint (with_retry_after), so the retry waits at least that long (the runtime’s backoff still applies when it is longer). - A refusal whose provider parks the run (
ModelError::Refused), and, withModelParking::when_unreachable, an endpoint that cannot be reached once the step’s retries are spent: the run parks on the model (below), and fails only pastModelParking::limit, or on a park until woken in a run nobody can wake (a schedule’s firing). A refusal of status402(the person’s usage limit reached) first tries the fallback once, as a locked model does, and parks only when no model is left. - Other model error,
ModelError::ModelLocked(naming the model) among them: the run fails (model call failed: ...). So does a refusal under a provider that does not park (StaticBearer’s401isModelError::Auth). ToolError::Permanent,ToolOutput { is_error: true }and unknown tool names: an error tool result for the model; the run goes on. So does a child run that failed, was cancelled or no longer exists.- A call whose arguments were not JSON ([
ToolCall::invalid_arguments]): an error tool result quoting what was sent; nothing runs; the run goes on. - A tripped
max_turnsormax_tool_calls: one closing model call in which no tool may be called (CLOSING_TURN), and the run endsDonewith its answer markedlimited; the run fails only if that answer has no words.
Implementations§
§impl LlmAgent
impl LlmAgent
pub fn builder(
name: impl Into<String>,
model: Arc<dyn ModelClient>,
model_alias: impl Into<String>,
) -> LlmAgentBuilder
pub fn builder( name: impl Into<String>, model: Arc<dyn ModelClient>, model_alias: impl Into<String>, ) -> LlmAgentBuilder
Start building an agent called name that talks to model under the
gateway alias model_alias.
pub fn model_parking(&self) -> ModelParking
pub fn model_parking(&self) -> ModelParking
How a run of this agent waits on a model that refused it (LlmAgentBuilder::model_parking).
pub fn max_parallel(&self) -> usize
pub fn max_parallel(&self) -> usize
The most tool calls of a turn that run at the same time
(LlmAgentBuilder::max_parallel).
Trait Implementations§
§impl Agent for LlmAgent
impl Agent for LlmAgent
§fn init(&self, input: Inbound) -> Result<Conversation, AgentError>
fn init(&self, input: Inbound) -> Result<Conversation, AgentError>
The input is the first user message: payload {"text": "..."} or a bare
JSON string (see user_message); its kind is
not inspected. The same as LlmStarter::init.
§fn init_continuing(
&self,
input: Inbound,
prior: &Conversation,
prior_run: RunId,
) -> Result<Conversation, AgentError>
fn init_continuing( &self, input: Inbound, prior: &Conversation, prior_run: RunId, ) -> Result<Conversation, AgentError>
The prior run’s conversation with the input as its newest user message, see
Conversation::continued for what is carried, dropped and reset. The same as
LlmStarter::init_continuing.
§type State = Conversation
type State = Conversation
§fn split(&self, state: &Conversation) -> Option<(Conversation, Vec<Value>)>
fn split(&self, state: &Conversation) -> Option<(Conversation, Vec<Value>)>
state into the small part a run’s head keeps and its transcript, oldest first. Read more§fn join(
&self,
head: Conversation,
rows: Vec<Value>,
) -> Result<Conversation, AgentError>
fn join( &self, head: Conversation, rows: Vec<Value>, ) -> Result<Conversation, AgentError>
§fn step<'life0, 'life1, 'async_trait>(
&'life0 self,
ctx: &'life1 mut Ctx,
state: Conversation,
) -> Pin<Box<dyn Future<Output = Result<Transition<Conversation>, AgentError>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
LlmAgent: 'async_trait,
fn step<'life0, 'life1, 'async_trait>(
&'life0 self,
ctx: &'life1 mut Ctx,
state: Conversation,
) -> Pin<Box<dyn Future<Output = Result<Transition<Conversation>, AgentError>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
LlmAgent: 'async_trait,
ctx.step; step
may be re-invoked after a crash.§fn on_cancelled<'life0, 'async_trait>(
&'life0 self,
run: RunId,
state: Value,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
fn on_cancelled<'life0, 'async_trait>(
&'life0 self,
run: RunId,
state: Value,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
run as Failed (Runtime::cancel, a parent
that ended, a time limit, a cancel from the A2A front), with the agent state that commit
holds as JSON, so an agent can tell a system it started elsewhere (a remote task) to stop. Read moreAuto Trait Implementations§
impl !RefUnwindSafe for LlmAgent
impl !UnwindSafe for LlmAgent
impl Freeze for LlmAgent
impl Send for LlmAgent
impl Sync for LlmAgent
impl Unpin for LlmAgent
impl UnsafeUnpin for LlmAgent
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].