rig-agent 0.43.0

Rig's classic agent runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Typed run outputs with optional retries for execution or deserialization failures.
//! Native prompting parses final text; extractors require an output-tool call.
//!
//! ```no_run
//! # async fn example(agent: rig_agent::Agent) -> Result<(), rig_agent::completion::StructuredOutputError> {
//! let response = agent.prompt_typed::<Vec<String>>("List three colors.").retries(1).await?;
//! assert_eq!(response.output.len(), 3);
//! # Ok(())
//! # }
//! ```

use std::{future::IntoFuture, marker::PhantomData};

use schemars::{JsonSchema, schema_for};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend};
use tracing_futures::Instrument;

use super::{
    Agent,
    hook::AgentHook,
    run::{OutputMode, spec::UnhandledInvalidToolCall},
    runner::AgentRunner,
};
use crate::{
    completion::{Message, StructuredOutputError, Usage},
    run::response::{CompletionCall, PromptResponse},
    tool::ToolContext,
};

/// A typed run's response: the deserialized value plus the run's usage and
/// completion calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypedPromptResponse<T> {
    /// The parsed structured output.
    pub output: T,
    /// Usage accumulated across every attempt, including attempts that
    /// received a billed response but failed to produce a parseable value.
    pub usage: Usage,
    /// Successfully completed completion requests made by the accepted attempt.
    ///
    /// `usage` remains the aggregate across the whole run. Use the last
    /// entry's usage to inspect the final completion request's prompt/context
    /// length. An entry whose counters are all `None` means the provider
    /// reported no usage metrics for that request.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub completion_calls: Vec<CompletionCall>,
    /// How the accepted attempt's conversation-memory append settled; see
    /// [`PromptResponse::memory_append`](crate::agent::PromptResponse::memory_append).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_append: Option<crate::run::MemoryAppend>,
}

impl<T> TypedPromptResponse<T> {
    /// A response of `output` with the run's `usage`.
    pub fn new(output: T, usage: Usage) -> Self {
        Self {
            output,
            usage,
            completion_calls: Vec::new(),
            memory_append: None,
        }
    }

    /// Attach completion call details to this response.
    pub fn with_completion_calls(mut self, completion_calls: Vec<CompletionCall>) -> Self {
        self.completion_calls = completion_calls;
        self
    }

    /// Returns successfully completed completion requests made by this agent run.
    ///
    /// An entry whose counters are all `None` means the provider reported no
    /// usage metrics for that request.
    pub fn completion_calls(&self) -> &[CompletionCall] {
        &self.completion_calls
    }

    /// Number of completion requests this agent run made.
    pub fn requests(&self) -> usize {
        self.completion_calls.len()
    }
}

/// How a [`TypedRun`] recovers `T` from the accepted [`PromptResponse`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TypedOutput {
    /// Parse the model's final text; tolerate prose or fences around the JSON.
    Native,
    /// The value is the arguments of the run's output tool call; the model not
    /// calling it is an empty response.
    OutputTool,
}

/// A run that deserializes its accepted output as `T`.
///
/// Configure it with the same setters as [`AgentRunner`], then `.await` it for
/// a [`TypedPromptResponse<T>`]. With a [`retries`](Self::retries) budget, a
/// failed attempt (run error, empty output, unparseable output) is retried
/// from scratch; usage accumulates across attempts.
#[must_use = "a typed run does nothing until awaited"]
pub struct TypedRun<T> {
    runner: AgentRunner,
    retries: u64,
    output: TypedOutput,
    _t: PhantomData<T>,
}

