Skip to main content

objectiveai_sdk/agent/openrouter/
stop.rs

1//! Stop sequence configuration for Agents.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// Stop sequences that terminate model generation.
7///
8/// When the model generates any of these sequences, it immediately
9/// stops producing further tokens.
10#[derive(
11    Debug,
12    Clone,
13    PartialEq,
14    Serialize,
15    Deserialize,
16    JsonSchema,
17    arbitrary::Arbitrary,
18)]
19#[serde(untagged)]
20#[schemars(rename = "agent.openrouter.Stop")]
21pub enum Stop {
22    /// A single stop sequence.
23    #[schemars(title = "String")]
24    String(String),
25    /// Multiple stop sequences (up to 4 typically supported).
26    #[schemars(title = "Strings")]
27    Strings(Vec<String>),
28}
29
30impl Stop {
31    /// Normalizes the stop configuration for deterministic hashing.
32    ///
33    /// - Empty arrays become `None`
34    /// - Single-element arrays become `String` variant
35    /// - Multi-element arrays are sorted and deduplicated
36    pub fn prepare(self) -> Option<Self> {
37        if let Stop::Strings(mut strings) = self {
38            if strings.is_empty() {
39                None
40            } else if strings.len() == 1 {
41                Some(Stop::String(strings.into_iter().next().unwrap()))
42            } else {
43                strings.sort();
44                strings.dedup();
45                Some(Stop::Strings(strings))
46            }
47        } else {
48            Some(self)
49        }
50    }
51
52    /// Validates that stop sequences are non-empty strings.
53    pub fn validate(&self) -> Result<(), String> {
54        match self {
55            Stop::String(string) if string.is_empty() => {
56                Err("`stop` string cannot be empty".to_string())
57            }
58            Stop::Strings(strings) if strings.iter().any(|s| s.is_empty()) => {
59                Err("`stop` strings cannot be empty".to_string())
60            }
61            _ => Ok(()),
62        }
63    }
64}