Skip to main content

LlmAgentBuilder

Struct LlmAgentBuilder 

pub struct LlmAgentBuilder { /* private fields */ }
Expand description

Configures an LlmAgent. Start with LlmAgent::builder.

Implementations§

§

impl LlmAgentBuilder

pub fn instructions(self, instructions: impl Into<String>) -> LlmAgentBuilder

The system prompt.

pub fn tool(self, tool: impl Tool) -> LlmAgentBuilder

Register a tool. A second tool with the same name replaces the first.

pub fn dyn_tool(self, tool: Arc<dyn Tool>) -> LlmAgentBuilder

Register an already shared tool.

pub fn tools(self, tools: ToolSet) -> LlmAgentBuilder

Register every tool of a ToolSet, in order.

pub fn tool_source(self, source: impl ToolSource) -> LlmAgentBuilder

Add a ToolSource: tools the agent learns about while it runs, offered to the model on every turn after the agent’s own tools. Sources are asked in the order they were added.

pub fn dyn_tool_source(self, source: Arc<dyn ToolSource>) -> LlmAgentBuilder

Add an already shared ToolSource.

pub fn state<T>(self, value: Arc<T>) -> LlmAgentBuilder
where T: Send + Sync + 'static,

Share value with the tools: they read it with ToolCtx::state (as State<T>), and try_build checks it exists for every tool that declares it in Tool::required_state. One value per type; a second call with the same T replaces the first.

pub fn limits(self, limits: Limits) -> LlmAgentBuilder

Replace the Limits (default: Limits::default).

pub fn wait_poll(self, every: Duration) -> LlmAgentBuilder

How long a run that waits for a child run (a tool returned ToolError::AwaitRun) sleeps before it reads the child itself (default DEFAULT_WAIT_POLL, 60 s).

The child normally tells the parent when it finishes, and the parent wakes at once. The timer is the fallback for a message that never arrived (the child’s process died between its commit and the message), so it bounds how late the parent can be, not how often it runs: each wake without the message is one store read. A zero interval is raised to one millisecond.

A run that waits for a task on another system (ToolError::AwaitRemote) is told nothing when the task ends, so for it this is how often the task is looked at, and the longest a finished task waits to be noticed.

pub fn stream_text(self, on: bool) -> LlmAgentBuilder

Whether a model turn is asked for as a stream (the default) and its words are sent as they are written ([RunEvent::TextDelta]), or as one answer (ModelClient::complete) that is told when it is whole, as it was before.

Streaming changes what observers see, not what the run does: the turn is still one journaled step and the answer is the assembled response, so the history, the tools and the outcome are the same. A client of the model that cannot stream, or a provider that answers a stream request with an error, is a reason to turn it off. See “Streamed text” on LlmAgent.

pub fn session_agents( self, agents: impl IntoIterator<Item = impl Into<String>>, ) -> LlmAgentBuilder

Make the agent wait, at the end of a turn, for the sessions it started in this task (ADR 0045): agents are the registration names of the subagents the session tools (SessionTools) can start. A model answer with no tool call, while a session of one of them that this run started still works, does not end the run: the run parks on the session as if the model had called subagent_read with wait: true, and the report reaches the model before the run ends. The agent needs the tools of SessionTools::tools registered, or the wait has nothing to read the report with and is skipped. The default is none, which waits for nothing.

pub fn max_parallel(self, n: usize) -> LlmAgentBuilder

The most tool calls of one model turn that run at the same time: 10 by default, and n clamped to 1..=32. The calls of a turn run together as far as their Tool::access allows (a tool that declares nothing runs alone), the ones over the limit wait in a queue and start in call order, and the results go back to the model in call order. 1 runs the calls one after another. It is not a field of Limits: those are built by literals. See ADR 0049.

pub fn tool_retry( self, name: impl Into<String>, policy: RetryPolicy, ) -> LlmAgentBuilder

The retry policy of the tool name’s retryable failures, which wins over the tool’s own (Tool::retry_policy): what an agent folder’s retry: sets (ADR 0061). A tool that another system offers (an MCP server’s <server>__<tool>) has no policy of its own, so this is the only way to give it one. The failures count under the key tool:<name> (tool_retry_key). A policy for a name the agent never calls is never used.

pub fn admission(self, admission: Arc<dyn Admission>) -> LlmAgentBuilder

The process’s pools ([Admission], ADR 0065): every model call takes a seat of [Pool::ModelCalls] and every tool call one of [Pool::ToolCalls], so four runs at once never start more calls than the deployment allows. None (the default) admits everything: a host that sets no ceiling is the ceiling.

  • A model call waits five seconds for its seat, then parks the run on the refusal’s retry_after, as it parks on a provider’s 429 (ADR 0061, ADR 0067).
  • A tool call waits up to TOOL_ADMISSION_WAIT and then runs anyway, with a warning: a run never fails because a slot was busy (ADR 0065 decision 4).

pub fn hooks(self, hooks: HookSet) -> LlmAgentBuilder

Install a compiled hook set around every tool call (ADR 0050, slice H1): before_tool runs inside the call’s journaled step, after a source’s withhold and before the tool, and after_tool runs there once the tool answered.

A hook may rewrite the arguments or the text the model reads, deny the call, ask a person (until approval is built the call is not run, and its result says it awaits approval), or stop the run: the call’s result is the reason and the run fails stopped by a plugin: <reason>. A hook that fails never lets a call through. The verdict is recorded in the step’s record (HookedOutput), so a replay that finds the step recorded asks no hook again, and adding or removing a plugin never changes a step’s name or seq.

