Skip to main content

ToolLoop

Struct ToolLoop 

Source
pub struct ToolLoop { /* private fields */ }
Available on crate feature tool-loop only.
Expand description

A model, the tools it may call, and the bounded loop between them.

Each turn sends the preamble, the whole conversation and the whole catalogue; a reply with calls has them run and their results appended, and a reply without is the answer. What a call returns goes back to the model, errors included: an unknown tool, arguments that are not a JSON object and ToolError::Failed are each that call’s result, because that is how a model recovers. Only the provider failing, a ToolError::Fatal, the turn bound and cancellation end a run.

Each call carries an idempotency key (ToolInvocation::idempotency_key, ADR 0026), and a call identical to one that already succeeded in the run is answered with the earlier result instead of being run again, unless its tool is read_only.

Implementations§

Source§

impl ToolLoop

Source

pub fn new(model: impl ToolModel, tools: ToolSet) -> ToolLoop

A loop over model and tools, with no preamble, DEFAULT_MAX_TURNS and text-call recovery on.

Source

pub const fn max_turns(&self) -> usize

The turn bound.

Source

pub const fn max_calls_per_turn(&self) -> usize

The bound on the tool calls of one reply.

Source

pub async fn run( &self, user_text: &str, cancel: &CancellationToken, ) -> Result<Answer, LoopError>

Sends user_text and runs turns until the model answers without a call. cancel is checked before each turn and each call, and a turn or call in progress is abandoned when it fires. An answer is a final reply with text: an empty or blank one is LoopError::EmptyAnswer, and one cut off at the model’s output limit is an Answer whose truncated is true.

§Errors

A LoopError naming why there is no answer.

Source

pub async fn run_within( &self, user_text: &str, cancel: &CancellationToken, budget: Option<&BudgetHandle>, ) -> Result<Answer, LoopError>

run, held to budget when there is one: no turn starts once its deadline has passed, and each reply’s reported token usage (input plus output) is charged to its TOKENS_METER, the run ending once that is spent. A provider that reports no usage charges nothing.

§Errors

As run, and LoopError::Budget when the budget runs out.

Source

pub async fn run_scoped( &self, scope: &str, user_text: &str, cancel: &CancellationToken, budget: Option<&BudgetHandle>, ) -> Result<Answer, LoopError>

run_within, with the calls’ idempotency keys derived in scope. run and run_within draw a fresh scope for each run; ToolLoopExecutor uses the task and message ids, so that running the same message of the same task again gives each call the key it had before. Give different work different scopes: the same call in the same scope has the same key.

With a journal the scope is also the journal’s key: running the same scope again resumes the run it left, and two pieces of work that share a scope share a checkpoint.

§Errors

As run_within.

Source§

impl ToolLoop

Source

pub fn with_agent_name(self, name: impl Into<String>) -> ToolLoop

Names the agent this loop is, recorded as gen_ai.agent.name on the run’s metrics.

Source

pub fn with_meter(self, meter: &Meter) -> ToolLoop

Available on crate feature otel only.

Records the loop’s metrics (gen_ai.client.inference.duration and the rest; ADR 0013) to meter rather than to the global provider’s meter, which is looked up each time one is recorded.

Takes the meter by reference since 0.16.0: the instruments are built from it once, here, and the meter itself is not kept (audit C-23).

Source

pub const fn with_idempotency_secret(self, secret: [u8; 32]) -> ToolLoop

Sets the secret idempotency keys are derived under. Each loop draws its own by default, so keys differ between processes; replicas that set the same secret give the same call in the same scope the same key, so a backend deduplicates a call one replica retries after another made it. Keep it as secret as a credential: with it, keys can be computed from task ids and arguments.

Source

pub fn with_journal(self, journal: Arc<dyn StepJournal>) -> ToolLoop

Keeps each run’s progress in journal, so a run begun again under the same key resumes instead of starting over, and a call a policy says needs approval can wait for it (adversarial review, S1 and S7). See StepJournal for what is written, what a resume promises, and what it does not.

Set with_idempotency_secret too if a call may be in flight when a replica dies: without it a call whose receipt was written and whose result was not cannot be re-run safely, and the resumed run fails with LoopError::Indeterminate.

Source

pub fn with_journal_cipher(self, cipher: Arc<dyn ContentCipher>) -> ToolLoop

Available on crate feature encryption only.

