Skip to main content

adk_model/openrouter/
config.rs

1//! Configuration types for the OpenRouter provider.
2
3use adk_core::{AdkError, ErrorCategory, ErrorComponent};
4use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
5use serde::{Deserialize, Serialize};
6
7/// Default OpenRouter API base URL.
8pub const OPENROUTER_API_BASE: &str = "https://openrouter.ai/api/v1";
9
10const HTTP_REFERER_HEADER: &str = "http-referer";
11const X_OPENROUTER_TITLE_HEADER: &str = "x-openrouter-title";
12const X_TITLE_HEADER: &str = "x-title";
13
14/// Default API surface used by the `Llm` adapter.
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum OpenRouterApiMode {
18    /// Use the chat-completions API surface (default).
19    #[default]
20    ChatCompletions,
21    /// Use the Responses API surface.
22    Responses,
23}
24
25/// OpenRouter configuration shared by native APIs and the `Llm` adapter.
26///
27/// The API key is redacted from `Debug` output and omitted when serializing.
28#[derive(Clone, Serialize, Deserialize)]
29pub struct OpenRouterConfig {
30    /// OpenRouter API key. Never serialized; deserializing a config without it
31    /// yields an empty key.
32    #[serde(skip_serializing, default)]
33    pub api_key: String,
34    /// Default model name.
35    pub model: String,
36    /// Base URL for the OpenRouter API.
37    pub base_url: String,
38    /// Optional site URL sent as `HTTP-Referer`.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub http_referer: Option<String>,
41    /// Optional app title sent as `X-OpenRouter-Title` and `X-Title`.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub title: Option<String>,
44    /// Default API mode used when the generic `Llm` adapter is invoked.
45    #[serde(default)]
46    pub default_api_mode: OpenRouterApiMode,
47}
48
49impl std::fmt::Debug for OpenRouterConfig {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.debug_struct("OpenRouterConfig")
52            .field("api_key", &"[REDACTED]")
53            .field("model", &self.model)
54            .field("base_url", &self.base_url)
55            .field("http_referer", &self.http_referer)
56            .field("title", &self.title)
57            .field("default_api_mode", &self.default_api_mode)
58            .finish()
59    }
60}
61
62impl OpenRouterConfig {
63    /// Create a new OpenRouter config using the default API base URL.
64    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
65        Self {
66            api_key: api_key.into(),
67            model: model.into(),
68            base_url: OPENROUTER_API_BASE.to_string(),
69            http_referer: None,
70            title: None,
71            default_api_mode: OpenRouterApiMode::default(),
72        }
73    }
74
75    /// Override the API base URL.
76    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
77        self.base_url = base_url.into();
78        self
79    }
80
81    /// Set the optional `HTTP-Referer` attribution header.
82    pub fn with_http_referer(mut self, http_referer: impl Into<String>) -> Self {
83        self.http_referer = Some(http_referer.into());
84        self
85    }
86
87    /// Set the optional OpenRouter app title header.
88    pub fn with_title(mut self, title: impl Into<String>) -> Self {
89        self.title = Some(title.into());
90        self
91    }
92
93    /// Set the default API mode used by the generic `Llm` adapter.
94    pub fn with_default_api_mode(mut self, default_api_mode: OpenRouterApiMode) -> Self {
95        self.default_api_mode = default_api_mode;
96        self
97    }
98
99    /// Return the normalized API base URL without a trailing slash.
100    pub fn effective_base_url(&self) -> &str {
101        self.base_url.trim_end_matches('/')
102    }
103
104    /// Build an absolute endpoint URL from a relative OpenRouter API path.
105    pub fn endpoint_url(&self, path: &str) -> String {
106        format!("{}/{}", self.effective_base_url(), path.trim_start_matches('/'))
107    }
108
109    /// Build the shared default headers used for all OpenRouter requests.
110    pub fn default_headers(&self) -> Result<HeaderMap, AdkError> {
111        let mut headers = HeaderMap::new();
112
113        let mut authorization = HeaderValue::from_str(&format!("Bearer {}", self.api_key))
114            .map_err(|err| {
115                invalid_header_error(
116                    "authorization",
117                    "OpenRouter API key produced an invalid Authorization header",
118                )
119                .with_source(err)
120            })?;
121        authorization.set_sensitive(true);
122
123        headers.insert(AUTHORIZATION, authorization);
124        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
125        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
126
127        if let Some(http_referer) = &self.http_referer {
128            headers.insert(
129                HeaderName::from_static(HTTP_REFERER_HEADER),
130                HeaderValue::from_str(http_referer).map_err(|err| {
131                    invalid_header_error(
132                        "http_referer",
133                        "OpenRouter HTTP-Referer header contains invalid characters",
134                    )
135                    .with_source(err)
136                })?,
137            );
138        }
139
140        if let Some(title) = &self.title {
141            let title_value = HeaderValue::from_str(title).map_err(|err| {
142                invalid_header_error("title", "OpenRouter title header contains invalid characters")
143                    .with_source(err)
144            })?;
145
146            headers.insert(HeaderName::from_static(X_OPENROUTER_TITLE_HEADER), title_value.clone());
147            headers.insert(HeaderName::from_static(X_TITLE_HEADER), title_value);
148        }
149
150        Ok(headers)
151    }
152}
153
154fn invalid_header_error(field: &'static str, message: &'static str) -> AdkError {
155    AdkError::new(
156        ErrorComponent::Model,
157        ErrorCategory::InvalidInput,
158        "model.openrouter.invalid_header",
159        format!("{message}: {field}"),
160    )
161    .with_provider("openrouter")
162}
163
164#[cfg(test)]
165mod tests {
166    use super::{
167        HTTP_REFERER_HEADER, OpenRouterApiMode, OpenRouterConfig, X_OPENROUTER_TITLE_HEADER,
168        X_TITLE_HEADER,
169    };
170    use reqwest::header::{AUTHORIZATION, HeaderName};
171
172    #[test]
173    fn default_headers_include_authorization_and_attribution_headers() {
174        let config = OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2")
175            .with_http_referer("https://example.com")
176            .with_title("Example App");
177
178        let headers = config.default_headers().expect("headers should build");
179
180        assert_eq!(
181            headers.get(AUTHORIZATION).and_then(|value| value.to_str().ok()),
182            Some("Bearer sk-or-test")
183        );
184        assert_eq!(
185            headers
186                .get(HeaderName::from_static(HTTP_REFERER_HEADER))
187                .and_then(|value| value.to_str().ok()),
188            Some("https://example.com")
189        );
190        assert_eq!(
191            headers
192                .get(HeaderName::from_static(X_OPENROUTER_TITLE_HEADER))
193                .and_then(|value| value.to_str().ok()),
194            Some("Example App")
195        );
196        assert_eq!(
197            headers
198                .get(HeaderName::from_static(X_TITLE_HEADER))
199                .and_then(|value| value.to_str().ok()),
200            Some("Example App")
201        );
202    }
203
204    #[test]
205    fn endpoint_url_normalizes_trailing_slashes() {
206        let config = OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2")
207            .with_base_url("https://openrouter.ai/api/v1/");
208
209        assert_eq!(
210            config.endpoint_url("/chat/completions"),
211            "https://openrouter.ai/api/v1/chat/completions"
212        );
213    }
214
215    #[test]
216    fn config_builder_sets_default_api_mode() {
217        let config = OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2")
218            .with_default_api_mode(OpenRouterApiMode::Responses);
219
220        assert_eq!(config.default_api_mode, OpenRouterApiMode::Responses);
221    }
222}