Skip to main content

AgentRunner

Struct AgentRunner 

Source
pub struct AgentRunner<O = ()> { /* private fields */ }
Expand description

A hook-aware driver over AgentRun.

Construct one with Agent::prompt (a fresh run) or Agent::resume (a persisted one), attach hooks with add_hook, then call run (blocking), stream (incremental) or run_channel (a future plus an event feed). Hooks are held in a HookStack, an ordered, runtime-composable list; run() and stream() share the same loop and fire the same events, so they behave identically apart from the streamed delta events the medium adds.

O is what .await recovers: () for the raw PromptResponse, or a TypedOutput for a TypedRun.

Implementations§

Source§

impl AgentRunner

Source

pub fn unhandled_invalid_tool_call( self, policy: UnhandledInvalidToolCall, ) -> Self

Set the policy for invalid tool calls that no hook resolves. A resumed run keeps the policy it persisted.

Source§

impl<O> AgentRunner<O>

Source

pub fn add_hook<H>(self, hook: H) -> Self
where H: AgentHook + 'static,

Append a hook to the stack (on top of any the agent already carries). Hooks run in registration order; how their results compose is event-dependent (model selections and ToolCall/ToolResult rewrites chain, CompletionCall request patches accumulate and merge, while model-turn steering and observe-only/recovery events use their event-specific terminal action). See the hook module docs.

Source

pub fn max_turns(self, max_turns: usize) -> Self

Set the total model-call budget, including the initial call and every retry or continuation. Zero emits no model calls; one permits only the initial call. Exceeding the budget returns PromptError::MaxTurns, which a typed run wraps in StructuredOutputError::Prompt.

Source

pub fn memory( self, store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static, ) -> Self

Keep this run’s conversation in store, in place of the agent’s (AgentBuilder::memory), such as a store chosen per request; one store also holds every user’s conversation, a log each (conversation).

Source

pub fn conversation(self, log: impl Into<String>) -> Self

The log of the memory store this run loads and saves (AgentBuilder::conversation).

Source

pub fn using_model(self, label: impl Into<ModelRef>) -> Self

Set the default model candidate for this run.

This does not suppress registered model-selection hooks, which may replace the candidate before each model call (including retries). Append an unconditional selecting hook last when the run must always use one model.

Source

pub fn using_model_value(self, model: impl Into<DynModel<Completion>>) -> Self

Register model in the agent’s table under a generated label and use it as this run’s default. The registration is scoped to this runner and the run it produces: it leaves the table when they drop.

Source

pub fn tool_context(self, context: ToolContext) -> Self

Set the typed context cloned for every tool dispatch in this run.

Source

pub fn history<I, T>(self, history: I) -> Self
where I: IntoIterator<Item = T>, T: Into<Message>,

Set the chat history preceding the prompt. The run then neither loads nor saves a memory store’s conversation.

Source

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

Override the agent preamble for this run.

Source

pub fn without_preamble(self) -> Self

Remove the agent’s configured preamble for this run.

Source

pub fn document(self, document: Document) -> Self

Append one static context document for this run.

Source

pub fn documents(self, documents: impl IntoIterator<Item = Document>) -> Self

Append static context documents for this run.

Source

pub fn temperature(self, temperature: f64) -> Self

Override the model temperature for this run.

Source

pub fn without_temperature(self) -> Self

Remove the agent’s configured temperature for this run.

Source

pub fn max_tokens(self, max_tokens: u64) -> Self

Override the maximum completion token count for this run.

Source

pub fn merge_additional_params(self, params: Map<String, Value>) -> Self

Shallow-merge object fields into the provider-specific parameters for this run. Later fields win. A non-object baseline is replaced by the supplied object. A later completion-call hook patch has final precedence: object values shallow-merge, while a non-object on either side causes wholesale replacement by the hook value.

Source

pub fn options(self, options: GenerationOptions) -> Self

Overlay options on the agent’s generation options for this run: each field options sets wins, every other field keeps the agent’s (GenerationOptions::overlay). A policy options sets wins too, so a run can restore OnUnsupported::Error over an agent’s Ignore.

Calls apply in order: this overlays only the fields options sets, so it wins over a shortcut such as Self::seed called before it for those fields, and a shortcut called after it sets its one field on top.

Source

pub fn reasoning(self, reasoning: impl Into<Reasoning>) -> Self

Set the reasoning level or budget in this run’s generation options, as GenerationOptions::reasoning does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn cache(self, cache: CacheRetention) -> Self

Set the cache retention in this run’s generation options, as GenerationOptions::cache does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn service_tier(self, tier: ServiceTier) -> Self