/// The setters that forward verbatim to the inner [`AgentRunner`].
macro_rules! forward_runner_setters {
    () => {
        /// Attach a per-call [`ToolContext`] for this run.
        ///
        /// Every tool the agent executes during this run can read the
        /// caller-provided values (auth tokens, session IDs, conversation state, …)
        /// through the tool's [`ToolContext`](crate::tool::ToolContext),
        /// without the model ever seeing them.
        pub fn tool_context(mut self, context: ToolContext) -> Self {
            self.runner = self.runner.tool_context(context);
            self
        }

        /// Add chat history to the run.
        pub fn history<H, Item>(mut self, history: H) -> Self
        where
            H: IntoIterator<Item = Item>,
            Item: Into<Message>,
        {
            self.runner = self.runner.history(history);
            self
        }

        /// Override the agent preamble for this run.
        pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
            self.runner = self.runner.preamble(preamble);
            self
        }

        /// Remove the agent's configured preamble for this run.
        pub fn without_preamble(mut self) -> Self {
            self.runner = self.runner.without_preamble();
            self
        }

        /// Append one static context document for this run.
        pub fn document(mut self, document: crate::completion::Document) -> Self {
            self.runner = self.runner.document(document);
            self
        }

        /// Append static context documents for this run.
        pub fn documents(
            mut self,
            documents: impl IntoIterator<Item = crate::completion::Document>,
        ) -> Self {
            self.runner = self.runner.documents(documents);
            self
        }

        /// Override the model temperature for this run.
        pub fn temperature(mut self, temperature: f64) -> Self {
            self.runner = self.runner.temperature(temperature);
            self
        }

        /// Remove the agent's configured temperature for this run.
        pub fn without_temperature(mut self) -> Self {
            self.runner = self.runner.without_temperature();
            self
        }

        /// Override the maximum completion token count for this run.
        pub fn max_tokens(mut self, max_tokens: u64) -> Self {
            self.runner = self.runner.max_tokens(max_tokens);
            self
        }

        /// Remove the agent's configured maximum token count for this run.
        pub fn without_max_tokens(mut self) -> Self {
            self.runner = self.runner.without_max_tokens();
            self
        }

        /// Shallow-merge object fields into the provider-specific parameters
        /// for this run. Later fields win.
        pub fn merge_additional_params(
            mut self,
            params: serde_json::Map<String, serde_json::Value>,
        ) -> Self {
            self.runner = self.runner.merge_additional_params(params);
            self
        }

        /// Replace all provider-specific parameters for this run.
        pub fn replace_additional_params(mut self, params: serde_json::Value) -> Self {
            self.runner = self.runner.replace_additional_params(params);
            self
        }

        /// Remove the agent's configured provider-specific parameters for this run.
        pub fn without_additional_params(mut self) -> Self {
            self.runner = self.runner.without_additional_params();
            self
        }

        /// Override the tool-choice policy for this run.
        pub fn tool_choice(mut self, tool_choice: rig_core::message::ToolChoice) -> Self {
            self.runner = self.runner.tool_choice(tool_choice);
            self
        }

        /// Remove the agent's configured tool-choice policy for this run.
        pub fn without_tool_choice(mut self) -> Self {
            self.runner = self.runner.without_tool_choice();
            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, and other sensitive or high-cardinality data through
        /// OpenTelemetry span attributes. Structural metadata and token usage
        /// remain available when disabled.
        pub fn record_content_telemetry(mut self, enabled: bool) -> Self {
            self.runner = self.runner.record_content_telemetry(enabled);
            self
        }

        /// Set the conversation id used to load and persist memory for this run.
        ///
        /// Overrides any default conversation id set on the agent. If memory is not
        /// configured on the agent, this has no effect.
        pub fn conversation(mut self, id: impl Into<rig_core::id::ConversationId>) -> Self {
            self.runner = self.runner.conversation(id);
            self
        }

        /// Disable conversation memory for this run.
        ///
        /// History will neither be loaded from nor saved to the agent's memory backend.
        pub fn without_memory(mut self) -> Self {
            self.runner = self.runner.without_memory();
            self
        }

        /// Set the retry budget for invalid tool-call recovery.
        ///
        /// Invalid tool-call retries also consume the total model-call budget.
        pub fn max_invalid_tool_call_retries(mut self, retries: usize) -> Self {
            self.runner = self.runner.max_invalid_tool_call_retries(retries);
            self
        }

        /// Set the default model candidate for this run.
        ///
        /// This does not suppress registered model-selection hooks, which may
        /// replace this candidate before each model call (including retries).
        pub fn using_model(mut self, model: impl Into<$crate::agent::ModelRef>) -> Self {
            self.runner = self.runner.using_model(model);
            self
        }

        /// Erase and set a typed default model for this run.
        pub fn using_model_value(
            mut self,
            model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
        ) -> Self {
            self.runner = self.runner.using_model_value(model);
            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 a
        /// [`StructuredOutputError::PromptError`] wrapping a `MaxTurnsError`.
        pub fn max_turns(mut self, max_turns: usize) -> Self {
            self.runner = self.runner.max_turns(max_turns);
            self
        }

        /// Append a hook to this run's hook stack (on top of any the agent
        /// already carries). See the [`hook`](crate::agent::hook) module docs.
        pub fn add_hook<H>(mut self, hook: H) -> Self
        where
            H: AgentHook + 'static,
        {
            self.runner = self.runner.add_hook(hook);
            self
        }

        /// Execute up to `concurrency` of a turn's tool calls at once. See
        /// [`AgentRunner::tool_concurrency`] for ordering guarantees.
        pub fn tool_concurrency(mut self, concurrency: usize) -> Self {
            self.runner = self.runner.tool_concurrency(concurrency);
            self
        }
    };
}

impl<T> TypedRun<T>
where
    T: JsonSchema + DeserializeOwned + WasmCompatSend,
{
    /// A native-mode typed run: the schema for `T` is the run's structured
    /// output schema and the model's final text is parsed as `T`.
    pub(crate) fn native(agent: &Agent, prompt: impl Into<Message>) -> Self {
        let mut runner = AgentRunner::from_agent(agent, prompt);
        runner.config.output_schema = Some(schema_for!(T));
        // Native typed prompting parses final text rather than requiring an output call.
        runner.config.output_mode = OutputMode::Native;
        Self::from_runner(runner, TypedOutput::Native)
    }

    /// An output-tool typed run over an already configured runner: the value
    /// is the arguments of the run's output tool call. Unhandled invalid tool
    /// calls are ignored rather than failing the run.
    pub(crate) fn output_tool(runner: AgentRunner) -> Self {
        Self::from_runner(
            runner.unhandled_invalid_tool_call(UnhandledInvalidToolCall::Ignore),
            TypedOutput::OutputTool,
        )
    }

    pub(crate) fn from_runner(runner: AgentRunner, output: TypedOutput) -> Self {
        Self {
            runner,
            retries: 0,
            output,
            _t: PhantomData,
        }
    }

    /// 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.
    pub fn retries(mut self, retries: u64) -> Self {
        self.retries = retries;
        self
    }

    forward_runner_setters!();

    async fn send(
        self,
        ambient: tracing::Span,
    ) -> Result<TypedPromptResponse<T>, StructuredOutputError> {
        let mut usage = Usage::default();
        let mut last_error = None;

        for attempt in 0..=self.retries {
            if self.retries > 0 {
                tracing::debug!(
                    "Attempting to extract structured output. Retries left: {}",
                    self.retries - attempt
                );
            }
            let (result, error_usage) = self
                .runner
                .clone()
                .run_with_error_usage(ambient.clone())
                .await;
            let outcome = match result {
                Ok(response) => {
                    usage += response.usage;
                    recover_output(&response, self.output).map(|output| TypedPromptResponse {
                        output,
                        usage,
                        completion_calls: response.completion_calls,
                        memory_append: response.memory_append,
                    })
                }
                Err(err) => {
                    usage += error_usage;
                    Err(StructuredOutputError::PromptError(err))
                }
            };
            match outcome {
                Ok(response) => return Ok(response),
                Err(err) => {
                    if attempt < self.retries {
                        tracing::warn!(
                            "Attempt {attempt} to extract structured output failed: {err:?}. Retrying..."
                        );
                    }
                    last_error = Some(err);
                }
            }
        }

        Err(last_error.unwrap_or(StructuredOutputError::EmptyResponse))
    }
}

/// Recover `T` from an accepted response according to the run's output mode.
fn recover_output<T: DeserializeOwned>(
    response: &PromptResponse,
    output: TypedOutput,
) -> Result<T, StructuredOutputError> {
    match output {
        TypedOutput::Native => {
            if response.output.is_empty() {
                return Err(StructuredOutputError::EmptyResponse);
            }
            Ok(deserialize_structured_output(&response.output)?)
        }
        TypedOutput::OutputTool => {
            let submissions = response.output_tool_calls();
            // A whole JSON answer is the run's output too: the protocol accepts
            // schema-valid text, and a model that rejects forced tool choice
            // answers in native structured output instead of calling the tool.
            if submissions == 0
                && let Ok(value) = serde_json::from_str::<T>(response.output.trim())
            {
                return Ok(value);
            }
            if submissions == 0 {
                tracing::warn!(
                    "The submit tool was not called. If this happens more than once, please ensure the model you are using is powerful enough to reliably call tools."
                );
                return Err(StructuredOutputError::EmptyResponse);
            }
            if submissions > 1 {
                tracing::warn!(
                    "Multiple submit calls detected, using the first one. Providers / agents should only ensure one submit call."
                );
            }
            Ok(serde_json::from_str(&response.output)?)
        }
    }
}

/// Deserialize final text directly, then try one value starting at the first
/// object or array delimiter. Returns a parse error if neither attempt yields `T`.
pub(crate) fn deserialize_structured_output<T: DeserializeOwned>(
    text: &str,
) -> Result<T, serde_json::Error> {
    let trimmed = text.trim();
    match serde_json::from_str::<T>(trimmed) {
        Ok(value) => Ok(value),
        Err(direct_err) => {
            let Some(start) = trimmed.find(['{', '[']) else {
                return Err(direct_err);
            };
            serde_json::Deserializer::from_str(&trimmed[start..])
                .into_iter::<T>()
                .next()
                .unwrap_or(Err(direct_err))
        }
    }
}

impl<T> IntoFuture for TypedRun<T>
where
    T: JsonSchema + DeserializeOwned + WasmCompatSend + 'static,
{
    type Output = Result<TypedPromptResponse<T>, StructuredOutputError>;
    type IntoFuture = WasmBoxedFuture<'static, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        // Captured in the synchronous part of the call, like `run()`: a
        // typed run belongs to the span it was started in, not to the task
        // that first polls it.
        let ambient = tracing::Span::current();
        let run_under = ambient.clone();
        Box::pin(self.send(run_under).instrument(ambient))
    }
}