Skip to main content

fm_rs/
options.rs

1//! Generation options for controlling model output.
2
3use serde::{Deserialize, Serialize};
4
5/// Sampling strategy for token generation.
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(rename_all = "lowercase")]
8pub enum Sampling {
9    /// Greedy sampling: always pick the most likely token.
10    Greedy,
11    /// Random sampling with temperature.
12    #[default]
13    Random,
14}
15
16/// Extended-reasoning effort for Foundation Models 27 requests.
17#[non_exhaustive]
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ReasoningLevel {
20    /// Minimize reasoning latency and compute.
21    Light,
22    /// Balance reasoning quality with latency.
23    Moderate,
24    /// Spend the most effort on complex reasoning.
25    Deep,
26}
27
28impl ReasoningLevel {
29    pub(crate) fn as_ffi_code(self) -> i32 {
30        match self {
31            Self::Light => 1,
32            Self::Moderate => 2,
33            Self::Deep => 3,
34        }
35    }
36}
37
38/// Controls whether the model may, must, or must not call tools
39/// (Foundation Models 27).
40#[non_exhaustive]
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "lowercase")]
43pub enum ToolCallingMode {
44    /// The model decides when to call tools (framework default).
45    Allowed,
46    /// The model must call a tool before responding. Apple warns that this
47    /// mode needs an explicit exit condition to avoid unbounded loops.
48    Required,
49    /// The model must answer from current context without calling tools.
50    Disallowed,
51}
52
53/// Options that control how the model generates its response.
54///
55/// Use the builder pattern to configure options:
56///
57/// ```rust
58/// use fm_rs::GenerationOptions;
59///
60/// let options = GenerationOptions::builder()
61///     .temperature(0.7)
62///     .max_response_tokens(500)
63///     .build();
64/// ```
65#[derive(Debug, Clone, Default, Serialize, Deserialize)]
66pub struct GenerationOptions {
67    /// Temperature for sampling (0.0-2.0).
68    /// Higher values produce more random outputs.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub temperature: Option<f64>,
71
72    /// Sampling strategy.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub sampling: Option<Sampling>,
75
76    /// Maximum number of tokens in the response.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    #[serde(rename = "maximumResponseTokens")]
79    pub max_response_tokens: Option<u32>,
80
81    /// Random seed for reproducible generation.
82    ///
83    /// **Note**: This field is currently not supported by Apple's `GenerationOptions` API
84    /// and is ignored. It is included for potential future use.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub seed: Option<u64>,
87
88    /// Tool-calling mode (Foundation Models 27).
89    ///
90    /// Ignored on pre-27 build SDKs and runtimes, where the framework
91    /// behaves as [`ToolCallingMode::Allowed`].
92    #[serde(skip_serializing_if = "Option::is_none")]
93    #[serde(rename = "toolCallingMode")]
94    pub tool_calling_mode: Option<ToolCallingMode>,
95}
96
97impl GenerationOptions {
98    /// Creates a new builder for configuring generation options.
99    pub fn builder() -> GenerationOptionsBuilder {
100        GenerationOptionsBuilder::default()
101    }
102
103    /// Serializes the options to JSON for FFI.
104    pub fn to_json(&self) -> String {
105        serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
106    }
107}
108
109/// Builder for configuring [`GenerationOptions`].
110#[derive(Debug, Default)]
111pub struct GenerationOptionsBuilder {
112    temperature: Option<f64>,
113    sampling: Option<Sampling>,
114    max_response_tokens: Option<u32>,
115    seed: Option<u64>,
116    tool_calling_mode: Option<ToolCallingMode>,
117}
118
119impl GenerationOptionsBuilder {
120    /// Sets the temperature for generation.
121    ///
122    /// Temperature influences the confidence of the model's response.
123    /// Higher values (e.g., 1.5) produce more random outputs.
124    /// Lower values (e.g., 0.2) produce more deterministic outputs.
125    ///
126    /// Valid range: 0.0 to 2.0. Values outside this range are ignored
127    /// and the default temperature is used instead.
128    pub fn temperature(mut self, temp: f64) -> Self {
129        if (0.0..=2.0).contains(&temp) {
130            self.temperature = Some(temp);
131        }
132        self
133    }
134
135    /// Sets the temperature, returning an error if out of range.
136    ///
137    /// This is the fallible version of [`temperature`](Self::temperature).
138    /// Use this when you want to catch invalid temperature values at build time.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error if `temp` is not in the range 0.0 to 2.0.
143    pub fn try_temperature(mut self, temp: f64) -> Result<Self, crate::Error> {
144        if (0.0..=2.0).contains(&temp) {
145            self.temperature = Some(temp);
146            Ok(self)
147        } else {
148            Err(crate::Error::InvalidInput(format!(
149                "Temperature must be between 0.0 and 2.0, got {temp}"
150            )))
151        }
152    }
153
154    /// Sets the sampling strategy.
155    pub fn sampling(mut self, sampling: Sampling) -> Self {
156        self.sampling = Some(sampling);
157        self
158    }
159
160    /// Sets the maximum number of tokens in the response.
161    ///
162    /// Only use this when you need to protect against unexpectedly verbose responses.
163    /// Enforcing a strict token limit can lead to malformed or grammatically incorrect output.
164    pub fn max_response_tokens(mut self, tokens: u32) -> Self {
165        if tokens > 0 {
166            self.max_response_tokens = Some(tokens);
167        }
168        self
169    }
170
171    /// Sets the random seed for reproducible generation.
172    ///
173    /// **Note**: This is currently not supported by Apple's `GenerationOptions` API
174    /// and will be ignored. Included for potential future use.
175    pub fn seed(mut self, seed: u64) -> Self {
176        self.seed = Some(seed);
177        self
178    }
179
180    /// Sets the tool-calling mode (Foundation Models 27).
181    ///
182    /// Ignored on pre-27 build SDKs and runtimes.
183    pub fn tool_calling_mode(mut self, mode: ToolCallingMode) -> Self {
184        self.tool_calling_mode = Some(mode);
185        self
186    }
187
188    /// Builds the [`GenerationOptions`].
189    pub fn build(self) -> GenerationOptions {
190        GenerationOptions {
191            temperature: self.temperature,
192            sampling: self.sampling,
193            max_response_tokens: self.max_response_tokens,
194            seed: self.seed,
195            tool_calling_mode: self.tool_calling_mode,
196        }
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use crate::options::{GenerationOptions, ReasoningLevel, Sampling, ToolCallingMode};
203
204    #[test]
205    fn test_default_options() {
206        let options = GenerationOptions::default();
207        assert!(options.temperature.is_none());
208        assert!(options.sampling.is_none());
209        assert!(options.max_response_tokens.is_none());
210    }
211
212    #[test]
213    fn test_builder() {
214        let options = GenerationOptions::builder()
215            .temperature(0.7)
216            .sampling(Sampling::Random)
217            .max_response_tokens(500)
218            .seed(42)
219            .build();
220
221        assert_eq!(options.temperature, Some(0.7));
222        assert_eq!(options.sampling, Some(Sampling::Random));
223        assert_eq!(options.max_response_tokens, Some(500));
224        assert_eq!(options.seed, Some(42));
225    }
226
227    #[test]
228    fn test_temperature_bounds() {
229        // Valid temperature
230        let options = GenerationOptions::builder().temperature(1.5).build();
231        assert_eq!(options.temperature, Some(1.5));
232
233        // Out of bounds (negative)
234        let options = GenerationOptions::builder().temperature(-0.5).build();
235        assert!(options.temperature.is_none());
236
237        // Out of bounds (too high)
238        let options = GenerationOptions::builder().temperature(3.0).build();
239        assert!(options.temperature.is_none());
240    }
241
242    #[test]
243    fn test_json_serialization() {
244        let options = GenerationOptions::builder()
245            .temperature(0.7)
246            .max_response_tokens(100)
247            .build();
248
249        let json = options.to_json();
250        assert!(json.contains("temperature"));
251        assert!(json.contains("0.7"));
252    }
253
254    #[test]
255    fn tool_calling_mode_serializes_with_stable_names() {
256        let options = GenerationOptions::builder()
257            .tool_calling_mode(ToolCallingMode::Required)
258            .build();
259        assert_eq!(options.to_json(), r#"{"toolCallingMode":"required"}"#);
260
261        let options = GenerationOptions::builder()
262            .tool_calling_mode(ToolCallingMode::Disallowed)
263            .build();
264        assert!(options.to_json().contains("disallowed"));
265    }
266
267    #[test]
268    fn reasoning_levels_have_stable_ffi_codes() {
269        assert_eq!(ReasoningLevel::Light.as_ffi_code(), 1);
270        assert_eq!(ReasoningLevel::Moderate.as_ffi_code(), 2);
271        assert_eq!(ReasoningLevel::Deep.as_ffi_code(), 3);
272    }
273}