Skip to main content

rig_agent/run/
patch.rs

1//! Per-turn overrides applied before request preparation without changing agent defaults.
2//!
3//! ```
4//! use rig_agent::run::patch::RequestPatch;
5//! let patch = RequestPatch::new().temperature(0.2).max_tokens(256);
6//! assert!(!patch.is_empty());
7//! ```
8
9use rig_core::completion::Document;
10use rig_core::message::{Message, ToolChoice};
11use serde::{Deserialize, Serialize};
12
13/// A non-sticky patch applied only to the current turn's completion request.
14///
15/// A driver's hook stack merges patches in hook registration order according to these
16/// rules:
17///
18/// - `extra_context` documents are appended in order.
19/// - JSON-object `additional_params` values are shallow-merged, with later
20///   top-level keys winning; a later non-object value replaces an earlier value.
21/// - `active_tools` allow-lists are intersected.
22/// - Scalar fields and `history` use last-writer-wins semantics, with a warning
23///   when multiple hooks set the same field.
24///
25/// The merged patch does not mutate the agent's configured baseline and is not
26/// carried into subsequent turns.
27#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
28pub struct RequestPatch {
29    /// Preamble to use instead of the agent's configured preamble for this turn.
30    pub preamble: Option<String>,
31    /// Sampling temperature to use for this turn.
32    pub temperature: Option<f64>,
33    /// Maximum output-token count to use for this turn.
34    pub max_tokens: Option<u64>,
35    /// Tool-choice policy to use for this turn.
36    pub tool_choice: Option<ToolChoice>,
37    /// Allow-list used to narrow the tools advertised for this turn.
38    pub active_tools: Option<Vec<String>>,
39    /// Provider-specific request parameters to apply for this turn.
40    pub additional_params: Option<serde_json::Value>,
41    /// Context documents appended to the request for this turn.
42    pub extra_context: Vec<Document>,
43    /// Conversation history to use instead of the current history for this turn.
44    pub history: Option<Vec<Message>>,
45}
46
47fn merge_last_wins<T>(earlier: Option<T>, later: Option<T>, field: &str) -> Option<T> {
48    match (earlier, later) {
49        (Some(_), Some(later)) => {
50            tracing::warn!(
51                patch_field = field,
52                "two hooks set the same request field; later wins"
53            );
54            Some(later)
55        }
56        (earlier, later) => later.or(earlier),
57    }
58}
59
60impl RequestPatch {
61    /// Creates an empty request patch.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Replaces the agent's configured preamble for this turn.
67    pub fn preamble(mut self, value: impl Into<String>) -> Self {
68        self.preamble = Some(value.into());
69        self
70    }
71
72    /// Sets the sampling temperature for this turn.
73    pub fn temperature(mut self, value: f64) -> Self {
74        self.temperature = Some(value);
75        self
76    }
77
78    /// Sets the maximum output-token count for this turn.
79    pub fn max_tokens(mut self, value: u64) -> Self {
80        self.max_tokens = Some(value);
81        self
82    }
83
84    /// Sets the tool-choice policy for this turn.
85    pub fn tool_choice(mut self, value: ToolChoice) -> Self {
86        self.tool_choice = Some(value);
87        self
88    }
89
90    /// Sets the allow-list used to narrow the tools advertised for this turn.
91    pub fn active_tools<I, S>(mut self, values: I) -> Self
92    where
93        I: IntoIterator<Item = S>,
94        S: Into<String>,
95    {
96        self.active_tools = Some(values.into_iter().map(Into::into).collect());
97        self
98    }
99
100    /// Sets provider-specific request parameters for this turn.
101    ///
102    /// When multiple patches provide JSON objects, their top-level keys are
103    /// shallow-merged and values from later hooks win.
104    pub fn additional_params(mut self, value: serde_json::Value) -> Self {
105        self.additional_params = Some(value);
106        self
107    }
108
109    /// Appends context documents to the request for this turn.
110    pub fn extra_context<I>(mut self, values: I) -> Self
111    where
112        I: IntoIterator<Item = Document>,
113    {
114        self.extra_context.extend(values);
115        self
116    }
117
118    /// Appends one context document to the request for this turn.
119    pub fn context(mut self, value: Document) -> Self {
120        self.extra_context.push(value);
121        self
122    }
123
124    /// Replaces the conversation history for this turn.
125    pub fn history<I>(mut self, values: I) -> Self
126    where
127        I: IntoIterator<Item = Message>,
128    {
129        self.history = Some(values.into_iter().collect());
130        self
131    }
132
133    /// Whether the patch sets nothing at all.
134    pub fn is_empty(&self) -> bool {
135        self.preamble.is_none()
136            && self.temperature.is_none()
137            && self.max_tokens.is_none()
138            && self.tool_choice.is_none()
139            && self.active_tools.is_none()
140            && self.additional_params.is_none()
141            && self.extra_context.is_empty()
142            && self.history.is_none()
143    }
144
145    /// Merge a later patch over this one under the rules documented on the
146    /// type: `extra_context` appends, object `additional_params` shallow-merge
147    /// (later keys win), `active_tools` intersect, scalars and `history` take
148    /// the later value (with a warning when both are set).
149    pub fn merge(mut self, later: Self) -> Self {
150        self.extra_context.extend(later.extra_context);
151        self.additional_params = match (self.additional_params.take(), later.additional_params) {
152            (Some(base), Some(patch)) if base.is_object() && patch.is_object() => {
153                Some(rig_core::json_utils::merge(base, patch))
154            }
155            (base, patch) => patch.or(base),
156        };
157        self.preamble = merge_last_wins(self.preamble, later.preamble, "preamble");
158        self.temperature = merge_last_wins(self.temperature, later.temperature, "temperature");
159        self.max_tokens = merge_last_wins(self.max_tokens, later.max_tokens, "max_tokens");
160        self.tool_choice = merge_last_wins(self.tool_choice, later.tool_choice, "tool_choice");
161        self.history = merge_last_wins(self.history, later.history, "history");
162        self.active_tools = match (self.active_tools.take(), later.active_tools) {
163            (Some(earlier), Some(later)) => {
164                let later: std::collections::BTreeSet<_> = later.iter().collect();
165                Some(
166                    earlier
167                        .into_iter()
168                        .filter(|name| later.contains(name))
169                        .collect(),
170                )
171            }
172            (earlier, later) => earlier.or(later),
173        };
174        self
175    }
176}
177
178#[cfg(test)]
179mod tests;