Skip to main content

open_agent/types/
protocol.rs

1//! Which HTTP API an endpoint speaks.
2//!
3//! The SDK started as an OpenAI-compatible client and the shape of that API was baked into
4//! the request path, the auth header, the request body and the streaming vocabulary. Several
5//! providers that are otherwise ordinary OpenAI-compatible vendors publish their
6//! subscription tiers only behind an Anthropic-shaped `/messages` endpoint, so "which
7//! protocol" became a per-endpoint fact rather than a property of the SDK.
8//!
9//! This is deliberately not a provider enum. It names the wire format, so a new vendor
10//! speaking an existing protocol needs no change here.
11
12/// The wire protocol an endpoint exposes.
13///
14/// Selects the request path, the authentication header, the request body shape and the
15/// streaming event vocabulary. Defaults to [`ApiProtocol::OpenAiChat`], which is what every
16/// endpoint the SDK supported before 0.9.0 speaks.
17///
18/// # Examples
19///
20/// ```rust
21/// use open_agent::ApiProtocol;
22///
23/// assert_eq!(ApiProtocol::default(), ApiProtocol::OpenAiChat);
24/// assert_eq!(ApiProtocol::Anthropic.path(), "/messages");
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27#[non_exhaustive]
28pub enum ApiProtocol {
29    /// OpenAI chat completions: `POST {base_url}/chat/completions`, bearer auth.
30    #[default]
31    OpenAiChat,
32
33    /// Anthropic messages: `POST {base_url}/messages`, `x-api-key` auth.
34    Anthropic,
35}
36
37impl ApiProtocol {
38    /// The path appended to `base_url` to reach the completion endpoint.
39    ///
40    /// Includes the leading slash, because the request URL is built from `base_url` with its
41    /// trailing slashes removed.
42    pub fn path(&self) -> &'static str {
43        match self {
44            Self::OpenAiChat => "/chat/completions",
45            Self::Anthropic => "/messages",
46        }
47    }
48
49    /// The lowercase name used in configuration files and diagnostics.
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            Self::OpenAiChat => "openai",
53            Self::Anthropic => "anthropic",
54        }
55    }
56
57    /// Parses a protocol name, ASCII-case-insensitively.
58    ///
59    /// Returns `None` for anything unrecognised, so a caller reading a config file can name
60    /// the offending value in its own error rather than silently falling back to a default
61    /// the user did not ask for.
62    ///
63    /// `openai` is accepted alongside `openai-chat` and `openai_chat`: configuration files
64    /// in the wild write it every way, and rejecting the short form would be a trap with no
65    /// upside.
66    ///
67    /// # Examples
68    ///
69    /// ```rust
70    /// use open_agent::ApiProtocol;
71    ///
72    /// assert_eq!(ApiProtocol::from_wire("Anthropic"), Some(ApiProtocol::Anthropic));
73    /// assert_eq!(ApiProtocol::from_wire("openai_chat"), Some(ApiProtocol::OpenAiChat));
74    /// assert_eq!(ApiProtocol::from_wire("cohere"), None);
75    /// ```
76    pub fn from_wire(raw: &str) -> Option<Self> {
77        match raw {
78            s if s.eq_ignore_ascii_case("openai")
79                || s.eq_ignore_ascii_case("openai-chat")
80                || s.eq_ignore_ascii_case("openai_chat") =>
81            {
82                Some(Self::OpenAiChat)
83            }
84            s if s.eq_ignore_ascii_case("anthropic") => Some(Self::Anthropic),
85            _ => None,
86        }
87    }
88}
89
90impl std::fmt::Display for ApiProtocol {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.write_str(self.as_str())
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn default_is_openai_chat() {
102        assert_eq!(ApiProtocol::default(), ApiProtocol::OpenAiChat);
103    }
104
105    #[test]
106    fn each_protocol_has_its_own_path() {
107        assert_eq!(ApiProtocol::OpenAiChat.path(), "/chat/completions");
108        assert_eq!(ApiProtocol::Anthropic.path(), "/messages");
109    }
110
111    #[test]
112    fn each_protocol_has_its_own_name() {
113        assert_eq!(ApiProtocol::OpenAiChat.as_str(), "openai");
114        assert_eq!(ApiProtocol::Anthropic.as_str(), "anthropic");
115    }
116
117    #[test]
118    fn from_wire_is_case_insensitive() {
119        assert_eq!(
120            ApiProtocol::from_wire("ANTHROPIC"),
121            Some(ApiProtocol::Anthropic)
122        );
123        assert_eq!(
124            ApiProtocol::from_wire("OpenAI"),
125            Some(ApiProtocol::OpenAiChat)
126        );
127    }
128
129    #[test]
130    fn from_wire_accepts_every_spelling_of_openai() {
131        for spelling in ["openai", "openai-chat", "openai_chat"] {
132            assert_eq!(
133                ApiProtocol::from_wire(spelling),
134                Some(ApiProtocol::OpenAiChat),
135                "{spelling} should parse"
136            );
137        }
138    }
139
140    #[test]
141    fn from_wire_rejects_an_unknown_protocol() {
142        assert_eq!(ApiProtocol::from_wire("cohere"), None);
143        assert_eq!(ApiProtocol::from_wire(""), None);
144    }
145
146    #[test]
147    fn display_matches_as_str() {
148        assert_eq!(ApiProtocol::Anthropic.to_string(), "anthropic");
149        assert_eq!(ApiProtocol::OpenAiChat.to_string(), "openai");
150    }
151
152    #[test]
153    fn from_wire_round_trips_as_str() {
154        for protocol in [ApiProtocol::OpenAiChat, ApiProtocol::Anthropic] {
155            assert_eq!(ApiProtocol::from_wire(protocol.as_str()), Some(protocol));
156        }
157    }
158}