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
impl AgentRunner
Sourcepub fn unhandled_invalid_tool_call(
self,
policy: UnhandledInvalidToolCall,
) -> Self
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>
impl<O> AgentRunner<O>
Sourcepub fn add_hook<H>(self, hook: H) -> Selfwhere
H: AgentHook + 'static,
pub fn add_hook<H>(self, hook: H) -> Selfwhere
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.
Sourcepub fn max_turns(self, max_turns: usize) -> Self
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.
Sourcepub fn memory(
self,
store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
) -> Self
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).
Sourcepub fn conversation(self, log: impl Into<String>) -> Self
pub fn conversation(self, log: impl Into<String>) -> Self
The log of the memory store this run loads and saves
(AgentBuilder::conversation).
Sourcepub fn using_model(self, label: impl Into<ModelRef>) -> Self
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.
Sourcepub fn using_model_value(self, model: impl Into<DynModel<Completion>>) -> Self
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.
Sourcepub fn tool_context(self, context: ToolContext) -> Self
pub fn tool_context(self, context: ToolContext) -> Self
Set the typed context cloned for every tool dispatch in this run.
Sourcepub fn history<I, T>(self, history: I) -> Self
pub fn history<I, T>(self, history: I) -> Self
Set the chat history preceding the prompt. The run then neither loads nor saves a memory store’s conversation.
Sourcepub fn preamble(self, preamble: impl Into<String>) -> Self
pub fn preamble(self, preamble: impl Into<String>) -> Self
Override the agent preamble for this run.
Sourcepub fn without_preamble(self) -> Self
pub fn without_preamble(self) -> Self
Remove the agent’s configured preamble for this run.
Sourcepub fn document(self, document: Document) -> Self
pub fn document(self, document: Document) -> Self
Append one static context document for this run.
Sourcepub fn documents(self, documents: impl IntoIterator<Item = Document>) -> Self
pub fn documents(self, documents: impl IntoIterator<Item = Document>) -> Self
Append static context documents for this run.
Sourcepub fn temperature(self, temperature: f64) -> Self
pub fn temperature(self, temperature: f64) -> Self
Override the model temperature for this run.
Sourcepub fn without_temperature(self) -> Self
pub fn without_temperature(self) -> Self
Remove the agent’s configured temperature for this run.
Sourcepub fn max_tokens(self, max_tokens: u64) -> Self
pub fn max_tokens(self, max_tokens: u64) -> Self
Override the maximum completion token count for this run.
Sourcepub fn merge_additional_params(self, params: Map<String, Value>) -> Self
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.
Sourcepub fn options(self, options: GenerationOptions) -> Self
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.
Sourcepub fn reasoning(self, reasoning: impl Into<Reasoning>) -> Self
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.
Sourcepub fn cache(self, cache: CacheRetention) -> Self
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.
Sourcepub fn service_tier(self, tier: ServiceTier) -> Self
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.
Sourcepub fn verbosity(self, verbosity: Verbosity) -> Self
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.
Sourcepub fn parallel_tool_calls(self, parallel: bool) -> Self
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.
Sourcepub fn top_p(self, top_p: f64) -> Self
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.
Sourcepub fn seed(self, seed: u64) -> Self
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.
Sourcepub fn on_unsupported(self, policy: OnUnsupported) -> Self
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.
Sourcepub fn stop<S: Into<String>>(self, stop: impl IntoIterator<Item = S>) -> Self
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.
Sourcepub fn provider_options(self, options: ProviderOptions) -> Self
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.
Sourcepub fn provider_option<E: ExtensionOptions>(self, options: E) -> Self
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.
Sourcepub fn tool_choice(self, tool_choice: ToolChoice) -> Self
pub fn tool_choice(self, tool_choice: ToolChoice) -> Self
Override the tool-choice policy for this run.
Sourcepub fn record_content_telemetry(self, enabled: bool) -> Self
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.
Sourcepub fn accept_unknown_finish_reasons(self, accept: bool) -> Self
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.
Sourcepub fn tool_concurrency(self, concurrency: usize) -> Self
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.
Sourcepub fn ordered_by_footprint(self, ordered: bool) -> Self
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.
Sourcepub fn max_invalid_tool_call_retries(self, retries: usize) -> Self
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.
Sourcepub fn max_consecutive_malformed_tool_calls(
self,
limit: impl Into<Option<usize>>,
) -> Self
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
impl AgentRunner
Sourcepub fn run(
self,
) -> impl Future<Output = Result<PromptResponse, PromptError>> + WasmCompatSend
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
impl AgentRunner
Sourcepub fn stream(self) -> StreamingResult
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
impl AgentRunner
Sourcepub fn run_channel(
self,
) -> (impl Future<Output = Result<PromptResponse, PromptError>> + WasmCompatSend, RunEvents)
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>>
impl<T> AgentRunner<TypedOutput<T>>
Trait Implementations§
Source§impl<O: Clone> Clone for AgentRunner<O>
impl<O: Clone> Clone for AgentRunner<O>
Source§impl IntoFuture for AgentRunner
.awaiting a runner is run.
impl IntoFuture for AgentRunner
.awaiting a runner is run.