rig-agent 0.44.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
//! Pure request preparation from run settings, model capabilities, history, tools,
//! and per-turn overrides. Retrieval and model execution remain driver responsibilities.
//!
//! ```
//! use rig_agent::run::{prepare::prepare_request, spec::RunSpec};
//! let request = prepare_request(&RunSpec::new(), &Default::default(), &[], vec![], None, None)?;
//! assert!(request.tools.is_empty());
//! # Ok::<(), rig_agent::run::prepare::PrepareError>(())
//! ```

use std::collections::BTreeSet;

use rig_core::completion::{
    CompletionRequest, Document, GenerationOptions, Message, ProviderCapabilities, ProviderOptions,
    ToolDefinition,
};
use rig_core::error::ProviderError;
use rig_core::message::{ToolChoice, ToolName};
use rig_core::structured_output::{
    AUGMENTATION_SEPARATOR, OUTPUT_TOOL_DESCRIPTION, output_tool_augmentation,
    output_tool_callable, output_tool_name, prompted_augmentation,
};

use super::output::OutputMode;
use super::patch::RequestPatch;
use super::spec::RunSpec;

/// Why a request could not be prepared. Every variant is a local, pre-IO
/// error: the spec, patch and tool set cannot produce a request the model
/// could honor.
#[derive(Debug, thiserror::Error)]
pub enum PrepareError {
    /// The effective request is invalid (an impossible tool choice, an
    /// `active_tools` name that is not available, an output-tool collision).
    #[error("{0}")]
    Request(String),
    /// `output_schema` is not a valid JSON schema.
    #[error("invalid output schema: {0}")]
    InvalidOutputSchema(#[source] serde_json::Error),
}

impl From<PrepareError> for ProviderError {
    fn from(error: PrepareError) -> Self {
        ProviderError::request(error.to_string())
    }
}

/// Everything a model call carries that the protocol decides, as owned data.
///
/// Apply it to a provider's request builder with [`apply`](Self::apply); the
/// driver adds only what is its own (telemetry flags), then sends. The
/// bookkeeping fields (`executable_tool_names`, `allowed_tool_names`,
/// `output_tool_name`, `output_mode`) are what the driver feeds back into the
/// run when the response arrives.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PreparedRequest {
    /// Prior messages to send: the effective (possibly augmented) preamble as a
    /// leading system message, then the history (the patch's `history` when
    /// set, else the caller's).
    pub chat_history: Vec<Message>,
    /// Static context documents followed by the patch's `extra_context`.
    pub documents: Vec<Document>,
    /// The tools advertised to the model this turn, in order: the executable
    /// tools (after any `active_tools` allow-list) plus, in Tool output mode,
    /// the synthetic output tool last.
    pub tools: Vec<ToolDefinition>,
    /// Effective sampling temperature (patch over spec).
    pub temperature: Option<f64>,
    /// Effective output-token cap, with patch values overriding the spec.
    pub max_tokens: Option<u64>,
    /// Effective provider passthrough parameters (patch shallow-merged over
    /// spec when both are objects).
    pub additional_params: Option<serde_json::Value>,
    /// Effective tool choice (patch over spec).
    pub tool_choice: Option<ToolChoice>,
    /// The spec's portable generation options.
    #[serde(default, skip_serializing_if = "GenerationOptions::is_default")]
    pub options: GenerationOptions,
    /// The spec's typed per-provider options.
    #[serde(default, skip_serializing_if = "ProviderOptions::is_empty")]
    pub provider_options: ProviderOptions,
    /// The provider-native structured-output constraint, set only when the
    /// resolved mode is [`OutputMode::Native`].
    pub output_schema: Option<rig_core::schemars::Schema>,
    /// The mode this turn actually runs in (never [`OutputMode::Auto`]).
    pub output_mode: OutputMode,
    /// Names of the real, dispatchable tools advertised this turn.
    pub executable_tool_names: BTreeSet<String>,
    /// Names the model may call without it being an invalid tool call: the
    /// executable tools narrowed by the tool choice, plus the output tool.
    pub allowed_tool_names: BTreeSet<String>,
    /// In Tool output mode, the synthetic output tool's name (allowed but never
    /// executable); reuse it as `committed_output_tool` on later turns.
    pub output_tool_name: Option<String>,
    /// The spec's [`RunSpec::accept_unknown_finish_reasons`].
    #[serde(default)]
    pub accept_unknown_finish_reasons: bool,
}