Set the service tier in this run’s generation options, as GenerationOptions::service_tier does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn verbosity(self, verbosity: Verbosity) -> Self

Set the answer verbosity in this run’s generation options, as GenerationOptions::verbosity does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn parallel_tool_calls(self, parallel: bool) -> Self

Set whether the model may call several tools in one turn in this run’s generation options, as GenerationOptions::parallel_tool_calls does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn top_p(self, top_p: f64) -> Self

Set the nucleus sampling probability mass in this run’s generation options, as GenerationOptions::top_p does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn seed(self, seed: u64) -> Self

Set the sampling seed in this run’s generation options, as GenerationOptions::seed does, keeping its other fields. See Self::options for the order of calls.

Source

pub fn on_unsupported(self, policy: OnUnsupported) -> Self

Set what happens to an option the wire or model cannot honour in this run’s generation options, as GenerationOptions::on_unsupported does, keeping its other fields. See Self::options for the order of calls.

Each call is checked by the model it goes to, when that model encodes it, against the catalog spec the model was connected with: a refused option fails the run under Error with nothing sent, and is dropped with a warning under Ignore. A model a run switches to checks its own calls the same way. To see every refusal before a run starts, call DynModel::check on the model.

Source

pub fn stop<S: Into<String>>(self, stop: impl IntoIterator<Item = S>) -> Self

Set the stop sequences in this run’s generation options, keeping its other fields: the same as .options(GenerationOptions::new().stop(stop)). As with that overlay, an empty list means “not set” and keeps the agent’s stop sequences; it does not clear them. See Self::options for the order of calls.

Source

pub fn provider_options(self, options: ProviderOptions) -> Self

Overlay options on the agent’s provider options for this run: each provider entry options holds replaces the agent’s, every other entry keeps the agent’s (ProviderOptions::overlay).

Unlike AgentBuilder::provider_options, it merges rather than replaces, so calls apply in order without loss: an entry set by an earlier Self::provider_option is kept unless options holds an entry for the same provider, and a later Self::provider_option replaces its provider’s entry on top.

Source

pub fn provider_option<E: ExtensionOptions>(self, options: E) -> Self

Store options as the entry of their provider (ExtensionOptions::Ext) for this run, in place of the agent’s entry for that provider; every other entry keeps the agent’s. The same as .provider_options(ProviderOptions::new().set(options)), so options that write no field hold no entry and keep the agent’s entry for that provider. Options that do not serialize fail each request’s encode. See Self::provider_options for the order of calls. A third-party provider reusing a built-in options type needs ProviderOptions::with::<P> and Self::provider_options: this stores under the built-in key.

Source

pub fn tool_choice(self, tool_choice: ToolChoice) -> Self

Override the tool-choice policy for this run.

Source

pub fn record_content_telemetry(self, enabled: bool) -> Self

Opt in or out of recording sensitive request, response, and tool content on GenAI telemetry spans for this run.

Defaults to the agent’s setting, which defaults to false. Enabling this can expose prompts, retrieved context, tool results, model responses, the tool definitions sent with each completion (gen_ai.tool.definitions), and other sensitive or high-cardinality data through OpenTelemetry span attributes, which can increase observability backend storage and query costs. Only enable it when content telemetry is acceptable for this run. Structural metadata and token usage remain available when disabled.

Source

pub fn accept_unknown_finish_reasons(self, accept: bool) -> Self

Accept finish reasons outside the normalized vocabulary (FinishReason::Other) as a normal stop, for this run. Off by default: such a turn fails the run, and history replay leaves it out. When on, the turn succeeds, its tool calls run, and it replays.

Other also holds genuine failures, such as Gemini’s MALFORMED_FUNCTION_CALL and RECITATION or Bedrock’s malformed_tool_use, so tool calls from a malformed reply may run. Filtered content still fails the turn.

Source

pub fn tool_concurrency(self, concurrency: usize) -> Self

Limit concurrent tool calls in awaited and streamed runs. Defaults to one; zero is clamped to one. Sequential execution follows call order and stops at the first terminating error; concurrent hooks and side effects may interleave. Committed history always retains call order.

Streams emit model tool calls when the turn commits. Execution confirmations and results appear in call order only after the whole batch succeeds; execution confirmations exclude calls whose bodies did not run.

Source

pub fn ordered_by_footprint(self, ordered: bool) -> Self

