Skip to main content

LlmAgent

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

  1. 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).
  2. The model is called in a journaled step model:<turn> with the history and tool specs.
  3. 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 to LlmAgentBuilder::max_parallel, except where Tool::access says two conflict: a tool that declares nothing runs alone, after the calls before it (ADR 0049). Then the step returns Continue, so every turn is committed before the next begins. A turn without tool calls returns Done with {"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:

  • TextDelta while 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, with stream (the id of the stream the words were sent as) for a turn that goes on to call tools;
  • Step for each tool call: a StepEvent with the id tool:<call id>, the kind, label and icon of Tool::step_style (the tool’s name by default), running before the tool runs and, after it, completed (a result), failed (an error result, or a failure the run retries), or waiting (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). The running report 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’s StepIo (ADR 0011);
  • Step again from ToolCtx::emit_progress (an update of the call’s own step, the text in its detail) and from ToolCtx::report_step (steps that run under the call’s: a command, a tool of the agent the call drives);
  • Usage for 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 in Conversation::usage_totals, and a child’s totals are added to its parent’s when it answers (ADR 0032);
  • Artifact for 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 (question is 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 step waiting (not final), and later by the final completed or failed when 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 by ModelParking::limit from 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 an LlmAgent forwards 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_KIND wakes 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 in Conversation::deferred for 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::Transient or ToolError::Retryable: AgentError::Transient of 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 under tool_retry_key). A ModelError::RateLimited that carries a retry_after becomes an AgentError::Transient with 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, with ModelParking::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 past ModelParking::limit, or on a park until woken in a run nobody can wake (a schedule’s firing). A refusal of status 402 (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’s 401 is ModelError::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_turns or max_tool_calls: one closing model call in which no tool may be called (CLOSING_TURN), and the run ends Done with its answer marked limited; the run fails only if that answer has no words.

Implementations§

§

impl LlmAgent

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

How a run of this agent waits on a model that refused it (LlmAgentBuilder::model_parking).

pub fn limits(&self) -> &Limits

The limits in force.

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

§

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>

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

The agent’s own state machine, stored as JSON.
§

fn name(&self) -> &str

Stable name, stored as RunRecord::agent.
§

fn split(&self, state: &Conversation) -> Option<(Conversation, Vec<Value>)>

Split 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>

head with rows as its transcript: the inverse of split. Read more
§

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,

Advance by one transition. Side effects go through 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,

Called once after a cancel has committed 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 more
§

impl Clone for LlmAgent

§

fn clone(&self) -> LlmAgent

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for LlmAgent

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more