impl PreparedRequest {
    /// Apply every prepared field to `request`, in the protocol's canonical
    /// order. The request keeps its prompt last; the prepared sampling fields
    /// (`temperature`, `max_tokens`, `output_schema`) and
    /// `accept_unknown_finish_reasons` overwrite whatever the driver set on
    /// it, while messages, documents, tools and additional parameters
    /// accumulate.
    pub fn apply(self, mut request: CompletionRequest) -> CompletionRequest {
        request.accept_unknown_finish_reasons = self.accept_unknown_finish_reasons;
        let request = request
            .messages(self.chat_history)
            .temperature(self.temperature)
            .max_tokens(self.max_tokens)
            .additional_params(self.additional_params)
            .options(self.options)
            .provider_options(self.provider_options)
            .documents(self.documents)
            .tools(self.tools)
            .output_schema(self.output_schema);
        match self.tool_choice {
            Some(tool_choice) => request.tool_choice(tool_choice),
            None => request,
        }
    }
}

/// Prepare one model call from settings, capability snapshot, ordered history,
/// retrieved tools in advertisement order, and an optional merged patch.
/// A committed output-tool name pins tool mode while a schema is present.
/// Returns errors for incompatible tool choices, unavailable allow-list names,
/// output-tool collisions, or invalid native schemas. Performs no I/O.
pub fn prepare_request(
    spec: &RunSpec,
    capabilities: &ProviderCapabilities,
    history: &[Message],
    tools: Vec<ToolDefinition>,
    committed_output_tool: Option<&str>,
    patch: Option<&RequestPatch>,
) -> Result<PreparedRequest, PrepareError> {
    let request_patch = patch;
    let chat_history = history;
    let preamble = spec.preamble.as_deref();
    let static_context = &spec.static_context;
    let temperature = spec.temperature;
    let max_tokens = spec.max_tokens;
    let additional_params = spec.additional_params.as_ref();
    let tool_choice = spec.tool_choice.as_ref();
    let output_schema = spec.output_schema.as_ref();
    let output_mode = &spec.output_mode;
    let output_tool_description = spec.output_tool_description.as_deref();
    let augment_output_preamble = spec.augment_output_preamble;
    let preamble = request_patch
        .and_then(|o| o.preamble.as_deref())
        .or(preamble);
    let temperature = request_patch.and_then(|o| o.temperature).or(temperature);
    let max_tokens = request_patch.and_then(|o| o.max_tokens).or(max_tokens);
    let tool_choice = request_patch
        .and_then(|o| o.tool_choice.as_ref())
        .or(tool_choice);
    // Non-object patches must replace the baseline; the object merge helper
    // otherwise retains its first argument for these inputs.
    let additional_params: Option<serde_json::Value> = match (
        additional_params,
        request_patch.and_then(|o| o.additional_params.as_ref()),
    ) {
        (Some(base), Some(patch)) if base.is_object() && patch.is_object() => {
            Some(rig_core::json_utils::merge(base.clone(), patch.clone()))
        }
        (base, patch) => patch.or(base).cloned(),
    };
    let active_tools = request_patch.and_then(|o| o.active_tools.as_deref());

    // Reserve output names against the full tool set because filtered tools may
    // return on later turns while the output name remains pinned.
    let pre_filter_tool_names: Option<BTreeSet<String>> =
        active_tools.map(|_| tools.iter().map(|tool| tool.name.to_string()).collect());

    // Filter before computing executable names so request advertisements and
    // runtime validation agree. Synthetic output remains independent of this filter.
    let mut tooldefs = tools;
    if let Some(allow) = active_tools {
        if let Some(missing) = allow
            .iter()
            .find(|name| !tooldefs.iter().any(|tool| tool.name == **name))
        {
            return Err(PrepareError::Request(format!(
                "active_tools requested tool `{missing}`, which is not available this turn"
            )));
        }
        let allowed: BTreeSet<String> = allow.iter().cloned().collect();
        tooldefs.retain(|tool| allowed.contains(tool.name.as_str()));
    }

    // The synthetic output tool must never enter the executable set.
    let executable_tool_names: BTreeSet<String> =
        tooldefs.iter().map(|tool| tool.name.to_string()).collect();

    // Resolve against the actual candidate name so Specific choices can permit
    // the output tool. A committed name prevents changing output mode mid-run.
    let candidate_output_tool = committed_output_tool.map_or_else(
        || {
            let taken = pre_filter_tool_names
                .as_ref()
                .unwrap_or(&executable_tool_names);
            output_tool_name(|name| taken.contains(name))
        },
        str::to_owned,
    );
    let resolved_mode = if committed_output_tool.is_some() && output_schema.is_some() {
        OutputMode::Tool
    } else {
        resolve_output_mode(
            output_schema.is_some(),
            !executable_tool_names.is_empty(),
            output_tool_callable(tool_choice, &candidate_output_tool),
            capabilities.composes_native_output_with_tools,
            output_mode,
        )
    };

    let output_tool_name =
        matches!(resolved_mode, OutputMode::Tool).then_some(candidate_output_tool);

    // A later real tool may collide with a pinned output name; reject it before
    // a real tool call can be mistaken for run finalization.
    if let Some(name) = &output_tool_name
        && executable_tool_names.contains(name)
    {
        return Err(PrepareError::Request(format!(
            "real tool `{name}` conflicts with the structured-output tool reserved for this \
             run; rename or remove the real tool, exclude it with `active_tools`, or make it \
             visible before starting a new run so Rig can reserve a different output-tool name"
        )));
    }

    // Pinned tool mode cannot fall back to native output when a later choice
    // forbids its output call, so report the incompatible policy.
    if let Some(name) = &output_tool_name
        && !output_tool_callable(tool_choice, name)
    {
        tracing::warn!(
            "the active tool_choice forbids calling the structured-output tool while the \
             run is pinned to Tool output mode; this turn cannot emit the structured \
             result (check for a `RequestPatch` setting `tool_choice` to None or a \
             Specific set that excludes the output tool)"
        );
    }

    let effective_preamble: Option<String> = {
        let base = preamble.map(str::to_owned);
        let instruction = match &resolved_mode {
            OutputMode::Tool if augment_output_preamble => {
                output_tool_name.as_deref().map(output_tool_augmentation)
            }
            OutputMode::Tool => None,
            OutputMode::Prompted => output_schema.map(|schema| {
                prompted_augmentation(&rig_core::json_utils::to_canonical_string(schema))
            }),
            OutputMode::Native | OutputMode::Auto => None,
        };
        match (base, instruction) {
            (Some(b), Some(i)) => Some(format!("{b}{AUGMENTATION_SEPARATOR}{i}")),
            (Some(b), None) => Some(b),
            (None, Some(i)) => Some(i),
            (None, None) => None,
        }
    };

    // Request history replacement must not mutate persisted conversation history.
    let messages_history: &[Message] = request_patch
        .and_then(|o| o.history.as_deref())
        .unwrap_or(chat_history);
    let chat_history: Vec<Message> = if let Some(preamble) = &effective_preamble {
        std::iter::once(Message::system(preamble.clone()))
            .chain(messages_history.iter().cloned())
            .collect()
    } else {
        messages_history.to_vec()
    };

    if let (Some(name), Some(schema)) = (&output_tool_name, output_schema) {
        tooldefs.push(ToolDefinition {
            name: ToolName::new(name.clone()).map_err(|_| {
                PrepareError::Request("the output tool name cannot be empty".to_string())
            })?,
            description: output_tool_description
                .unwrap_or(OUTPUT_TOOL_DESCRIPTION)
                .to_string(),
            parameters: schema.clone(),
        });
    }

    let native_schema = match (&resolved_mode, output_schema) {
        (OutputMode::Native, Some(schema)) => Some(
            rig_core::schemars::Schema::try_from(schema.clone())
                .map_err(PrepareError::InvalidOutputSchema)?,
        ),
        _ => None,
    };

    let mut documents = static_context.clone();
    if let Some(patch) = request_patch {
        documents.extend(patch.extra_context.iter().cloned());
    }

    // Reject impossible choices before spending a provider request.
    let mut allowed_tool_names = allowed_tool_names_for_choice(
        &executable_tool_names,
        tool_choice,
        output_tool_name.as_deref(),
        pre_filter_tool_names.as_ref(),
    )?;
    // The output tool must be allowed (so it isn't flagged as an invalid tool
    // call) even though it is not executable.
    if let Some(name) = &output_tool_name {
        allowed_tool_names.insert(name.clone());
    }

    Ok(PreparedRequest {
        chat_history,
        documents,
        tools: tooldefs,
        temperature,
        max_tokens,
        additional_params,
        tool_choice: tool_choice.cloned(),
        options: spec.options.clone(),
        provider_options: spec.provider_options.clone(),
        output_schema: native_schema,
        output_mode: resolved_mode,
        executable_tool_names,
        allowed_tool_names,
        output_tool_name,
        accept_unknown_finish_reasons: spec.accept_unknown_finish_reasons,
    })
}

