Skip to main content

rinne_workers/transport/
http.rs

1//! The `http` transport (`CONTEXT.md` §8, §14).
2//!
3//! One OpenAI-compatible chat client over `reqwest`, with a configurable base
4//! URL. It covers every OpenAI-format API worker and (in Phase 4) every
5//! conductor backend. Responses are streamed via SSE so deltas reach the event
6//! sink as they arrive, and final token usage is captured.
7
8use 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/// A chat message in the OpenAI format.
17#[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/// A chat completion request.
39#[derive(Debug, Clone)]
40pub struct ChatRequest {
41    pub model: String,
42    pub messages: Vec<ChatMessage>,
43    pub temperature: Option<f32>,
44    /// Extra JSON merged into the request body (provider-specific params).
45    pub extra: Option<serde_json::Value>,
46}
47
48/// The accumulated result of a (streamed) chat completion.
49#[derive(Debug, Clone)]
50pub struct ChatResponse {
51    pub content: String,
52    pub usage: Usage,
53    pub finish_reason: Option<String>,
54}
55
56/// A model offered by a platform's `/v1/models` endpoint, with optional cost
57/// and context metadata where the platform provides it (e.g. OpenRouter).
58#[derive(Debug, Clone)]
59pub struct DiscoveredModel {
60    pub id: String,
61    /// Prompt price per token (USD), if the platform reports it. Lower = cheaper.
62    pub prompt_price: Option<f64>,
63    /// Context window in tokens, if reported.
64    pub context: Option<u64>,
65}
66
67/// An OpenAI-compatible chat client over a configurable base URL.
68#[derive(Clone)]
69pub struct OpenAiClient {
70    http: reqwest::Client,
71    /// Base URL including the API version, e.g. `https://api.openai.com/v1`.
72    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    /// Discover the models this endpoint+key can access via `GET /models`.
86    /// Sorted cheapest→most-expensive where pricing is reported (others last),
87    /// so the result doubles as a price-ordered tier ladder.
88    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        // OpenAI shape: { "data": [ { "id", ... } ] }. Some platforms return a
109        // bare array. Pricing/context fields are platform-specific (OpenRouter).
110        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        // Cheapest first; models without pricing sink to the end.
138        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    /// Stream a chat completion, emitting each content delta as a
148    /// [`WorkerEvent::Message`] and returning the accumulated response.
149    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        // Merge provider-specific extra params (e.g. chat_template_kwargs).
164        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                    // SSE frames are separated by newlines; process complete lines.
206                    while let Some(nl) = buf.find('\n') {
207                        let line = buf[..nl].trim().to_string();
208                        buf.drain(..=nl);
209                        let parsed = parse_sse_line(&line, &mut usage, &mut finish_reason)?;
210                        if let Some(reasoning) = parsed.reasoning {
211                            if !reasoning.is_empty() {
212                                emit(events, WorkerEvent::Thinking(reasoning));
213                            }
214                        }
215                        if let Some(delta) = parsed.content {
216                            if !delta.is_empty() {
217                                emit(events, WorkerEvent::Token(delta.clone()));
218                                content.push_str(&delta);
219                            }
220                        }
221                    }
222                }
223            }
224        }
225
226        emit(events, WorkerEvent::Done);
227        Ok(ChatResponse {
228            content,
229            usage,
230            finish_reason,
231        })
232    }
233}
234
235/// Normalize an OpenAI-compatible base URL. We append our own path
236/// (`/chat/completions`, `/models`), so a user who pastes a full endpoint URL
237/// from a provider's docs gets it stripped back to the base rather than a
238/// doubled path (`…/chat/completions/chat/completions` → 404).
239pub fn normalize_base_url(raw: &str) -> String {
240    let mut b = raw.trim().trim_end_matches('/');
241    for suffix in ["/chat/completions", "/responses", "/completions", "/models"] {
242        if let Some(stripped) = b.strip_suffix(suffix) {
243            b = stripped.trim_end_matches('/');
244            break;
245        }
246    }
247    b.to_string()
248}
249
250/// Parse a JSON value that may be a number or a numeric string into `f64`
251/// (OpenRouter reports prices as strings like `"0.0000001"`).
252fn to_f64(v: &serde_json::Value) -> Option<f64> {
253    v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok()))
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn base_url_normalization_strips_pasted_endpoints() {
262        let base = "https://openrouter.ai/api/v1";
263        assert_eq!(normalize_base_url(base), base);
264        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/"), base);
265        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/chat/completions"), base);
266        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/responses"), base);
267        assert_eq!(normalize_base_url("  https://openrouter.ai/api/v1/models  "), base);
268    }
269}
270
271/// The content + reasoning deltas extracted from one SSE chunk.
272#[derive(Default)]
273struct SseDelta {
274    content: Option<String>,
275    reasoning: Option<String>,
276}
277
278/// Parse one SSE line into its content and reasoning deltas. Side-effects usage
279/// and finish_reason as they appear. Reasoning is read from the de-facto fields
280/// (`reasoning_content` — DeepSeek; `reasoning` — OpenRouter and others).
281fn parse_sse_line(
282    line: &str,
283    usage: &mut Usage,
284    finish_reason: &mut Option<String>,
285) -> Result<SseDelta> {
286    let Some(data) = line.strip_prefix("data:") else {
287        return Ok(SseDelta::default());
288    };
289    let data = data.trim();
290    if data.is_empty() || data == "[DONE]" {
291        return Ok(SseDelta::default());
292    }
293
294    let chunk: ChatChunk =
295        serde_json::from_str(data).map_err(|e| RinneError::Worker(format!("bad SSE json: {e}")))?;
296
297    if let Some(u) = chunk.usage {
298        usage.prompt_tokens = u.prompt_tokens;
299        usage.completion_tokens = u.completion_tokens;
300    }
301
302    let mut content = String::new();
303    let mut reasoning = String::new();
304    for choice in chunk.choices {
305        if let Some(fr) = choice.finish_reason {
306            *finish_reason = Some(fr);
307        }
308        if let Some(c) = choice.delta.content {
309            content.push_str(&c);
310        }
311        if let Some(r) = choice.delta.reasoning_content.or(choice.delta.reasoning) {
312            reasoning.push_str(&r);
313        }
314    }
315    Ok(SseDelta {
316        content: (!content.is_empty()).then_some(content),
317        reasoning: (!reasoning.is_empty()).then_some(reasoning),
318    })
319}
320
321#[derive(Deserialize)]
322struct ChatChunk {
323    #[serde(default)]
324    choices: Vec<ChunkChoice>,
325    #[serde(default)]
326    usage: Option<ApiUsage>,
327}
328
329#[derive(Deserialize)]
330struct ChunkChoice {
331    delta: Delta,
332    #[serde(default)]
333    finish_reason: Option<String>,
334}
335
336#[derive(Deserialize)]
337struct Delta {
338    #[serde(default)]
339    content: Option<String>,
340    /// DeepSeek-style reasoning stream.
341    #[serde(default)]
342    reasoning_content: Option<String>,
343    /// OpenRouter/others-style reasoning stream.
344    #[serde(default)]
345    reasoning: Option<String>,
346}
347
348#[derive(Deserialize)]
349struct ApiUsage {
350    #[serde(default)]
351    prompt_tokens: u64,
352    #[serde(default)]
353    completion_tokens: u64,
354}
355
356/// Marker trait tie-in kept minimal for Phase 2; the API worker adapter wraps
357/// this client and implements `Worker`.
358#[async_trait]
359pub trait ChatBackend: Send + Sync {
360    async fn complete(
361        &self,
362        req: &ChatRequest,
363        events: &EventSink,
364        cancel: &CancellationToken,
365    ) -> Result<ChatResponse>;
366}
367
368#[async_trait]
369impl ChatBackend for OpenAiClient {
370    async fn complete(
371        &self,
372        req: &ChatRequest,
373        events: &EventSink,
374        cancel: &CancellationToken,
375    ) -> Result<ChatResponse> {
376        self.chat_stream(req, events, cancel).await
377    }
378}