Skip to main content

rig_agent/run/
prepare.rs

1//! Pure request preparation from run settings, model capabilities, history, tools,
2//! and per-turn overrides. Retrieval and model execution remain driver responsibilities.
3//!
4//! ```
5//! use rig_agent::run::{prepare::prepare_request, spec::RunSpec};
6//! let request = prepare_request(&RunSpec::new(), &Default::default(), &[], vec![], None, None)?;
7//! assert!(request.tools.is_empty());
8//! # Ok::<(), rig_agent::run::prepare::PrepareError>(())
9//! ```
10
11use std::collections::BTreeSet;
12use std::sync::Arc;
13
14use rig_core::completion::{
15    CompletionRequest, Document, GenerationOptions, Message, ProviderCapabilities, ProviderOptions,
16    ToolDefinition,
17};
18use rig_core::error::ProviderError;
19use rig_core::message::ToolName;
20use rig_core::structured_output::{
21    AUGMENTATION_SEPARATOR, OUTPUT_TOOL_DESCRIPTION, output_tool_augmentation,
22    output_tool_callable, output_tool_name, prompted_augmentation,
23};
24
25use super::output::OutputMode;
26use super::patch::RequestPatch;
27use super::policy::TurnPolicy;
28use super::spec::RunSpec;
29
30/// Why a request could not be prepared: a local, pre-IO error. The effective
31/// request is invalid (an impossible tool choice, an `active_tools` name that
32/// is not available, an output-tool collision).
33#[derive(Debug, thiserror::Error)]
34pub enum PrepareError {
35    /// The request the spec, patch and tool set describe.
36    #[error("{0}")]
37    Request(String),
38}
39
40impl From<PrepareError> for ProviderError {
41    fn from(error: PrepareError) -> Self {
42        ProviderError::request(error.to_string())
43    }
44}
45
46/// Everything a model call carries that the protocol decides, as owned data.
47///
48/// Apply it to a provider's request builder with [`apply`](Self::apply); the
49/// driver adds only what is its own (telemetry flags), then sends. The
50/// turn's [`policy`](Self::policy) is what the driver feeds back into the run
51/// when the response arrives.
52#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
53pub struct PreparedRequest {
54    /// Prior messages to send: the effective (possibly augmented) preamble as a
55    /// leading system message, then the history (the patch's `history` when
56    /// set, else the caller's).
57    pub chat_history: Vec<Arc<Message>>,
58    /// Static context documents followed by the patch's `extra_context`.
59    pub documents: Vec<Document>,
60    /// The tools advertised to the model this turn, in order: the executable
61    /// tools (after any `active_tools` allow-list) plus, in Tool output mode,
62    /// the synthetic output tool last.
63    pub tools: Vec<Arc<ToolDefinition>>,
64    /// Effective sampling temperature (patch over spec).
65    pub temperature: Option<f64>,
66    /// Effective output-token cap, with patch values overriding the spec.
67    pub max_tokens: Option<u64>,
68    /// Effective provider passthrough parameters (patch shallow-merged over
69    /// spec when both are objects).
70    pub additional_params: Option<serde_json::Value>,
71    /// The spec's portable generation options.
72    #[serde(default, skip_serializing_if = "GenerationOptions::is_default")]
73    pub options: GenerationOptions,
74    /// The spec's typed per-provider options.
75    #[serde(default, skip_serializing_if = "ProviderOptions::is_empty")]
76    pub provider_options: ProviderOptions,
77    /// The provider-native structured-output constraint, set only when the
78    /// resolved mode is [`OutputMode::Native`].
79    pub output_schema: Option<rig_core::schemars::Schema>,
80    /// The mode this turn actually runs in (never [`OutputMode::Auto`]).
81    pub output_mode: OutputMode,
82    /// The turn's tool policy: executable tools, effective tool choice
83    /// (patch over spec), output tool and the names the choice allows.
84    pub policy: TurnPolicy,
85    /// The spec's [`RunSpec::accept_unknown_finish_reasons`].
86    #[serde(default)]
87    pub accept_unknown_finish_reasons: bool,
88}
89
90impl PreparedRequest {
91    /// Apply every prepared field to `request`, in the protocol's canonical
92    /// order. The request keeps its prompt last; the prepared sampling fields
93    /// (`temperature`, `max_tokens`, `output_schema`) and
94    /// `accept_unknown_finish_reasons` overwrite whatever the driver set on
95    /// it, while messages, documents, tools and additional parameters
96    /// accumulate.
97    pub fn apply(self, mut request: CompletionRequest) -> CompletionRequest {
98        request.accept_unknown_finish_reasons = self.accept_unknown_finish_reasons;
99        let request = request
100            .messages(self.chat_history)
101            .temperature(self.temperature)
102            .max_tokens(self.max_tokens)
103            .additional_params(self.additional_params)
104            .options(self.options)
105            .provider_options(self.provider_options)
106            .documents(self.documents)
107            .tools(self.tools)
108            .output_schema(self.output_schema);
109        match self.policy.tool_choice() {
110            Some(tool_choice) => request.tool_choice(tool_choice.clone()),
111            None => request,
112        }
113    }
114}
115
116/// Prepare one model call from settings, capability snapshot, ordered history,
117/// retrieved tools in advertisement order, and an optional merged patch.
118/// A committed output-tool name pins tool mode while a schema is present.
119/// Returns errors for incompatible tool choices, unavailable allow-list names,
120/// output-tool collisions, or invalid native schemas. Performs no I/O.
121pub fn prepare_request(
122    spec: &RunSpec,
123    capabilities: &ProviderCapabilities,
124    history: &[Arc<Message>],
125    tools: Vec<Arc<ToolDefinition>>,
126    committed_output_tool: Option<&str>,
127    patch: Option<&RequestPatch>,
128) -> Result<PreparedRequest, PrepareError> {
129    let request_patch = patch;
130    let chat_history = history;
131    let preamble = spec.preamble.as_deref();
132    let static_context = &spec.static_context;
133    let temperature = spec.temperature;
134    let max_tokens = spec.max_tokens;
135    let additional_params = spec.additional_params.as_ref();
136    let tool_choice = spec.tool_choice.as_ref();
137    let output_schema = spec.output_schema.as_ref();
138    let output_mode = &spec.output_mode;
139    let output_tool_description = spec.output_tool_description.as_deref();
140    let augment_output_preamble = spec.augment_output_preamble;
141    let preamble = request_patch
142        .and_then(|o| o.preamble.as_deref())
143        .or(preamble);
144    let temperature = request_patch.and_then(|o| o.temperature).or(temperature);
145    let max_tokens = request_patch.and_then(|o| o.max_tokens).or(max_tokens);
146    let tool_choice = request_patch
147        .and_then(|o| o.tool_choice.as_ref())
148        .or(tool_choice);
149    // Non-object patches must replace the baseline; the object merge helper
150    // otherwise retains its first argument for these inputs.
151    let additional_params: Option<serde_json::Value> = match (
152        additional_params,
153        request_patch.and_then(|o| o.additional_params.as_ref()),
154    ) {
155        (Some(base), Some(patch)) if base.is_object() && patch.is_object() => {
156            Some(rig_core::json_utils::merge(base.clone(), patch.clone()))
157        }
158        (base, patch) => patch.or(base).cloned(),
159    };
160    let active_tools = request_patch.and_then(|o| o.active_tools.as_deref());
161
162    // Reserve output names against the full tool set because filtered tools may
163    // return on later turns while the output name remains pinned.
164    let pre_filter_tool_names: Option<BTreeSet<String>> =
165        active_tools.map(|_| tools.iter().map(|tool| tool.name.to_string()).collect());
166
167    // Filter before computing executable names so request advertisements and
168    // runtime validation agree. Synthetic output remains independent of this filter.
169    let mut tooldefs = tools;
170    if let Some(allow) = active_tools {
171        if let Some(missing) = allow
172            .iter()
173            .find(|name| !tooldefs.iter().any(|tool| tool.name == **name))
174        {
175            return Err(PrepareError::Request(format!(
176                "active_tools requested tool `{missing}`, which is not available this turn"
177            )));
178        }
179        let allowed: BTreeSet<String> = allow.iter().cloned().collect();
180        tooldefs.retain(|tool| allowed.contains(tool.name.as_str()));
181    }
182
183    // The synthetic output tool must never enter the executable set.
184    let executable_tool_names: BTreeSet<String> =
185        tooldefs.iter().map(|tool| tool.name.to_string()).collect();
186
187    // Resolve against the actual candidate name so Specific choices can permit
188    // the output tool. A committed name prevents changing output mode mid-run.
189    let candidate_output_tool = committed_output_tool.map_or_else(
190        || {
191            let taken = pre_filter_tool_names
192                .as_ref()
193                .unwrap_or(&executable_tool_names);
194            output_tool_name(|name| taken.contains(name))
195        },
196        str::to_owned,
197    );
198    let resolved_mode = if committed_output_tool.is_some() && output_schema.is_some() {
199        OutputMode::Tool
200    } else {
201        resolve_output_mode(
202            output_schema.is_some(),
203            !executable_tool_names.is_empty(),
204            output_tool_callable(tool_choice, &candidate_output_tool),
205            capabilities.composes_native_output_with_tools,
206            output_mode,
207        )
208    };
209
210    let output_tool_name =
211        matches!(resolved_mode, OutputMode::Tool).then_some(candidate_output_tool);
212
213    // A later real tool may collide with a pinned output name; reject it before
214    // a real tool call can be mistaken for run finalization.
215    if let Some(name) = &output_tool_name
216        && executable_tool_names.contains(name)
217    {
218        return Err(PrepareError::Request(format!(
219            "real tool `{name}` conflicts with the structured-output tool reserved for this \
220             run; rename or remove the real tool, exclude it with `active_tools`, or make it \
221             visible before starting a new run so Rig can reserve a different output-tool name"
222        )));
223    }
224
225    // Pinned tool mode cannot fall back to native output when a later choice
226    // forbids its output call, so report the incompatible policy.
227    if let Some(name) = &output_tool_name
228        && !output_tool_callable(tool_choice, name)
229    {
230        tracing::warn!(
231            "the active tool_choice forbids calling the structured-output tool while the \
232             run is pinned to Tool output mode; this turn cannot emit the structured \
233             result (check for a `RequestPatch` setting `tool_choice` to None or a \
234             Specific set that excludes the output tool)"
235        );
236    }
237
238    let effective_preamble: Option<String> = {
239        let base = preamble.map(str::to_owned);
240        let instruction = match &resolved_mode {
241            OutputMode::Tool if augment_output_preamble => {
242                output_tool_name.as_deref().map(output_tool_augmentation)
243            }
244            OutputMode::Tool => None,
245            OutputMode::Prompted => output_schema.map(|schema| {
246                prompted_augmentation(&rig_core::json_utils::to_canonical_string(
247                    schema.as_value(),
248                ))
249            }),
250            OutputMode::Native | OutputMode::Auto => None,
251        };
252        match (base, instruction) {
253            (Some(b), Some(i)) => Some(format!("{b}{AUGMENTATION_SEPARATOR}{i}")),
254            (Some(b), None) => Some(b),
255            (None, Some(i)) => Some(i),
256            (None, None) => None,
257        }
258    };
259
260    // Request history replacement must not mutate persisted conversation history.
261    let messages_history: &[Arc<Message>] = request_patch
262        .and_then(|o| o.history.as_deref())
263        .unwrap_or(chat_history);
264    let preamble = effective_preamble.map(|preamble| Arc::new(Message::system(preamble)));
265    let chat_history: Vec<Arc<Message>> = preamble
266        .into_iter()
267        .chain(messages_history.iter().cloned())
268        .collect();
269
270    if let (Some(name), Some(schema)) = (&output_tool_name, output_schema) {
271        tooldefs.push(Arc::new(ToolDefinition {
272            name: ToolName::new(name.clone()).map_err(|_| {
273                PrepareError::Request("the output tool name cannot be empty".to_string())
274            })?,
275            description: output_tool_description
276                .unwrap_or(OUTPUT_TOOL_DESCRIPTION)
277                .to_string(),
278            parameters: schema.as_value().clone(),
279            annotations: Default::default(),
280        }));
281    }
282
283    let native_schema = match (&resolved_mode, output_schema) {
284        (OutputMode::Native, Some(schema)) => Some(schema.clone()),
285        _ => None,
286    };
287
288    let mut documents = static_context.clone();
289    if let Some(patch) = request_patch {
290        documents.extend(patch.extra_context.iter().cloned());
291    }
292
293    // Reject impossible choices before spending a provider request.
294    let policy = TurnPolicy::resolve(
295        executable_tool_names,
296        tool_choice.cloned(),
297        output_tool_name,
298        pre_filter_tool_names.as_ref(),
299    )?;
300
301    Ok(PreparedRequest {
302        chat_history,
303        documents,
304        tools: tooldefs,
305        temperature,
306        max_tokens,
307        additional_params,
308        options: spec.options.clone(),
309        provider_options: spec.provider_options.clone(),
310        output_schema: native_schema,
311        output_mode: resolved_mode,
312        policy,
313        accept_unknown_finish_reasons: spec.accept_unknown_finish_reasons,
314    })
315}
316
317/// Resolve to a non-auto mode. Without a schema, use native output. Auto selects
318/// tool output only with executable tools, a callable output tool, and no native
319/// composition support. Explicit tool mode falls back to native if uncallable;
320/// native and prompted modes remain unchanged when a schema is present.
321fn resolve_output_mode(
322    has_schema: bool,
323    has_executable_tools: bool,
324    output_tool_callable: bool,
325    provider_composes_native: bool,
326    requested: &OutputMode,
327) -> OutputMode {
328    if !has_schema {
329        return OutputMode::Native;
330    }
331    match requested {
332        OutputMode::Native => OutputMode::Native,
333        OutputMode::Prompted => OutputMode::Prompted,
334        OutputMode::Tool if output_tool_callable => OutputMode::Tool,
335        OutputMode::Tool => OutputMode::Native,
336        OutputMode::Auto
337            if has_executable_tools && output_tool_callable && !provider_composes_native =>
338        {
339            OutputMode::Tool
340        }
341        OutputMode::Auto => OutputMode::Native,
342    }
343}
344
345#[cfg(test)]
346mod tests;