A before_tool rewrite that would change what the call touches (Tool::access of the new arguments differs from the one the schedule used, ADR 0049) is refused and the call denied. A call that takes no step (arguments that are not JSON, a tool nobody has) runs no hook: a decision is recorded in the step it would have changed, and there is none.

pub fn max_run_continuations(self, max: u32) -> LlmAgentBuilder

The most times the run.ending hooks may keep one run going (ADR 0050, decision 10; default DEFAULT_RUN_CONTINUATIONS, at most MAX_RUN_CONTINUATIONS). Past it the run ends and the step end:<turn> records capped; 0 never lets a hook keep a run going.

pub fn turn_keys(self, keys: Arc<dyn TurnKeys>) -> LlmAgentBuilder

The keys that sign every assistant and tool turn this agent commits (ADR 0068, slice T3a-1): each carries extra_content.adam.turn_signature, bound to its run, conversation, position and the chain of every message before it. A person’s message is chained, never signed. Without keys (the default) nothing is signed and a run commits as it always did. Nothing is verified here (re-entry is slice T3a-3), and the signature is never sent to a model.

pub fn event(self, spec: EventSpec) -> LlmAgentBuilder

Declare a custom event the agent’s tools may emit, beside the ones each tool declares itself (Tool::events) (ADR 0050, decision 6). Every tool of the agent may emit it. A name in a core namespace, one that is not ns.name, or a second declaration of it that differs is a BuildError::Event from try_build.

pub fn plugin(self, plugin: impl Plugin + 'static) -> LlmAgentBuilder

Append one plugin to the hook set (LlmAgentBuilder::hooks); the order plugins are added in is the order their hooks run in.

pub fn reasoning_effort( self, effort: Option<ReasoningEffort>, ) -> LlmAgentBuilder

The reasoning effort every model call of this agent asks for unless the run’s context names one (REASONING_EFFORT_CONTEXT_KEY, ADR 0063): what an agent folder, its model_preset or its model profile resolves to. None (the default) sends nothing, which is the model’s own default and may reason. The loop sets it on the request of each turn, never on the summary call.

pub fn model_fallback(self, fallback: ModelBinding) -> LlmAgentBuilder

The model the run continues on, once, when a model call of it is refused with [ModelError::ModelLocked] or over the person’s limit ([ModelError::Refused] of status 402, ADR 0064 amended 2026-11-23 and 2026-11-25): an agent folder’s model_fallback, resolved by the assembly with its profile. The run says so as a step, reports the calls after it under this alias, and never switches back; a second ModelLocked fails the run naming both models, and a second 402 parks it as over limit. Without one, a locked model fails the run as before, and a 402 parks it.

pub fn model_choices(self, choices: Vec<ModelBinding>) -> LlmAgentBuilder

The models a message may pick for its run (MODEL_CONTEXT_KEY), each with its resolved profile values. A context that names another alias, or an agent given none, is ignored: the agent’s own model answers. The assembly gives them to an embedding engine only, never to a served agent, whose callers may not choose what a run costs.

pub fn model_parking(self, parking: ModelParking) -> LlmAgentBuilder

How a run waits on a model that refused it or could not be reached (ADR 0067): how long parks on a timer in a row may last (24 hours by default), and whether an unreachable endpoint parks at all (no, by default). See “A run parked on the model” on LlmAgent.

pub fn step_io(self, step_io: StepIo) -> LlmAgentBuilder

How the step of a tool call reports what the tool was given and what it answered: the arguments on the report that starts the step, the result (or the error) on the one that ends it, each scrubbed by StepIo::redact and then cut to the contract’s bounds (4 KiB in, 8 KiB out). The default sends both, with no redactor; StepIo::off sends neither. See “Events” on LlmAgent and ADR 0011.

pub fn try_build(self) -> Result<LlmAgent, BuildError>

Build the agent, or say what is wrong with how it was put together: a tool whose Tool::required_state was not registered with state, or two tools with one name.

build keeps accepting both (the last duplicate wins, with a warning; a missing state shows up when the tool runs), for compatibility. Prefer this one.

use std::sync::Arc;
use adam_llm_agent::{BuildError, LlmAgent, Tool, ToolCtx, ToolError, ToolOutput, StateKey};
use adam_model::{MockModel, ToolSpec};
use async_trait::async_trait;
use serde_json::{Value, json};

struct Db;
struct Lookup;

#[async_trait]
impl Tool for Lookup {
    fn spec(&self) -> ToolSpec {
        ToolSpec { name: "lookup".into(), description: "Look up.".into(),
                   parameters: json!({"type": "object", "properties": {}}) }
    }
    fn required_state(&self) -> Vec<StateKey> { vec![StateKey::of::<Db>()] }
    async fn call(&self, ctx: &ToolCtx, _args: Value) -> Result<ToolOutput, ToolError> {
        let _db = ctx.require_state::<Db>()?;
        Ok(ToolOutput::text("found"))
    }
}

let model = Arc::new(MockModel::new());
let missing = LlmAgent::builder("a", model.clone(), "m").tool(Lookup).try_build();
assert!(matches!(missing, Err(BuildError::MissingState { .. })));
let ok = LlmAgent::builder("a", model, "m").state(Arc::new(Db)).tool(Lookup).try_build();
assert!(ok.is_ok());

pub fn build(self) -> LlmAgent

Build the agent.

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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