Order the tool calls of one reply by what each touches, for this run: a call waits to start until every earlier call of its reply that it conflicts with has settled (Touches::must_wait), and a waiting call holds no tool_concurrency slot, so later calls that conflict with nothing unsettled before them start beside it. A call’s footprint is what its tool says of it (Tool::footprint), read from the arguments the model sent, so a dispatch hook that rewrites them does not change whom the call waits for. A tool that cannot say may change anything (Touches::default). Off by default: calls start in call order as slots free up. The setting is not saved with the run.

Source

pub fn max_invalid_tool_call_retries(self, retries: usize) -> Self

Set the retry budget for invalid tool-call recovery. Invalid tool-call retries also consume the total model-call budget.

Source

pub fn max_consecutive_malformed_tool_calls( self, limit: impl Into<Option<usize>>, ) -> Self

Set how many consecutive turns may call a tool with arguments that are not a JSON object. Each such call is answered with feedback, or as the invalid-call hook decides; a turn whose calls all parse resets the count. Past the limit the run fails. None, the default, sets no limit. A resumed run keeps the limit it persisted.

Source§

impl AgentRunner

Source

pub fn run( self, ) -> impl Future<Output = Result<PromptResponse, PromptError>> + WasmCompatSend

Drive the agent loop to completion, returning the aggregated PromptResponse. Hooks fire at every observable point; the first hook to terminate cancels the run. The run belongs to the span this method (or .await) was called in, wherever the future is polled.

Source§

impl AgentRunner

Source

pub fn stream(self) -> StreamingResult

Drive the agent loop as a stream of assistant content, tool activity and, last, the FinalResponse. Hooks fire at every observable point, including streamed text and tool-call deltas.

Like run, this is lazy: agent span creation begins only when the stream is first polled, and a stream that is dropped unpolled has done nothing. The stream is Send on native targets, so it can be built in synchronous code and handed to whatever polls it; it runs under the span it was built in (a caller’s enabled span is adopted, otherwise a root invoke_agent is created), not under whichever span first polls it.

fn start(agent: &Agent, prompt: &str) -> StreamingResult {
    // Nothing runs until whoever holds this polls it.
    agent.prompt(prompt).stream()
}

Shares the drive loop, run construction, tool execution and fail-closed hook handling with the blocking run via drive_agent, so the two behave identically apart from the streamed delta events.

Source§

impl AgentRunner

Source

pub fn run_channel( self, ) -> (impl Future<Output = Result<PromptResponse, PromptError>> + WasmCompatSend, RunEvents)

Split the run into a driving future and a RunEvents feed.

The future performs the same agent loop as run and stream, and resolves with the final PromptResponse; the feed receives each intermediate MultiTurnStreamItem as it happens. Spawn the future on any executor and poll the feed from wherever the events are consumed; neither side assumes a runtime.

The feed is bounded (RUN_EVENTS_CAPACITY); when it is full the run waits for the consumer rather than dropping events. Dropping the feed lets the run continue to completion unobserved. Like stream, the run belongs to the span this method was called in, wherever the future is later polled.

Source§

impl<T> AgentRunner<TypedOutput<T>>

Source

pub fn retries(self, retries: usize) -> Self

Retry a failed attempt up to retries more times. An attempt fails when the run errors, produces no output, or produces output that does not parse as T. Usage accumulates across attempts.

Trait Implementations§

Source§

impl<O: Clone> Clone for AgentRunner<O>

Source§

fn clone(&self) -> Self

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

impl IntoFuture for AgentRunner

.awaiting a runner is run.

Source§

type Output = Result<PromptResponse, PromptError>

The output that the future will produce on completion.
Source§

type IntoFuture = Pin<Box<dyn Future<Output = <AgentRunner as IntoFuture>::Output> + Send>>

Which kind of future are we turning this into?
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

§

impl<O = ()> !RefUnwindSafe for AgentRunner<O>

§

impl<O = ()> !UnwindSafe for AgentRunner<O>

§

impl<O> Forget for AgentRunner<O>

§

impl<O> Freeze for AgentRunner<O>
where O: Freeze,

§

impl<O> Move for AgentRunner<O>

§

impl<O> Send for AgentRunner<O>
where O: Send,

§

impl<O> Sync for AgentRunner<O>
where O: Sync,

§

impl<O> Unpin for AgentRunner<O>
where O: Unpin,

§

impl<O> UnsafeUnpin for AgentRunner<O>
where O: UnsafeUnpin,

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.

Source§

impl<T> Instrument for T

Source§

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

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

fn in_current_span(self) -> Instrumented<Self> ⓘ

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

impl<T> Instrument for T

Source§

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

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

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

Source§

type Output = T

Should always be Self
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 = !

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.
Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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