rig-agent 0.46.0

Rig's classic agent runtime.
Documentation
//! 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 std::sync::Arc;

use rig_core::completion::{
    CompletionRequest, Document, GenerationOptions, Message, ProviderCapabilities, ProviderOptions,
    ProviderToolDefinition, ToolDefinition,
};
use rig_core::error::ProviderError;
use rig_core::message::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::policy::TurnPolicy;
use super::spec::RunSpec;

/// Why a request could not be prepared: a local, pre-IO error. The effective
/// request is invalid (an impossible tool choice, an `active_tools` name that
/// is not available, an output-tool collision).
#[derive(Debug, thiserror::Error)]
pub enum PrepareError {
    /// The request the spec, patch and tool set describe.
    #[error("{0}")]
    Request(String),
}

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
/// turn's [`policy`](Self::policy) is 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<Arc<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<Arc<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>,
    /// The spec's provider-hosted tools, appended to
    /// `additional_params.tools` by [`apply`](Self::apply).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub provider_tools: Vec<ProviderToolDefinition>,
    /// 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,
    /// The turn's tool policy: executable tools, effective tool choice
    /// (patch over spec), output tool and the names the choice allows.
    pub policy: TurnPolicy,
    /// 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)
            .provider_tools(self.provider_tools)
            .output_schema(self.output_schema);
        match self.policy.tool_choice() {
            Some(tool_choice) => request.tool_choice(tool_choice.clone()),
            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: &[Arc<Message>],
    tools: Vec<Arc<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());
    // Hosted tools also arrive as raw `additional_params.tools`; providers
    // advertise both after the function tools.
    let hosted = !spec.provider_tools.is_empty()
        || additional_params
            .as_ref()
            .and_then(|params| params.get("tools"))
            .and_then(serde_json::Value::as_array)
            .is_some_and(|tools| !tools.is_empty());

    // 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(),
            hosted || !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.as_value(),
                ))
            }),
            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: &[Arc<Message>] = request_patch
        .and_then(|o| o.history.as_deref())
        .unwrap_or(chat_history);
    let preamble = effective_preamble.map(|preamble| Arc::new(Message::system(preamble)));
    let chat_history: Vec<Arc<Message>> = preamble
        .into_iter()
        .chain(messages_history.iter().cloned())
        .collect();

    if let (Some(name), Some(schema)) = (&output_tool_name, output_schema) {
        tooldefs.push(Arc::new(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.as_value().clone(),
            annotations: Default::default(),
        }));
    }

    let native_schema = match (&resolved_mode, output_schema) {
        (OutputMode::Native, Some(schema)) => Some(schema.clone()),
        _ => 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 policy = TurnPolicy::resolve(
        executable_tool_names,
        tool_choice.cloned(),
        output_tool_name,
        pre_filter_tool_names.as_ref(),
        hosted,
    )?;

    Ok(PreparedRequest {
        chat_history,
        documents,
        tools: tooldefs,
        temperature,
        max_tokens,
        additional_params,
        provider_tools: spec.provider_tools.clone(),
        options: spec.options.clone(),
        provider_options: spec.provider_options.clone(),
        output_schema: native_schema,
        output_mode: resolved_mode,
        policy,
        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 advertised tools (executable or hosted), 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_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_tools && output_tool_callable && !provider_composes_native => {
            OutputMode::Tool
        }
        OutputMode::Auto => OutputMode::Native,
    }
}

#[cfg(test)]
mod tests;