pub struct ToolLoop { /* private fields */ }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
impl ToolLoop
Sourcepub fn new(model: impl ToolModel, tools: ToolSet) -> ToolLoop
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.
Sourcepub const fn max_calls_per_turn(&self) -> usize
pub const fn max_calls_per_turn(&self) -> usize
The bound on the tool calls of one reply.
Sourcepub async fn run(
&self,
user_text: &str,
cancel: &CancellationToken,
) -> Result<Answer, LoopError>
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.
Sourcepub async fn run_within(
&self,
user_text: &str,
cancel: &CancellationToken,
budget: Option<&BudgetHandle>,
) -> Result<Answer, LoopError>
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.
Sourcepub async fn run_scoped(
&self,
scope: &str,
user_text: &str,
cancel: &CancellationToken,
budget: Option<&BudgetHandle>,
) -> Result<Answer, LoopError>
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
impl ToolLoop
Sourcepub fn with_agent_name(self, name: impl Into<String>) -> ToolLoop
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.
Sourcepub fn with_meter(self, meter: &Meter) -> ToolLoop
Available on crate feature otel only.
pub fn with_meter(self, meter: &Meter) -> ToolLoop
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).
Sourcepub const fn with_idempotency_secret(self, secret: [u8; 32]) -> ToolLoop
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.
Sourcepub fn with_journal(self, journal: Arc<dyn StepJournal>) -> ToolLoop
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.
Sourcepub fn with_journal_cipher(self, cipher: Arc<dyn ContentCipher>) -> ToolLoop
Available on crate feature encryption only.
pub fn with_journal_cipher(self, cipher: Arc<dyn ContentCipher>) -> ToolLoop
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.
Sourcepub const fn with_result_limit(self, bytes: usize) -> ToolLoop
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).
Sourcepub const fn with_request_limit(self, bytes: usize) -> ToolLoop
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).
Sourcepub const fn with_checkpoint_limit(self, bytes: usize) -> ToolLoop
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).
Sourcepub fn with_pin(
self,
name: impl Into<String>,
value: impl Into<String>,
) -> ToolLoop
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.
Sourcepub fn with_preamble(self, preamble: impl Into<String>) -> ToolLoop
pub fn with_preamble(self, preamble: impl Into<String>) -> ToolLoop
Sets the system preamble every turn is sent with.
Sourcepub const fn with_max_turns(self, max_turns: usize) -> ToolLoop
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.
Sourcepub const fn with_max_calls_per_turn(self, max_calls: usize) -> ToolLoop
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.
Sourcepub const fn with_recover_text_calls(self, on: bool) -> ToolLoop
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.
Sourcepub const fn with_text_call_recovery(
self,
recovery: TextCallRecovery,
) -> ToolLoop
pub const fn with_text_call_recovery( self, recovery: TextCallRecovery, ) -> ToolLoop
Which tools a reply written as a call may run (adversarial review T3).
Sourcepub const fn with_trace_content(self, content: TraceContent) -> ToolLoop
pub const fn with_trace_content(self, content: TraceContent) -> ToolLoop
What the caller’s trace carries for each call (adversarial review T1).
Sourcepub const fn with_argument_check(self, check: ArgumentCheck) -> ToolLoop
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.
Sourcepub fn with_policy(self, policy: impl ToolPolicy) -> ToolLoop
pub fn with_policy(self, policy: impl ToolPolicy) -> ToolLoop
Installs a policy asked before every call runs (adversarial review T2).
Sourcepub fn strict(model: impl ToolModel, tools: ToolSet) -> ToolLoop
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
impl ToolLoop
Sourcepub const fn with_model_retry(self, retry: ModelRetry) -> ToolLoop
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§
Auto Trait Implementations§
impl !RefUnwindSafe for ToolLoop
impl !UnwindSafe for ToolLoop
impl Forget for ToolLoop
impl Freeze for ToolLoop
impl Move for ToolLoop
impl Send for ToolLoop
impl Sync for ToolLoop
impl Unpin for ToolLoop
impl UnsafeUnpin for ToolLoop
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§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].