/// Resolve to a non-auto mode. Without a schema, use native output. Auto selects
/// tool output only with executable tools, a callable output tool, and no native
/// composition support. Explicit tool mode falls back to native if uncallable;
/// native and prompted modes remain unchanged when a schema is present.
fn resolve_output_mode(
    has_schema: bool,
    has_executable_tools: bool,
    output_tool_callable: bool,
    provider_composes_native: bool,
    requested: &OutputMode,
) -> OutputMode {
    if !has_schema {
        return OutputMode::Native;
    }
    match requested {
        OutputMode::Native => OutputMode::Native,
        OutputMode::Prompted => OutputMode::Prompted,
        OutputMode::Tool if output_tool_callable => OutputMode::Tool,
        OutputMode::Tool => OutputMode::Native,
        OutputMode::Auto
            if has_executable_tools && output_tool_callable && !provider_composes_native =>
        {
            OutputMode::Tool
        }
        OutputMode::Auto => OutputMode::Native,
    }
}

/// Validate tool choice and return permitted names. Auto and required choices
/// return executable names; specific choices return their requested names,
/// including the output tool if named. None returns an empty set.
/// Errors on required choice without any advertised tool, empty specific choices,
/// or names absent from executable tools and the output tool. Supply pre-filter
/// names only when an allow-list was applied, for filter-specific diagnostics.
pub fn allowed_tool_names_for_choice(
    executable_tool_names: &BTreeSet<String>,
    tool_choice: Option<&ToolChoice>,
    output_tool_name: Option<&str>,
    pre_filter_tool_names: Option<&BTreeSet<String>>,
) -> Result<BTreeSet<String>, PrepareError> {
    let has_advertised_tool = !executable_tool_names.is_empty() || output_tool_name.is_some();
    let hint = |active_tools_caused: bool| {
        if active_tools_caused {
            " A per-turn `active_tools` allow-list narrowed the advertised tools this turn; \
             set a compatible `tool_choice` in the same `RequestPatch`, or widen `active_tools`."
        } else {
            ""
        }
    };
    let advertised = || {
        executable_tool_names
            .iter()
            .map(String::as_str)
            .chain(output_tool_name)
            .collect::<Vec<_>>()
    };

    let allowed = match tool_choice {
        None | Some(ToolChoice::Auto) => executable_tool_names.clone(),
        Some(ToolChoice::Required) => {
            if !has_advertised_tool {
                let active_tools_caused = pre_filter_tool_names.is_some_and(|pf| !pf.is_empty());
                return Err(PrepareError::Request(format!(
                    "ToolChoice::Required forces the model to call a tool, but no tools are \
                     advertised this turn.{}",
                    hint(active_tools_caused)
                )));
            }
            executable_tool_names.clone()
        }
        Some(ToolChoice::None) => BTreeSet::new(),
        Some(ToolChoice::Specific { function_names }) => {
            if function_names.is_empty() {
                return Err(PrepareError::Request(
                    "ToolChoice::Specific requires at least one function name".to_string(),
                ));
            }

            let requested = function_names
                .iter()
                .map(ToString::to_string)
                .collect::<BTreeSet<String>>();
            let missing = function_names
                .iter()
                .map(ToolName::as_str)
                .filter(|name| {
                    !executable_tool_names.contains(*name) && Some(*name) != output_tool_name
                })
                .collect::<Vec<_>>();

            if !missing.is_empty() {
                // Attribute missing names to filtering only if they existed before it.
                let active_tools_caused = pre_filter_tool_names
                    .is_some_and(|pf| missing.iter().any(|name| pf.contains(*name)));
                return Err(PrepareError::Request(format!(
                    "ToolChoice::Specific requested tool names not advertised this turn: \
                     {missing:?}. Advertised: {:?}.{}",
                    advertised(),
                    hint(active_tools_caused)
                )));
            }

            requested
        }
    };

    Ok(allowed)
}

#[cfg(test)]
mod tests;