rig-agent 0.46.0

Rig's classic agent runtime.
Documentation
//! Serializable request settings, turn budgets, and output policies for runs.
//! Live models, tools, and hooks remain owned by the driver.
//!
//! ```
//! use rig_agent::run::spec::RunSpec;
//! let spec = RunSpec::new();
//! assert_eq!(spec.effective_max_turns(), 1);
//! ```

use rig_core::completion::{Document, GenerationOptions, ProviderOptions, ProviderToolDefinition};
use rig_core::message::ToolChoice;
use serde::{Deserialize, Serialize};

use super::output::OutputMode;

/// Protocol-facing run configuration. See the [module docs](self).
/// [`Default`] equals [`RunSpec::new`], and a field missing from serialized
/// input takes its value from there.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RunSpec {
    /// System prompt.
    pub preamble: Option<String>,
    /// Documents always attached to the request.
    pub static_context: Vec<Document>,
    /// Provider-specific request parameters, merged into every request.
    pub additional_params: Option<serde_json::Value>,
    /// Provider-hosted tools every request carries, appended to
    /// `additional_params.tools` after the patch is merged. Omitted from the
    /// serialized spec while empty.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub provider_tools: Vec<ProviderToolDefinition>,
    /// Portable generation options every request carries. Omitted from the
    /// serialized spec while they hold their defaults.
    #[serde(skip_serializing_if = "GenerationOptions::is_default")]
    pub options: GenerationOptions,
    /// Typed per-provider options every request carries. Omitted from the
    /// serialized spec while empty.
    #[serde(skip_serializing_if = "ProviderOptions::is_empty")]
    pub provider_options: ProviderOptions,
    /// Maximum tokens the model may generate per call.
    pub max_tokens: Option<u64>,
    /// Sampling temperature.
    pub temperature: Option<f64>,
    /// Tool choice applied to every model call.
    pub tool_choice: Option<ToolChoice>,
    /// Total model-call budget for the run. `None` means the protocol default
    /// of one call.
    pub max_turns: Option<usize>,
    /// How many times an invalid model tool call may be retried with feedback.
    pub max_invalid_tool_call_retries: usize,
    /// How many consecutive turns may call a tool with arguments that are not
    /// a JSON object. Each such call is answered with feedback; a turn whose
    /// calls all parse resets the count. Past `Some(n)` such turns in a row,
    /// the run fails. `None`, the default, sets no limit.
    pub max_consecutive_malformed_tool_calls: Option<usize>,
    /// JSON schema the final answer must satisfy, when structured output is
    /// requested.
    pub output_schema: Option<rig_core::schemars::Schema>,
    /// How structured output is obtained.
    pub output_mode: OutputMode,
    /// Name of the synthetic output tool when output is collected through a
    /// tool call; `None` lets the driver pick.
    pub output_tool_name: Option<String>,
    /// Description of that synthetic tool.
    pub output_tool_description: Option<String>,
    /// Whether the driver may augment the preamble with structured-output
    /// instructions.
    pub augment_output_preamble: bool,
    /// What the run does with a model tool call that cannot be dispatched as
    /// written when no hook resolves it.
    pub unhandled_invalid_tool_call: UnhandledInvalidToolCall,
    /// Whether a finish reason outside the normalized vocabulary ends a turn
    /// as a normal stop. Carried into every prepared request. Defaults to
    /// `false`.
    pub accept_unknown_finish_reasons: bool,
}

/// Policy applied when every [`on_invalid_tool_call`] hook declines to resolve
/// a call to an unknown or disallowed tool. Defaults to failure; ignoring drops
/// the call and continues.
///
/// [`on_invalid_tool_call`]: crate::agent::AgentHook::on_invalid_tool_call
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnhandledInvalidToolCall {
    /// Fail the run.
    #[default]
    Fail,
    /// Drop the call and continue the turn.
    Ignore,
}

impl RunSpec {
    /// Create a spec with a one-call budget, no preamble, tool choice, or schema,
    /// and output-preamble augmentation enabled.
    pub fn new() -> Self {
        Self {
            preamble: None,
            static_context: Vec::new(),
            additional_params: None,
            provider_tools: Vec::new(),
            options: GenerationOptions::default(),
            provider_options: ProviderOptions::default(),
            max_tokens: None,
            temperature: None,
            tool_choice: None,
            max_turns: None,
            max_invalid_tool_call_retries: 0,
            max_consecutive_malformed_tool_calls: None,
            output_schema: None,
            output_mode: OutputMode::default(),
            output_tool_name: None,
            output_tool_description: None,
            augment_output_preamble: true,
            unhandled_invalid_tool_call: UnhandledInvalidToolCall::default(),
            accept_unknown_finish_reasons: false,
        }
    }

    /// The turn budget the protocol will use.
    pub fn effective_max_turns(&self) -> usize {
        self.max_turns.unwrap_or(1)
    }
}

impl Default for RunSpec {
    fn default() -> Self {
        Self::new()
    }
}

impl RunSpec {
    /// How many times a run re-prompts for structured output that failed
    /// validation before giving up. The default a run built from a spec
    /// carries; drivers that construct runs by hand pass it explicitly.
    pub const DEFAULT_OUTPUT_RETRIES: usize = 1;
}

#[cfg(test)]
mod tests;