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, ToolSpec, Usage, WorkerEvent};
14use rinne_core::{Result, RinneError};
15
16/// A chat message in the OpenAI format. The tool fields are only set on the
17/// host agentic loop: `tool_calls` on an assistant turn that calls tools,
18/// `tool_call_id` on a `tool`-role message carrying a call's result.
19#[derive(Debug, Clone, Serialize)]
20pub struct ChatMessage {
21    pub role: String,
22    #[serde(skip_serializing_if = "String::is_empty")]
23    pub content: String,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub tool_calls: Option<Vec<ToolCall>>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub tool_call_id: Option<String>,
28}
29
30impl ChatMessage {
31    pub fn system(content: impl Into<String>) -> Self {
32        Self::plain("system", content)
33    }
34    pub fn user(content: impl Into<String>) -> Self {
35        Self::plain("user", content)
36    }
37    fn plain(role: &str, content: impl Into<String>) -> Self {
38        Self {
39            role: role.into(),
40            content: content.into(),
41            tool_calls: None,
42            tool_call_id: None,
43        }
44    }
45    /// An assistant turn that requested tool calls (echoed back into the next
46    /// request so the model sees its own calls before their results).
47    pub fn assistant_tool_calls(calls: Vec<ToolCall>) -> Self {
48        Self {
49            role: "assistant".into(),
50            content: String::new(),
51            tool_calls: Some(calls),
52            tool_call_id: None,
53        }
54    }
55    /// The result of one tool call, keyed back to its `tool_call_id`.
56    pub fn tool_result(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
57        Self {
58            role: "tool".into(),
59            content: content.into(),
60            tool_calls: None,
61            tool_call_id: Some(tool_call_id.into()),
62        }
63    }
64}
65
66/// One tool call in the OpenAI function-calling format — serialized when echoing
67/// an assistant turn, deserialized when reading the model's response.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct ToolCall {
70    pub id: String,
71    #[serde(rename = "type", default = "function_kind")]
72    pub kind: String,
73    pub function: FunctionCall,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct FunctionCall {
78    pub name: String,
79    /// JSON-encoded arguments string (per the OpenAI schema).
80    #[serde(default)]
81    pub arguments: String,
82}
83
84fn function_kind() -> String {
85    "function".into()
86}
87
88/// One turn of the host agentic loop: either text (the model is done) or a set
89/// of tool calls to execute and feed back.
90#[derive(Debug, Clone)]
91pub struct ChatTurn {
92    pub content: String,
93    pub tool_calls: Vec<ToolCall>,
94    pub usage: Usage,
95    pub finish_reason: Option<String>,
96}
97
98/// A chat completion request.
99#[derive(Debug, Clone)]
100pub struct ChatRequest {
101    pub model: String,
102    pub messages: Vec<ChatMessage>,
103    pub temperature: Option<f32>,
104    /// Extra JSON merged into the request body (provider-specific params).
105    pub extra: Option<serde_json::Value>,
106}
107
108/// The accumulated result of a (streamed) chat completion.
109#[derive(Debug, Clone)]
110pub struct ChatResponse {
111    pub content: String,
112    pub usage: Usage,
113    pub finish_reason: Option<String>,
114}
115
116/// A model offered by a platform's `/v1/models` endpoint, with optional cost
117/// and context metadata where the platform provides it (e.g. OpenRouter).
118#[derive(Debug, Clone)]
119pub struct DiscoveredModel {
120    pub id: String,
121    /// Prompt price per token (USD), if the platform reports it. Lower = cheaper.
122    pub prompt_price: Option<f64>,
123    /// Context window in tokens, if reported.
124    pub context: Option<u64>,
125}
126
127/// An OpenAI-compatible chat client over a configurable base URL.
128#[derive(Clone)]
129pub struct OpenAiClient {
130    http: reqwest::Client,
131    /// Base URL including the API version, e.g. `https://api.openai.com/v1`.
132    base_url: String,
133    api_key: Option<String>,
134}
135
136impl OpenAiClient {
137    pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {
138        // Bound connection setup and idle reads so a dead/stalled endpoint can
139        // never wedge a call forever (reqwest has no default timeout). A total
140        // request timeout would cut off legitimately long streamed generations,
141        // so streaming relies on `read_timeout` (idle-between-bytes cap) and the
142        // non-streaming calls add their own per-request total timeout.
143        let http = reqwest::Client::builder()
144            .connect_timeout(std::time::Duration::from_secs(15))
145            .read_timeout(std::time::Duration::from_secs(120))
146            .build()
147            .unwrap_or_default();
148        Self {
149            http,
150            base_url: normalize_base_url(&base_url.into()),
151            api_key,
152        }
153    }
154
155    /// Discover the models this endpoint+key can access via `GET /models`.
156    /// Sorted cheapest→most-expensive where pricing is reported (others last),
157    /// so the result doubles as a price-ordered tier ladder.
158    pub async fn list_models(&self) -> Result<Vec<DiscoveredModel>> {
159        let url = format!("{}/models", self.base_url);
160        let mut builder = self.http.get(&url).timeout(std::time::Duration::from_secs(30));
161        if let Some(key) = &self.api_key {
162            builder = builder.bearer_auth(key);
163        }
164        let resp = builder
165            .send()
166            .await
167            .map_err(|e| RinneError::Worker(format!("models request failed: {e}")))?;
168        if !resp.status().is_success() {
169            let status = resp.status();
170            let text = resp.text().await.unwrap_or_default();
171            return Err(RinneError::Worker(format!("GET /models HTTP {status}: {text}")));
172        }
173        let v: serde_json::Value = resp
174            .json()
175            .await
176            .map_err(|e| RinneError::Worker(format!("bad /models json: {e}")))?;
177
178        // OpenAI shape: { "data": [ { "id", ... } ] }. Some platforms return a
179        // bare array. Pricing/context fields are platform-specific (OpenRouter).
180        let items = v
181            .get("data")
182            .and_then(|d| d.as_array())
183            .or_else(|| v.as_array())
184            .cloned()
185            .unwrap_or_default();
186
187        let mut models: Vec<DiscoveredModel> = items
188            .iter()
189            .filter_map(|m| {
190                let id = m.get("id").and_then(|x| x.as_str())?.to_string();
191                let prompt_price = m
192                    .get("pricing")
193                    .and_then(|p| p.get("prompt"))
194                    .and_then(to_f64);
195                let context = m
196                    .get("context_length")
197                    .or_else(|| m.get("context_window"))
198                    .and_then(|c| c.as_u64());
199                Some(DiscoveredModel {
200                    id,
201                    prompt_price,
202                    context,
203                })
204            })
205            .collect();
206
207        // Cheapest first; models without pricing sink to the end.
208        models.sort_by(|a, b| match (a.prompt_price, b.prompt_price) {
209            (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
210            (Some(_), None) => std::cmp::Ordering::Less,
211            (None, Some(_)) => std::cmp::Ordering::Greater,
212            (None, None) => a.id.cmp(&b.id),
213        });
214        Ok(models)
215    }
216
217    /// Run one non-streaming chat completion offering `tools`, returning whole
218    /// tool calls (streaming tool-call deltas are fiddly; the host loop wants
219    /// them complete). When `tools` is empty this is a plain completion.
220    pub async fn chat_with_tools(&self, req: &ChatRequest, tools: &[ToolSpec]) -> Result<ChatTurn> {
221        let url = format!("{}/chat/completions", self.base_url);
222        let mut body = serde_json::json!({
223            "model": req.model,
224            "messages": req.messages,
225            "temperature": req.temperature,
226            "stream": false,
227        });
228        if !tools.is_empty() {
229            let defs: Vec<serde_json::Value> = tools
230                .iter()
231                .map(|t| {
232                    serde_json::json!({
233                        "type": "function",
234                        "function": {
235                            "name": t.id,
236                            "description": t.description,
237                            "parameters": t.schema,
238                        }
239                    })
240                })
241                .collect();
242            if let Some(obj) = body.as_object_mut() {
243                obj.insert("tools".into(), serde_json::Value::Array(defs));
244                obj.insert("tool_choice".into(), serde_json::json!("auto"));
245            }
246        }
247        // Merge provider-specific extra params, as the streaming path does.
248        if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
249            (&req.extra, body.as_object_mut())
250        {
251            for (k, v) in extra {
252                obj.insert(k.clone(), v.clone());
253            }
254        }
255
256        // Non-streaming completion → a total per-request timeout is safe (no long
257        // stream to cut off) and bounds a stalled host tool-loop turn.
258        let mut builder = self
259            .http
260            .post(&url)
261            .timeout(std::time::Duration::from_secs(120))
262            .json(&body);
263        if let Some(key) = &self.api_key {
264            builder = builder.bearer_auth(key);
265        }
266        let resp = builder
267            .send()
268            .await
269            .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
270        if !resp.status().is_success() {
271            let status = resp.status();
272            let text = resp.text().await.unwrap_or_default();
273            return Err(RinneError::Worker(format!(
274                "chat completion HTTP {status}: {text}"
275            )));
276        }
277
278        let v: serde_json::Value = resp
279            .json()
280            .await
281            .map_err(|e| RinneError::Worker(format!("bad completion json: {e}")))?;
282        let message = &v["choices"][0]["message"];
283        let content = message["content"].as_str().unwrap_or("").to_string();
284        let tool_calls: Vec<ToolCall> = message
285            .get("tool_calls")
286            .filter(|t| !t.is_null())
287            .and_then(|t| serde_json::from_value(t.clone()).ok())
288            .unwrap_or_default();
289        let finish_reason = v["choices"][0]["finish_reason"].as_str().map(String::from);
290        let usage = Usage {
291            prompt_tokens: v["usage"]["prompt_tokens"].as_u64().unwrap_or(0),
292            completion_tokens: v["usage"]["completion_tokens"].as_u64().unwrap_or(0),
293            wall_ms: 0,
294        };
295        Ok(ChatTurn {
296            content,
297            tool_calls,
298            usage,
299            finish_reason,
300        })
301    }
302
303    /// Stream a chat completion, emitting each content delta as a
304    /// [`WorkerEvent::Message`] and returning the accumulated response.
305    pub async fn chat_stream(
306        &self,
307        req: &ChatRequest,
308        events: &EventSink,
309        cancel: &CancellationToken,
310    ) -> Result<ChatResponse> {
311        let url = format!("{}/chat/completions", self.base_url);
312        let mut body = serde_json::json!({
313            "model": req.model,
314            "messages": req.messages,
315            "temperature": req.temperature,
316            "stream": true,
317            "stream_options": { "include_usage": true },
318        });
319        // Merge provider-specific extra params (e.g. chat_template_kwargs).
320        if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
321            (&req.extra, body.as_object_mut())
322        {
323            for (k, v) in extra {
324                obj.insert(k.clone(), v.clone());
325            }
326        }
327
328        let mut builder = self.http.post(&url).json(&body);
329        if let Some(key) = &self.api_key {
330            builder = builder.bearer_auth(key);
331        }
332
333        let resp = builder
334            .send()
335            .await
336            .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
337
338        if !resp.status().is_success() {
339            let status = resp.status();
340            let text = resp.text().await.unwrap_or_default();
341            return Err(RinneError::Worker(format!(
342                "chat completion HTTP {status}: {text}"
343            )));
344        }
345
346        let mut content = String::new();
347        let mut usage = Usage::default();
348        let mut finish_reason = None;
349        // Accumulate raw bytes and decode only complete lines: a multi-byte UTF-8
350        // codepoint can straddle two network chunks, so decoding each chunk in
351        // isolation would corrupt it (`�`). `\n` (0x0A) never appears inside a
352        // multi-byte sequence, so splitting on it is safe.
353        let mut buf: Vec<u8> = Vec::new();
354
355        let mut stream = resp.bytes_stream();
356        loop {
357            tokio::select! {
358                _ = cancel.cancelled() => {
359                    return Ok(ChatResponse { content, usage, finish_reason: Some("cancelled".into()) });
360                }
361                chunk = stream.next() => {
362                    let Some(chunk) = chunk else { break };
363                    let bytes = chunk.map_err(|e| RinneError::Worker(format!("stream error: {e}")))?;
364                    buf.extend_from_slice(&bytes);
365                    // SSE frames are separated by newlines; process complete lines.
366                    while let Some(nl) = buf.iter().position(|&b| b == b'\n') {
367                        let line = String::from_utf8_lossy(&buf[..nl]).trim().to_string();
368                        buf.drain(..=nl);
369                        let parsed = parse_sse_line(&line, &mut usage, &mut finish_reason)?;
370                        if let Some(reasoning) = parsed.reasoning {
371                            if !reasoning.is_empty() {
372                                emit(events, WorkerEvent::Thinking(reasoning));
373                            }
374                        }
375                        if let Some(delta) = parsed.content {
376                            if !delta.is_empty() {
377                                emit(events, WorkerEvent::Token(delta.clone()));
378                                content.push_str(&delta);
379                            }
380                        }
381                    }
382                }
383            }
384        }
385
386        emit(events, WorkerEvent::Done);
387        Ok(ChatResponse {
388            content,
389            usage,
390            finish_reason,
391        })
392    }
393}
394
395/// Normalize an OpenAI-compatible base URL. We append our own path
396/// (`/chat/completions`, `/models`), so a user who pastes a full endpoint URL
397/// from a provider's docs gets it stripped back to the base rather than a
398/// doubled path (`…/chat/completions/chat/completions` → 404).
399pub fn normalize_base_url(raw: &str) -> String {
400    let mut b = raw.trim().trim_end_matches('/');
401    for suffix in ["/chat/completions", "/responses", "/completions", "/models"] {
402        if let Some(stripped) = b.strip_suffix(suffix) {
403            b = stripped.trim_end_matches('/');
404            break;
405        }
406    }
407    b.to_string()
408}
409
410/// Parse a JSON value that may be a number or a numeric string into `f64`
411/// (OpenRouter reports prices as strings like `"0.0000001"`).
412fn to_f64(v: &serde_json::Value) -> Option<f64> {
413    v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok()))
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    #[test]
421    fn base_url_normalization_strips_pasted_endpoints() {
422        let base = "https://openrouter.ai/api/v1";
423        assert_eq!(normalize_base_url(base), base);
424        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/"), base);
425        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/chat/completions"), base);
426        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/responses"), base);
427        assert_eq!(normalize_base_url("  https://openrouter.ai/api/v1/models  "), base);
428    }
429
430    #[test]
431    fn plain_message_serializes_without_tool_fields() {
432        let v = serde_json::to_value(ChatMessage::user("hi")).unwrap();
433        assert_eq!(v, serde_json::json!({"role": "user", "content": "hi"}));
434    }
435
436    #[test]
437    fn assistant_tool_call_message_omits_empty_content() {
438        let call = ToolCall {
439            id: "call_1".into(),
440            kind: "function".into(),
441            function: FunctionCall {
442                name: "github.search_issues".into(),
443                arguments: r#"{"q":"bug"}"#.into(),
444            },
445        };
446        let v = serde_json::to_value(ChatMessage::assistant_tool_calls(vec![call])).unwrap();
447        assert_eq!(v["role"], "assistant");
448        assert!(v.get("content").is_none(), "empty content is skipped");
449        assert_eq!(v["tool_calls"][0]["id"], "call_1");
450        assert_eq!(v["tool_calls"][0]["type"], "function");
451        assert_eq!(v["tool_calls"][0]["function"]["name"], "github.search_issues");
452    }
453
454    #[test]
455    fn tool_result_message_carries_call_id() {
456        let v = serde_json::to_value(ChatMessage::tool_result("call_1", "42 issues")).unwrap();
457        assert_eq!(v, serde_json::json!({
458            "role": "tool",
459            "content": "42 issues",
460            "tool_call_id": "call_1",
461        }));
462    }
463
464    #[test]
465    fn tool_calls_parse_from_a_response_message() {
466        let message = serde_json::json!({
467            "tool_calls": [
468                {"id": "c1", "type": "function",
469                 "function": {"name": "fs.read", "arguments": "{\"path\":\"a\"}"}}
470            ]
471        });
472        let calls: Vec<ToolCall> =
473            serde_json::from_value(message["tool_calls"].clone()).unwrap();
474        assert_eq!(calls.len(), 1);
475        assert_eq!(calls[0].function.name, "fs.read");
476        assert_eq!(calls[0].id, "c1");
477    }
478}
479
480/// The content + reasoning deltas extracted from one SSE chunk.
481#[derive(Default)]
482struct SseDelta {
483    content: Option<String>,
484    reasoning: Option<String>,
485}
486
487/// Parse one SSE line into its content and reasoning deltas. Side-effects usage
488/// and finish_reason as they appear. Reasoning is read from the de-facto fields
489/// (`reasoning_content` — DeepSeek; `reasoning` — OpenRouter and others).
490fn parse_sse_line(
491    line: &str,
492    usage: &mut Usage,
493    finish_reason: &mut Option<String>,
494) -> Result<SseDelta> {
495    let Some(data) = line.strip_prefix("data:") else {
496        return Ok(SseDelta::default());
497    };
498    let data = data.trim();
499    if data.is_empty() || data == "[DONE]" {
500        return Ok(SseDelta::default());
501    }
502
503    let chunk: ChatChunk =
504        serde_json::from_str(data).map_err(|e| RinneError::Worker(format!("bad SSE json: {e}")))?;
505
506    if let Some(u) = chunk.usage {
507        usage.prompt_tokens = u.prompt_tokens;
508        usage.completion_tokens = u.completion_tokens;
509    }
510
511    let mut content = String::new();
512    let mut reasoning = String::new();
513    for choice in chunk.choices {
514        if let Some(fr) = choice.finish_reason {
515            *finish_reason = Some(fr);
516        }
517        if let Some(c) = choice.delta.content {
518            content.push_str(&c);
519        }
520        if let Some(r) = choice.delta.reasoning_content.or(choice.delta.reasoning) {
521            reasoning.push_str(&r);
522        }
523    }
524    Ok(SseDelta {
525        content: (!content.is_empty()).then_some(content),
526        reasoning: (!reasoning.is_empty()).then_some(reasoning),
527    })
528}
529
530#[derive(Deserialize)]
531struct ChatChunk {
532    #[serde(default)]
533    choices: Vec<ChunkChoice>,
534    #[serde(default)]
535    usage: Option<ApiUsage>,
536}
537
538#[derive(Deserialize)]
539struct ChunkChoice {
540    delta: Delta,
541    #[serde(default)]
542    finish_reason: Option<String>,
543}
544
545#[derive(Deserialize)]
546struct Delta {
547    #[serde(default)]
548    content: Option<String>,
549    /// DeepSeek-style reasoning stream.
550    #[serde(default)]
551    reasoning_content: Option<String>,
552    /// OpenRouter/others-style reasoning stream.
553    #[serde(default)]
554    reasoning: Option<String>,
555}
556
557#[derive(Deserialize)]
558struct ApiUsage {
559    #[serde(default)]
560    prompt_tokens: u64,
561    #[serde(default)]
562    completion_tokens: u64,
563}
564
565/// Marker trait tie-in kept minimal for Phase 2; the API worker adapter wraps
566/// this client and implements `Worker`.
567#[async_trait]
568pub trait ChatBackend: Send + Sync {
569    async fn complete(
570        &self,
571        req: &ChatRequest,
572        events: &EventSink,
573        cancel: &CancellationToken,
574    ) -> Result<ChatResponse>;
575}
576
577#[async_trait]
578impl ChatBackend for OpenAiClient {
579    async fn complete(
580        &self,
581        req: &ChatRequest,
582        events: &EventSink,
583        cancel: &CancellationToken,
584    ) -> Result<ChatResponse> {
585        self.chat_stream(req, events, cancel).await
586    }
587}