rig_agent/agent/runner.rs
1//! Hook-aware execution of [`AgentRun`] with per-run overrides, completion
2//! requests and tools.
3//!
4//! ```rust,no_run
5//! # use rig_agent::Agent;
6//! # async fn example(agent: Agent) -> Result<(), Box<dyn std::error::Error>> {
7//! let response = agent
8//! .prompt("What is 2 + 2?")
9//! .max_turns(3)
10//! .run()
11//! .await?;
12//! println!("{}", response.output());
13//! # Ok(())
14//! # }
15//! ```
16
17use std::sync::{Arc, Mutex};
18
19use futures::StreamExt;
20use tracing_futures::Instrument;
21
22use super::{
23 completion::{Agent, AgentConfig},
24 engine::{DriveItem, UnaryTurnSource, drive_agent},
25 hook::{AgentHook, HookContext},
26 telemetry::acquire_agent_span,
27};
28use crate::run::{AgentRun, response::PromptResponse, spec::UnhandledInvalidToolCall};
29use rig_core::error::ProviderError;
30use rig_core::{completion::ModelRef, message::ToolChoice};
31
32use crate::{
33 completion::{Document, Message, PromptError, Usage},
34 tool::{ToolContext, server::ToolServerHandle},
35};
36
37use super::UNKNOWN_AGENT_NAME;
38
39/// A hook-aware driver over [`AgentRun`].
40///
41/// Construct one with [`Agent::prompt`] (a fresh run) or [`Agent::resume`]
42/// (a persisted one), attach hooks with [`add_hook`](Self::add_hook), then
43/// call [`run`](Self::run) (blocking), [`stream`](Self::stream)
44/// (incremental) or [`run_channel`](Self::run_channel) (a future plus an
45/// event feed). Hooks are held in a [`HookStack`](super::hook::HookStack), an ordered,
46/// runtime-composable list; `run()` and `stream()` share the same loop and fire
47/// the same events, so they behave identically apart from the streamed delta
48/// events the medium adds.
49///
50/// `O` is what `.await` recovers: `()` for the raw [`PromptResponse`], or a
51/// [`TypedOutput`](super::TypedOutput) for a [`TypedRun`](super::TypedRun).
52#[derive(Clone)]
53#[must_use = "a run does nothing until awaited or driven"]
54pub struct AgentRunner<O = ()> {
55 /// Run-local configuration; overrides never mutate the source agent.
56 pub(crate) config: AgentConfig,
57 /// Where the run starts: a prompt ([`Agent::prompt`]) or a persisted
58 /// run to continue ([`Agent::resume`]).
59 pub(crate) origin: RunOrigin,
60 pub(crate) chat_history: Option<Vec<Arc<Message>>>,
61 pub(crate) tool_server_handle: ToolServerHandle,
62 /// Typed context cloned freshly for every tool dispatch.
63 pub(crate) tool_context: ToolContext,
64 pub(crate) concurrency: usize,
65 /// Whether a tool call waits for the earlier calls of its reply it
66 /// conflicts with ([`ordered_by_footprint`](Self::ordered_by_footprint)).
67 pub(crate) ordered: bool,
68 pub(crate) error_usage: Option<Arc<Mutex<Usage>>>,
69 pub(crate) output: O,
70}
71
72/// Where a run starts. A prompt builds a fresh [`AgentRun`]; a persisted run
73/// is continued as it is, so neither a prompt nor a history applies to it.
74#[derive(Clone)]
75pub(crate) enum RunOrigin {
76 Prompt(Message),
77 Resume(AgentRun),
78}
79
80impl AgentRunner {
81 /// Build a runner from an agent, seeding it with the agent's default hook
82 /// stack. The one construction site behind [`Agent::prompt`] and the
83 /// typed and extractor runs.
84 pub(crate) fn from_agent(agent: &Agent, prompt: impl Into<Message>) -> Self {
85 Self::new(agent, RunOrigin::Prompt(prompt.into()))
86 }
87
88 /// Build a runner that continues `run` ([`Agent::resume`]).
89 pub(crate) fn resuming(agent: &Agent, run: AgentRun) -> Self {
90 Self::new(agent, RunOrigin::Resume(run))
91 }
92
93 fn new(agent: &Agent, origin: RunOrigin) -> Self {
94 Self {
95 config: agent.config.clone(),
96 origin,
97 chat_history: None,
98 tool_server_handle: agent.tool_server_handle.clone(),
99 tool_context: ToolContext::new(),
100 concurrency: 1,
101 ordered: false,
102 error_usage: None,
103 output: (),
104 }
105 }
106
107 /// Configure the synthetic tool used by an internal Tool-output flow.
108 pub(crate) fn output_tool(
109 mut self,
110 name: impl Into<String>,
111 description: impl Into<String>,
112 augment_preamble: bool,
113 ) -> Self {
114 let spec = self.config.spec_mut();
115 spec.output_tool_name = Some(name.into());
116 spec.output_tool_description = Some(description.into());
117 spec.augment_output_preamble = augment_preamble;
118 self
119 }
120
121 /// Set the policy for invalid tool calls that no hook resolves. A resumed
122 /// run keeps the policy it persisted.
123 pub fn unhandled_invalid_tool_call(mut self, policy: UnhandledInvalidToolCall) -> Self {
124 self.config.spec_mut().unhandled_invalid_tool_call = policy;
125 self
126 }
127}
128
129impl<O> AgentRunner<O> {
130 /// Append a hook to the stack (on top of any the agent already carries).
131 /// Hooks run in registration order; how their results compose is
132 /// event-dependent (model selections and `ToolCall`/`ToolResult` rewrites
133 /// chain, `CompletionCall` request patches accumulate and merge, while
134 /// model-turn steering and observe-only/recovery events use their
135 /// event-specific terminal action). See the [`hook`](crate::agent::hook)
136 /// module docs.
137 pub fn add_hook<H>(mut self, hook: H) -> Self
138 where
139 H: AgentHook + 'static,
140 {
141 self.config.hooks.push(hook);
142 self
143 }
144
145 /// Set the total model-call budget, including the initial call and every
146 /// retry or continuation. Zero emits no model calls; one permits only the
147 /// initial call. Exceeding the budget returns [`PromptError::MaxTurns`],
148 /// which a typed run wraps in
149 /// [`StructuredOutputError::Prompt`](crate::completion::StructuredOutputError::Prompt).
150 pub fn max_turns(mut self, max_turns: usize) -> Self {
151 self.config.spec_mut().max_turns = Some(max_turns);
152 self
153 }
154
155 /// Keep this run's conversation in `store`, in place of the agent's
156 /// ([`AgentBuilder::memory`](super::AgentBuilder::memory)), such as a
157 /// store chosen per request; one store also holds every user's
158 /// conversation, a log each ([`conversation`](Self::conversation)).
159 pub fn memory(
160 mut self,
161 store: impl rig_memory::AsyncStore
162 + rig_core::wasm_compat::WasmCompatSend
163 + rig_core::wasm_compat::WasmCompatSync
164 + 'static,
165 ) -> Self {
166 self.config.memory = Some(super::memory::Memory::new(store));
167 self
168 }
169
170 /// The log of the memory store this run loads and saves
171 /// ([`AgentBuilder::conversation`](super::AgentBuilder::conversation)).
172 pub fn conversation(mut self, log: impl Into<String>) -> Self {
173 self.config.conversation = Some(log.into());
174 self
175 }
176
177 /// The store and log this run keeps its conversation in: none without a
178 /// store, or with an explicit [`history`](AgentRunner::history).
179 pub(crate) fn memory_log(&self) -> Option<(super::memory::Memory, String)> {
180 let memory = self
181 .config
182 .memory
183 .clone()
184 .filter(|_| self.chat_history.is_none())?;
185 let log = self
186 .config
187 .conversation
188 .as_ref()
189 .or(self.config.name.as_ref());
190 Some((memory, log.map_or_else(|| "agent".to_owned(), Clone::clone)))
191 }
192
193 /// Set the default model candidate for this run.
194 ///
195 /// This does not suppress registered model-selection hooks, which may
196 /// replace the candidate before each model call (including retries).
197 /// Append an unconditional selecting hook last when the run must always
198 /// use one model.
199 pub fn using_model(mut self, label: impl Into<ModelRef>) -> Self {
200 self.config.select_model_label(label.into());
201 self
202 }
203
204 /// Register `model` in the agent's table under a generated label and use
205 /// it as this run's default. The registration is scoped to this runner
206 /// and the run it produces: it leaves the table when they drop.
207 pub fn using_model_value(
208 mut self,
209 model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
210 ) -> Self {
211 self.config.select_anonymous_model(model);
212 self
213 }
214
215 /// Set the typed context cloned for every tool dispatch in this run.
216 pub fn tool_context(mut self, context: ToolContext) -> Self {
217 self.tool_context = context;
218 self
219 }
220
221 /// Set the chat history preceding the prompt. The run then neither
222 /// loads nor saves a memory store's conversation.
223 pub fn history<I, T>(mut self, history: I) -> Self
224 where
225 I: IntoIterator<Item = T>,
226 T: Into<Message>,
227 {
228 let history = history.into_iter().map(|message| Arc::new(message.into()));
229 self.chat_history = Some(history.collect());
230 self
231 }
232
233 /// Override the agent preamble for this run.
234 pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
235 self.config.spec_mut().preamble = Some(preamble.into());
236 self
237 }
238
239 /// Remove the agent's configured preamble for this run.
240 pub fn without_preamble(mut self) -> Self {
241 self.config.spec_mut().preamble = None;
242 self
243 }
244
245 /// Append one static context document for this run.
246 pub fn document(mut self, document: Document) -> Self {
247 self.config.spec_mut().static_context.push(document);
248 self
249 }
250
251 /// Append static context documents for this run.
252 pub fn documents(mut self, documents: impl IntoIterator<Item = Document>) -> Self {
253 self.config.spec_mut().static_context.extend(documents);
254 self
255 }
256
257 /// Override the model temperature for this run.
258 pub fn temperature(mut self, temperature: f64) -> Self {
259 self.config.spec_mut().temperature = Some(temperature);
260 self
261 }
262
263 /// Remove the agent's configured temperature for this run.
264 pub fn without_temperature(mut self) -> Self {
265 self.config.spec_mut().temperature = None;
266 self
267 }
268
269 /// Override the maximum completion token count for this run.
270 pub fn max_tokens(mut self, max_tokens: u64) -> Self {
271 self.config.spec_mut().max_tokens = Some(max_tokens);
272 self
273 }
274
275 /// Shallow-merge object fields into the provider-specific parameters for
276 /// this run. Later fields win. A non-object baseline is replaced by the
277 /// supplied object. A later completion-call hook patch has final
278 /// precedence: object values shallow-merge, while a non-object on either
279 /// side causes wholesale replacement by the hook value.
280 pub fn merge_additional_params(
281 mut self,
282 params: serde_json::Map<String, serde_json::Value>,
283 ) -> Self {
284 let params = serde_json::Value::Object(params);
285 self.config.spec_mut().additional_params =
286 Some(match self.config.spec_mut().additional_params.take() {
287 Some(baseline) if baseline.is_object() => {
288 crate::json_utils::merge(baseline, params)
289 }
290 _ => params,
291 });
292 self
293 }
294
295 /// Overlay `options` on the agent's generation options for this run:
296 /// each field `options` sets wins, every other field keeps the agent's
297 /// ([`GenerationOptions::overlay`](rig_core::completion::GenerationOptions::overlay)).
298 /// A policy `options` sets wins too, so a run can restore
299 /// [`OnUnsupported::Error`](rig_core::completion::OnUnsupported::Error)
300 /// over an agent's `Ignore`.
301 ///
302 /// Calls apply in order: this overlays only the fields `options` sets,
303 /// so it wins over a shortcut such as [`Self::seed`] called before it
304 /// for those fields, and a shortcut called after it sets its one field
305 /// on top.
306 pub fn options(mut self, options: rig_core::completion::GenerationOptions) -> Self {
307 self.config.spec_mut().options = self.config.spec.options.clone().overlay(&options);
308 self
309 }
310
311 generation_option_setters!("this run's");
312
313 /// Set the stop sequences in this run's generation options, keeping its
314 /// other fields: the same as
315 /// `.options(GenerationOptions::new().stop(stop))`. As with that overlay,
316 /// an empty list means "not set" and keeps the agent's stop sequences;
317 /// it does not clear them. See [`Self::options`] for the order of calls.
318 pub fn stop<S: Into<String>>(self, stop: impl IntoIterator<Item = S>) -> Self {
319 self.options(rig_core::completion::GenerationOptions::new().stop(stop))
320 }
321
322 /// Overlay `options` on the agent's provider options for this run: each
323 /// provider entry `options` holds replaces the agent's, every other
324 /// entry keeps the agent's
325 /// ([`ProviderOptions::overlay`](rig_core::completion::ProviderOptions::overlay)).
326 ///
327 /// Unlike [`AgentBuilder::provider_options`](crate::agent::AgentBuilder::provider_options),
328 /// it merges rather than replaces, so calls apply in order without
329 /// loss: an entry set by an earlier [`Self::provider_option`] is kept
330 /// unless `options` holds an entry for the same provider, and a later
331 /// [`Self::provider_option`] replaces its provider's entry on top.
332 pub fn provider_options(mut self, options: rig_core::completion::ProviderOptions) -> Self {
333 self.config.spec_mut().provider_options =
334 self.config.spec.provider_options.clone().overlay(&options);
335 self
336 }
337
338 /// Store `options` as the entry of their provider
339 /// ([`ExtensionOptions::Ext`](rig_core::completion::ExtensionOptions::Ext))
340 /// for this run, in place of the agent's entry for that provider; every
341 /// other entry keeps the agent's. The same as
342 /// `.provider_options(ProviderOptions::new().set(options))`, so options
343 /// that write no field hold no entry and keep the agent's entry for
344 /// that provider. Options that do not serialize fail each request's
345 /// encode. See [`Self::provider_options`] for the order of calls. A
346 /// third-party provider reusing a built-in options type needs
347 /// [`ProviderOptions::with::<P>`](rig_core::completion::ProviderOptions::with)
348 /// and [`Self::provider_options`]: this stores under the built-in key.
349 pub fn provider_option<E: rig_core::completion::ExtensionOptions>(self, options: E) -> Self {
350 self.provider_options(rig_core::completion::ProviderOptions::new().set(options))
351 }
352
353 /// Override the tool-choice policy for this run.
354 pub fn tool_choice(mut self, tool_choice: ToolChoice) -> Self {
355 self.config.spec_mut().tool_choice = Some(tool_choice);
356 self
357 }
358
359 /// Opt in or out of recording sensitive request, response, and tool content
360 /// on GenAI telemetry spans for this run.
361 ///
362 /// Defaults to the agent's setting, which defaults to `false`. Enabling this
363 /// can expose prompts, retrieved context, tool results, model responses, the
364 /// tool definitions sent with each completion (`gen_ai.tool.definitions`),
365 /// and other sensitive or high-cardinality data through OpenTelemetry span
366 /// attributes, which can increase observability backend storage and query
367 /// costs. Only enable it when content telemetry is acceptable for this run.
368 /// Structural metadata and token usage remain available when disabled.
369 pub fn record_content_telemetry(mut self, enabled: bool) -> Self {
370 self.config.record_telemetry_content = enabled;
371 self
372 }
373
374 /// Accept finish reasons outside the normalized vocabulary
375 /// ([`FinishReason::Other`](rig_core::completion::FinishReason::Other))
376 /// as a normal stop, for this run. Off by default: such a turn fails the run,
377 /// and history replay leaves it out. When on, the turn succeeds, its
378 /// tool calls run, and it replays.
379 ///
380 /// `Other` also holds genuine failures, such as Gemini's
381 /// `MALFORMED_FUNCTION_CALL` and `RECITATION` or Bedrock's
382 /// `malformed_tool_use`, so tool calls from a malformed reply may run.
383 /// Filtered content still fails the turn.
384 pub fn accept_unknown_finish_reasons(mut self, accept: bool) -> Self {
385 self.config.spec_mut().accept_unknown_finish_reasons = accept;
386 self
387 }
388
389 /// Limit concurrent tool calls in awaited and streamed runs. Defaults to one;
390 /// zero is clamped to one. Sequential execution follows call order and stops
391 /// at the first terminating error; concurrent hooks and side effects may interleave.
392 /// Committed history always retains call order.
393 ///
394 /// Streams emit model tool calls when the turn commits. Execution confirmations
395 /// and results appear in call order only after the whole batch succeeds;
396 /// execution confirmations exclude calls whose bodies did not run.
397 pub fn tool_concurrency(mut self, concurrency: usize) -> Self {
398 self.concurrency = concurrency.max(1);
399 self
400 }
401
402 /// Order the tool calls of one reply by what each touches, for this run:
403 /// a call waits to start until every earlier call of its reply that it
404 /// conflicts with has settled ([`Touches::must_wait`]), and a waiting
405 /// call holds no [`tool_concurrency`](Self::tool_concurrency) slot, so
406 /// later calls that conflict with nothing unsettled before them start
407 /// beside it. A call's footprint is what its tool says of it
408 /// ([`Tool::footprint`](crate::tool::Tool::footprint)), read from the
409 /// arguments the model sent, so a dispatch hook that rewrites them does
410 /// not change whom the call waits for. A tool that cannot say may change
411 /// anything ([`Touches::default`]). Off by default: calls start in call order
412 /// as slots free up. The setting is not saved with the run.
413 ///
414 /// [`Touches::must_wait`]: rig_core::tool::Touches::must_wait
415 /// [`Touches::default`]: rig_core::tool::Touches::default
416 pub fn ordered_by_footprint(mut self, ordered: bool) -> Self {
417 self.ordered = ordered;
418 self
419 }
420
421 /// Set the retry budget for invalid tool-call recovery. Invalid tool-call
422 /// retries also consume the total model-call budget.
423 pub fn max_invalid_tool_call_retries(mut self, retries: usize) -> Self {
424 self.config.spec_mut().max_invalid_tool_call_retries = retries;
425 self
426 }
427
428 /// Set how many consecutive turns may call a tool with arguments that are
429 /// not a JSON object. Each such call is answered with feedback, or as the
430 /// invalid-call hook decides; a turn whose calls all parse resets the
431 /// count. Past the limit the run fails. `None`, the default, sets no
432 /// limit. A resumed run keeps the limit it persisted.
433 pub fn max_consecutive_malformed_tool_calls(mut self, limit: impl Into<Option<usize>>) -> Self {
434 self.config.spec_mut().max_consecutive_malformed_tool_calls = limit.into();
435 self
436 }
437
438 /// This runner recovering `output` instead, and the output it replaced.
439 pub(crate) fn replace_output<P>(self, output: P) -> (AgentRunner<P>, O) {
440 let Self {
441 config,
442 origin,
443 chat_history,
444 tool_server_handle,
445 tool_context,
446 concurrency,
447 ordered,
448 error_usage,
449 output: replaced,
450 } = self;
451 let runner = AgentRunner {
452 config,
453 origin,
454 chat_history,
455 tool_server_handle,
456 tool_context,
457 concurrency,
458 ordered,
459 error_usage,
460 output,
461 };
462 (runner, replaced)
463 }
464
465 pub(crate) fn agent_name_or_default(&self) -> &str {
466 self.config.name.as_deref().unwrap_or(UNKNOWN_AGENT_NAME)
467 }
468
469 /// The [`AgentRun`] this runner drives: the persisted run it continues,
470 /// or a fresh one from its prompt and configuration. The one construction
471 /// site, so the blocking and streaming drivers configure runs identically.
472 pub(crate) fn build_run(&self) -> AgentRun {
473 let prompt = match &self.origin {
474 RunOrigin::Resume(run) => return run.clone(),
475 RunOrigin::Prompt(prompt) => prompt.clone(),
476 };
477 AgentRun::from_spec(&self.config.spec, prompt, self.chat_history.clone())
478 }
479}
480
481impl AgentRunner {
482 /// [`run_under`](Self::run_under) that also reports the usage a failed
483 /// run consumed; `ambient` is the span the typed run was started in.
484 pub(crate) async fn run_with_error_usage(
485 mut self,
486 ambient: tracing::Span,
487 ) -> (Result<PromptResponse, PromptError>, Usage) {
488 let usage = Arc::new(Mutex::new(Usage::default()));
489 self.error_usage = Some(usage.clone());
490 let result = self.run_under(ambient).await;
491 let observed = result
492 .as_ref()
493 .map_or_else(|_| *crate::lock(&usage), |response| response.usage);
494 (result, observed)
495 }
496
497 /// Open the per-run agent span, recording the prompt when content
498 /// telemetry is enabled. Shared by the blocking and streaming surfaces.
499 pub(crate) fn open_agent_span(&self, ambient: tracing::Span) -> (tracing::Span, bool) {
500 let (agent_span, created_agent_span) = acquire_agent_span(
501 ambient,
502 self.agent_name_or_default(),
503 self.config.spec.preamble.as_deref(),
504 self.config.record_telemetry_content,
505 );
506
507 // A resumed run's prompt is inside its state: the span records none.
508 if self.config.record_telemetry_content
509 && let RunOrigin::Prompt(prompt) = &self.origin
510 && let Some(text) = prompt.rag_text()
511 {
512 agent_span.record("gen_ai.prompt", text);
513 }
514
515 (agent_span, created_agent_span)
516 }
517
518 /// The run-scoped hook context: minted once per run, shared by every
519 /// hook event.
520 pub(crate) fn hook_context(&self, is_streaming: bool) -> HookContext {
521 HookContext::new(is_streaming, self.config.handlers.clone())
522 }
523
524 /// Drive the agent loop to completion, returning the aggregated
525 /// [`PromptResponse`]. Hooks fire at every observable point; the first hook
526 /// to terminate cancels the run. The run belongs to the span this method
527 /// (or `.await`) was called in, wherever the future is polled.
528 pub fn run(
529 self,
530 ) -> impl Future<Output = Result<PromptResponse, PromptError>> + rig_core::wasm_compat::WasmCompatSend
531 {
532 // Like `stream()`: the run belongs to the span it was started in,
533 // not to whichever task first polls the future.
534 let ambient = tracing::Span::current();
535 let run_under = ambient.clone();
536 async move { self.run_under(run_under).await }.instrument(ambient)
537 }
538
539 async fn run_under(self, ambient: tracing::Span) -> Result<PromptResponse, PromptError> {
540 // Boxed, so the futures awaiting the run stay small.
541 let mut driver = Box::pin(drive_agent(self, UnaryTurnSource::default(), ambient));
542 let mut response = None;
543 while let Some(item) = driver.next().await {
544 match item {
545 Ok(DriveItem::Done(done)) => response = Some(done),
546 Ok(DriveItem::Surfaced(_) | DriveItem::Live(_) | DriveItem::Projected(_)) => {}
547 Err(err) => {
548 // Drain through termination so engine teardown completes
549 // rather than being dropped at the error yield.
550 while driver.next().await.is_some() {}
551 return Err(err);
552 }
553 }
554 }
555 response.ok_or_else(no_final_response)
556 }
557}
558
559/// `.await`ing a runner is [`run`](AgentRunner::run).
560impl std::future::IntoFuture for AgentRunner {
561 type Output = Result<PromptResponse, PromptError>;
562 type IntoFuture = rig_core::wasm_compat::WasmBoxedFuture<'static, Self::Output>;
563
564 fn into_future(self) -> Self::IntoFuture {
565 Box::pin(self.run())
566 }
567}
568
569/// The error of a run that ended without a final response.
570pub(crate) fn no_final_response() -> PromptError {
571 PromptError::Provider(ProviderError::Response(
572 "agent run ended without producing a final response".to_string(),
573 ))
574}
575
576#[cfg(test)]
577mod empty_turn_tests;
578#[cfg(test)]
579mod entry_tests;
580#[cfg(test)]
581mod ignore_tests;
582#[cfg(test)]
583mod settled_tests;
584#[cfg(test)]
585mod tests;
586
587#[cfg(test)]
588pub(crate) mod prompt_tests;