1use async_trait::async_trait;
9use futures_util::StreamExt;
10use serde::{Deserialize, Serialize};
11use tokio_util::sync::CancellationToken;
12
13use rinne_core::worker::{emit, EventSink, Usage, WorkerEvent};
14use rinne_core::{Result, RinneError};
15
16#[derive(Debug, Clone, Serialize)]
18pub struct ChatMessage {
19 pub role: String,
20 pub content: String,
21}
22
23impl ChatMessage {
24 pub fn system(content: impl Into<String>) -> Self {
25 Self {
26 role: "system".into(),
27 content: content.into(),
28 }
29 }
30 pub fn user(content: impl Into<String>) -> Self {
31 Self {
32 role: "user".into(),
33 content: content.into(),
34 }
35 }
36}
37
38#[derive(Debug, Clone)]
40pub struct ChatRequest {
41 pub model: String,
42 pub messages: Vec<ChatMessage>,
43 pub temperature: Option<f32>,
44 pub extra: Option<serde_json::Value>,
46}
47
48#[derive(Debug, Clone)]
50pub struct ChatResponse {
51 pub content: String,
52 pub usage: Usage,
53 pub finish_reason: Option<String>,
54}
55
56#[derive(Debug, Clone)]
59pub struct DiscoveredModel {
60 pub id: String,
61 pub prompt_price: Option<f64>,
63 pub context: Option<u64>,
65}
66
67#[derive(Clone)]
69pub struct OpenAiClient {
70 http: reqwest::Client,
71 base_url: String,
73 api_key: Option<String>,
74}
75
76impl OpenAiClient {
77 pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {
78 Self {
79 http: reqwest::Client::new(),
80 base_url: normalize_base_url(&base_url.into()),
81 api_key,
82 }
83 }
84
85 pub async fn list_models(&self) -> Result<Vec<DiscoveredModel>> {
89 let url = format!("{}/models", self.base_url);
90 let mut builder = self.http.get(&url);
91 if let Some(key) = &self.api_key {
92 builder = builder.bearer_auth(key);
93 }
94 let resp = builder
95 .send()
96 .await
97 .map_err(|e| RinneError::Worker(format!("models request failed: {e}")))?;
98 if !resp.status().is_success() {
99 let status = resp.status();
100 let text = resp.text().await.unwrap_or_default();
101 return Err(RinneError::Worker(format!("GET /models HTTP {status}: {text}")));
102 }
103 let v: serde_json::Value = resp
104 .json()
105 .await
106 .map_err(|e| RinneError::Worker(format!("bad /models json: {e}")))?;
107
108 let items = v
111 .get("data")
112 .and_then(|d| d.as_array())
113 .or_else(|| v.as_array())
114 .cloned()
115 .unwrap_or_default();
116
117 let mut models: Vec<DiscoveredModel> = items
118 .iter()
119 .filter_map(|m| {
120 let id = m.get("id").and_then(|x| x.as_str())?.to_string();
121 let prompt_price = m
122 .get("pricing")
123 .and_then(|p| p.get("prompt"))
124 .and_then(to_f64);
125 let context = m
126 .get("context_length")
127 .or_else(|| m.get("context_window"))
128 .and_then(|c| c.as_u64());
129 Some(DiscoveredModel {
130 id,
131 prompt_price,
132 context,
133 })
134 })
135 .collect();
136
137 models.sort_by(|a, b| match (a.prompt_price, b.prompt_price) {
139 (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
140 (Some(_), None) => std::cmp::Ordering::Less,
141 (None, Some(_)) => std::cmp::Ordering::Greater,
142 (None, None) => a.id.cmp(&b.id),
143 });
144 Ok(models)
145 }
146
147 pub async fn chat_stream(
150 &self,
151 req: &ChatRequest,
152 events: &EventSink,
153 cancel: &CancellationToken,
154 ) -> Result<ChatResponse> {
155 let url = format!("{}/chat/completions", self.base_url);
156 let mut body = serde_json::json!({
157 "model": req.model,
158 "messages": req.messages,
159 "temperature": req.temperature,
160 "stream": true,
161 "stream_options": { "include_usage": true },
162 });
163 if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
165 (&req.extra, body.as_object_mut())
166 {
167 for (k, v) in extra {
168 obj.insert(k.clone(), v.clone());
169 }
170 }
171
172 let mut builder = self.http.post(&url).json(&body);
173 if let Some(key) = &self.api_key {
174 builder = builder.bearer_auth(key);
175 }
176
177 let resp = builder
178 .send()
179 .await
180 .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
181
182 if !resp.status().is_success() {
183 let status = resp.status();
184 let text = resp.text().await.unwrap_or_default();
185 return Err(RinneError::Worker(format!(
186 "chat completion HTTP {status}: {text}"
187 )));
188 }
189
190 let mut content = String::new();
191 let mut usage = Usage::default();
192 let mut finish_reason = None;
193 let mut buf = String::new();
194
195 let mut stream = resp.bytes_stream();
196 loop {
197 tokio::select! {
198 _ = cancel.cancelled() => {
199 return Ok(ChatResponse { content, usage, finish_reason: Some("cancelled".into()) });
200 }
201 chunk = stream.next() => {
202 let Some(chunk) = chunk else { break };
203 let bytes = chunk.map_err(|e| RinneError::Worker(format!("stream error: {e}")))?;
204 buf.push_str(&String::from_utf8_lossy(&bytes));
205 while let Some(nl) = buf.find('\n') {
207 let line = buf[..nl].trim().to_string();
208 buf.drain(..=nl);
209 if let Some(delta) = parse_sse_line(&line, &mut usage, &mut finish_reason)? {
210 if !delta.is_empty() {
211 emit(events, WorkerEvent::Message(delta.clone()));
212 content.push_str(&delta);
213 }
214 }
215 }
216 }
217 }
218 }
219
220 emit(events, WorkerEvent::Done);
221 Ok(ChatResponse {
222 content,
223 usage,
224 finish_reason,
225 })
226 }
227}
228
229pub fn normalize_base_url(raw: &str) -> String {
234 let mut b = raw.trim().trim_end_matches('/');
235 for suffix in ["/chat/completions", "/responses", "/completions", "/models"] {
236 if let Some(stripped) = b.strip_suffix(suffix) {
237 b = stripped.trim_end_matches('/');
238 break;
239 }
240 }
241 b.to_string()
242}
243
244fn to_f64(v: &serde_json::Value) -> Option<f64> {
247 v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok()))
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 #[test]
255 fn base_url_normalization_strips_pasted_endpoints() {
256 let base = "https://openrouter.ai/api/v1";
257 assert_eq!(normalize_base_url(base), base);
258 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/"), base);
259 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/chat/completions"), base);
260 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/responses"), base);
261 assert_eq!(normalize_base_url(" https://openrouter.ai/api/v1/models "), base);
262 }
263}
264
265fn parse_sse_line(
268 line: &str,
269 usage: &mut Usage,
270 finish_reason: &mut Option<String>,
271) -> Result<Option<String>> {
272 let Some(data) = line.strip_prefix("data:") else {
273 return Ok(None);
274 };
275 let data = data.trim();
276 if data.is_empty() || data == "[DONE]" {
277 return Ok(None);
278 }
279
280 let chunk: ChatChunk =
281 serde_json::from_str(data).map_err(|e| RinneError::Worker(format!("bad SSE json: {e}")))?;
282
283 if let Some(u) = chunk.usage {
284 usage.prompt_tokens = u.prompt_tokens;
285 usage.completion_tokens = u.completion_tokens;
286 }
287
288 let mut delta_text = String::new();
289 for choice in chunk.choices {
290 if let Some(fr) = choice.finish_reason {
291 *finish_reason = Some(fr);
292 }
293 if let Some(c) = choice.delta.content {
294 delta_text.push_str(&c);
295 }
296 }
297 Ok(Some(delta_text))
298}
299
300#[derive(Deserialize)]
301struct ChatChunk {
302 #[serde(default)]
303 choices: Vec<ChunkChoice>,
304 #[serde(default)]
305 usage: Option<ApiUsage>,
306}
307
308#[derive(Deserialize)]
309struct ChunkChoice {
310 delta: Delta,
311 #[serde(default)]
312 finish_reason: Option<String>,
313}
314
315#[derive(Deserialize)]
316struct Delta {
317 #[serde(default)]
318 content: Option<String>,
319}
320
321#[derive(Deserialize)]
322struct ApiUsage {
323 #[serde(default)]
324 prompt_tokens: u64,
325 #[serde(default)]
326 completion_tokens: u64,
327}
328
329#[async_trait]
332pub trait ChatBackend: Send + Sync {
333 async fn complete(
334 &self,
335 req: &ChatRequest,
336 events: &EventSink,
337 cancel: &CancellationToken,
338 ) -> Result<ChatResponse>;
339}
340
341#[async_trait]
342impl ChatBackend for OpenAiClient {
343 async fn complete(
344 &self,
345 req: &ChatRequest,
346 events: &EventSink,
347 cancel: &CancellationToken,
348 ) -> Result<ChatResponse> {
349 self.chat_stream(req, events, cancel).await
350 }
351}