Seals each checkpoint’s body with cipher before the journal stores it: the conversation, tool arguments and results and the trace a run carries are then not readable from the journal’s table, its backups or its replicas without the key (adversarial review N07, 2026-11-13). The owner (tenant, caller, task), the revision and whether the run is finished stay readable: they are what the journal’s lifecycle (StepJournal::erase, StepJournal::sweep) finds a run by.

A body is bound to its run’s key and revision, so it does not open moved to another run or rolled back. A checkpoint written as JSON before the cipher was set is still read, and sealed from its next write.

Source

pub const fn with_result_limit(self, bytes: usize) -> ToolLoop

Shows the model at most bytes of one tool’s result; the rest is cut, at a character boundary, and the model is told how much there was (DEFAULT_RESULT_LIMIT, 1 MiB). The tool ran either way; this bounds what the run keeps of it (N09).

Source

pub const fn with_request_limit(self, bytes: usize) -> ToolLoop

Sends no model request past bytes (preamble, conversation and tool catalogue, as JSON): the run ends with LoopError::TooLarge instead (DEFAULT_REQUEST_LIMIT, 8 MiB; N09).

Source

pub const fn with_checkpoint_limit(self, bytes: usize) -> ToolLoop

Writes no checkpoint body past bytes: the run stops before the step it would have recorded, as for any checkpoint the journal cannot write (DEFAULT_CHECKPOINT_LIMIT, 32 MiB; N09).

Source

pub fn with_pin( self, name: impl Into<String>, value: impl Into<String>, ) -> ToolLoop

Adds a pin to every checkpoint: a policy version, a skill bundle digest, anything the deployment says a resumed run must still be running under. A run whose checkpoint carries other pins is refused on resume.

Source

pub fn with_preamble(self, preamble: impl Into<String>) -> ToolLoop

Sets the system preamble every turn is sent with.

Source

pub const fn with_max_turns(self, max_turns: usize) -> ToolLoop

Sets how many model turns a run may take. 0 is taken as 1: a run asks the model at least once.

Source

pub const fn with_max_calls_per_turn(self, max_calls: usize) -> ToolLoop

Sets how many tool calls one model reply may make; the first this many run and the rest are dropped, with a line in the trace saying so. 0 is taken as 1. DEFAULT_MAX_CALLS_PER_TURN when not set.

Source

pub const fn with_recover_text_calls(self, on: bool) -> ToolLoop

Whether a final reply that is exactly one JSON object naming a tool in the set — bare, in a code fence, or between <tool_call> tags — is run as that call rather than returned as the answer. On by default: small models write calls as text, and an answer of raw JSON helps nobody. true is TextCallRecovery::All and false TextCallRecovery::Off; with_text_call_recovery also offers ReadOnly.

Source

pub const fn with_text_call_recovery( self, recovery: TextCallRecovery, ) -> ToolLoop

Which tools a reply written as a call may run (adversarial review T3).

Source

pub const fn with_trace_content(self, content: TraceContent) -> ToolLoop

What the caller’s trace carries for each call (adversarial review T1).

Source

pub const fn with_argument_check(self, check: ArgumentCheck) -> ToolLoop

Whether a call’s arguments are checked against the tool’s JSON Schema before the policy is asked and the call runs (adversarial review T2); see ArgumentCheck for what is checked and what is not.

Source

pub fn with_policy(self, policy: impl ToolPolicy) -> ToolLoop

Installs a policy asked before every call runs (adversarial review T2).

Source

pub fn strict(model: impl ToolModel, tools: ToolSet) -> ToolLoop

A loop for a deployment that takes a tool call to be an action with consequences: no call is lifted out of text (TextCallRecovery::Off), the caller’s trace is a receipt (TraceContent::Receipt) and arguments are checked against the tool’s schema (ArgumentCheck::Strict). Add a ToolPolicy with with_policy for per-action authorisation.

Source§

impl ToolLoop

Source

pub const fn with_model_retry(self, retry: ModelRetry) -> ToolLoop

Sends a turn the provider refused as rate limited (ModelError::RateLimited) again, as retry says, instead of ending the run on it (audit H17, ADR 0048). Off by default: without it a 429 ends the run, and the task ends transient.

The wait honours the provider’s Retry-After, is never longer than what remains of the run’s budget, and is abandoned when the run is cancelled. A LimitedModel’s slot is not held while the loop waits.

Trait Implementations§

Source§

impl Debug for ToolLoop

Source§

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

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