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/// Cloudflare Workers AI rejects OpenAI-compatible `GET …/ai/v1/models` (HTTP 405).
128/// Use the native REST catalog instead:
129/// `GET /accounts/{account_id}/ai/models/search`.
130///
131/// Model ids are returned as Workers AI names (`@cf/meta/llama-3.1-8b-instruct`, …)
132/// so they work with the OpenAI-compatible chat base URL.
133pub async fn list_cloudflare_workers_ai_models(
134    account_id: &str,
135    api_token: &str,
136) -> Result<Vec<DiscoveredModel>> {
137    let account_id = account_id.trim();
138    if account_id.is_empty() {
139        return Err(RinneError::Worker(
140            "cloudflare catalog needs account_id (set conductor.account_id or use an accounts/…/ai/v1 base_url)"
141                .into(),
142        ));
143    }
144    let http = reqwest::Client::builder()
145        .connect_timeout(std::time::Duration::from_secs(15))
146        .build()
147        .unwrap_or_default();
148
149    let mut all: Vec<DiscoveredModel> = Vec::new();
150    let mut seen = std::collections::HashSet::new();
151    // Paginate; CF catalog is ~80–100 models.
152    for page in 1u32..=20 {
153        let url = format!(
154            "https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/models/search?per_page=100&page={page}"
155        );
156        let resp = http
157            .get(&url)
158            .bearer_auth(api_token)
159            .timeout(std::time::Duration::from_secs(30))
160            .send()
161            .await
162            .map_err(|e| RinneError::Worker(format!("cloudflare models/search failed: {e}")))?;
163        if !resp.status().is_success() {
164            let status = resp.status();
165            let text = resp.text().await.unwrap_or_default();
166            return Err(RinneError::Worker(format!(
167                "cloudflare models/search HTTP {status}: {text}"
168            )));
169        }
170        let v: serde_json::Value = resp
171            .json()
172            .await
173            .map_err(|e| RinneError::Worker(format!("cloudflare models/search json: {e}")))?;
174
175        if v.get("success").and_then(|s| s.as_bool()) == Some(false) {
176            let err = v
177                .get("errors")
178                .map(|e| e.to_string())
179                .unwrap_or_else(|| "success=false".into());
180            return Err(RinneError::Worker(format!(
181                "cloudflare models/search error: {err}"
182            )));
183        }
184
185        // Default shape: { "result": [ { "name": "@cf/…", "task": {…}, … } ] }
186        // Also accept openrouter marketplace shape: { "data": [ { "id": … } ] }
187        let items = v
188            .get("result")
189            .and_then(|r| r.as_array())
190            .or_else(|| v.get("data").and_then(|d| d.as_array()))
191            .cloned()
192            .unwrap_or_default();
193
194        if items.is_empty() {
195            break;
196        }
197
198        let mut page_count = 0usize;
199        for m in &items {
200            page_count += 1;
201            // Prefer chat / text-generation models for the ladder UI.
202            if let Some(task) = m.get("task") {
203                let task_name = task
204                    .get("name")
205                    .or_else(|| task.as_str().map(|_| task))
206                    .and_then(|t| t.as_str())
207                    .unwrap_or("");
208                let lower = task_name.to_lowercase();
209                // Skip pure embeddings / image / audio when task is known.
210                if !lower.is_empty()
211                    && !lower.contains("text generation")
212                    && !lower.contains("text-generation")
213                    && !lower.contains("conversational")
214                    && lower != "llm"
215                {
216                    // Keep models with no useful task filter applied when name looks like @cf text.
217                    let name_hint = m
218                        .get("name")
219                        .or_else(|| m.get("id"))
220                        .and_then(|x| x.as_str())
221                        .unwrap_or("");
222                    if !(name_hint.contains("instruct")
223                        || name_hint.contains("chat")
224                        || name_hint.contains("llama")
225                        || name_hint.contains("gpt")
226                        || name_hint.contains("kimi")
227                        || name_hint.contains("glm")
228                        || name_hint.contains("qwen")
229                        || name_hint.contains("mistral")
230                        || name_hint.contains("gemma")
231                        || name_hint.contains("deepseek")
232                        || name_hint.contains("nemotron")
233                        || name_hint.contains("granite")
234                        || name_hint.contains("coder"))
235                    {
236                        continue;
237                    }
238                }
239            }
240
241            let id = m
242                .get("name")
243                .or_else(|| m.get("id"))
244                .and_then(|x| x.as_str())
245                .map(str::trim)
246                .filter(|s| !s.is_empty())
247                .map(|s| s.to_string());
248            let Some(mut id) = id else { continue };
249            // Workers AI chat expects @cf/… ids; some rows use short names.
250            if !id.contains('/') {
251                id = format!("@cf/{id}");
252            } else if !id.starts_with('@') && !id.starts_with("cf/") {
253                // already org/model — leave; CF often returns full @cf/…
254            }
255
256            if !seen.insert(id.clone()) {
257                continue;
258            }
259            let context = m
260                .get("context_window")
261                .or_else(|| m.get("context_length"))
262                .or_else(|| m.pointer("/properties/context_window"))
263                .and_then(|c| c.as_u64());
264            all.push(DiscoveredModel {
265                id,
266                prompt_price: None,
267                context,
268            });
269        }
270
271        if page_count < 100 {
272            break;
273        }
274    }
275
276    all.sort_by(|a, b| a.id.cmp(&b.id));
277    if all.is_empty() {
278        // Never leave the UI empty — surface a curated text-generation shortlist.
279        return Ok(cloudflare_text_model_fallback());
280    }
281    Ok(all)
282}
283
284/// Curated Workers AI **text** model ids (OpenAI-compat chat). Used when the
285/// native models/search API is empty/unavailable so the Models tab still offers
286/// real `@cf/…` ids to add. Keep in sync with
287/// https://developers.cloudflare.com/workers-ai/models/
288pub fn cloudflare_text_model_fallback() -> Vec<DiscoveredModel> {
289    const IDS: &[&str] = &[
290        "@cf/zai-org/glm-5.2",
291        "@cf/zai-org/glm-4.7-flash",
292        "@cf/moonshotai/kimi-k2.7-code",
293        "@cf/moonshotai/kimi-k2.6",
294        "@cf/openai/gpt-oss-120b",
295        "@cf/openai/gpt-oss-20b",
296        "@cf/meta/llama-4-scout-17b-16e-instruct",
297        "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
298        "@cf/meta/llama-3.1-8b-instruct-fast",
299        "@cf/meta/llama-3.1-8b-instruct-fp8",
300        "@cf/meta/llama-3.2-3b-instruct",
301        "@cf/meta/llama-3.2-1b-instruct",
302        "@cf/google/gemma-4-26b-a4b-it",
303        "@cf/google/gemma-3-12b-it",
304        "@cf/qwen/qwen3-30b-a3b-fp8",
305        "@cf/qwen/qwen2.5-coder-32b-instruct",
306        "@cf/qwen/qwq-32b",
307        "@cf/mistralai/mistral-small-3.1-24b-instruct",
308        "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
309        "@cf/ibm/granite-4.0-h-micro",
310        "@cf/nvidia/nemotron-3-120b-a12b",
311    ];
312    IDS.iter()
313        .map(|id| DiscoveredModel {
314            id: (*id).to_string(),
315            prompt_price: None,
316            context: None,
317        })
318        .collect()
319}
320
321/// Extract Cloudflare account id from an OpenAI-compat base URL such as
322/// `https://api.cloudflare.com/client/v4/accounts/{id}/ai/v1`.
323pub fn cloudflare_account_id_from_base_url(base_url: &str) -> Option<String> {
324    let marker = "/accounts/";
325    let idx = base_url.find(marker)?;
326    let rest = &base_url[idx + marker.len()..];
327    let id = rest.split('/').next()?.trim();
328    if id.is_empty() {
329        None
330    } else {
331        Some(id.to_string())
332    }
333}
334
335#[cfg(test)]
336mod cf_catalog_tests {
337    use super::cloudflare_account_id_from_base_url;
338
339    #[test]
340    fn parses_account_id_from_openai_compat_base() {
341        let id = cloudflare_account_id_from_base_url(
342            "https://api.cloudflare.com/client/v4/accounts/34d54c2157d6c13f34c4d5a171484700/ai/v1",
343        );
344        assert_eq!(id.as_deref(), Some("34d54c2157d6c13f34c4d5a171484700"));
345    }
346}
347
348/// An OpenAI-compatible chat client over a configurable base URL.
349#[derive(Clone)]
350pub struct OpenAiClient {
351    http: reqwest::Client,
352    /// Base URL including the API version, e.g. `https://api.openai.com/v1`.
353    base_url: String,
354    api_key: Option<String>,
355}
356
357impl OpenAiClient {
358    pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {
359        // Bound connection setup and idle reads so a dead/stalled endpoint can
360        // never wedge a call forever (reqwest has no default timeout). A total
361        // request timeout would cut off legitimately long streamed generations,
362        // so streaming relies on `read_timeout` (idle-between-bytes cap) and the
363        // non-streaming calls add their own per-request total timeout.
364        let http = reqwest::Client::builder()
365            .connect_timeout(std::time::Duration::from_secs(15))
366            .read_timeout(std::time::Duration::from_secs(120))
367            .build()
368            .unwrap_or_default();
369        Self {
370            http,
371            base_url: normalize_base_url(&base_url.into()),
372            api_key,
373        }
374    }
375
376    /// Discover the models this endpoint+key can access via `GET /models`.
377    /// Sorted cheapest→most-expensive where pricing is reported (others last),
378    /// so the result doubles as a price-ordered tier ladder.
379    pub async fn list_models(&self) -> Result<Vec<DiscoveredModel>> {
380        let url = format!("{}/models", self.base_url);
381        let mut builder = self
382            .http
383            .get(&url)
384            .timeout(std::time::Duration::from_secs(30));
385        if let Some(key) = &self.api_key {
386            builder = builder.bearer_auth(key);
387        }
388        let resp = builder
389            .send()
390            .await
391            .map_err(|e| RinneError::Worker(format!("models request failed: {e}")))?;
392        if !resp.status().is_success() {
393            let status = resp.status();
394            let text = resp.text().await.unwrap_or_default();
395            return Err(RinneError::Worker(format!(
396                "GET /models HTTP {status}: {text}"
397            )));
398        }
399        let v: serde_json::Value = resp
400            .json()
401            .await
402            .map_err(|e| RinneError::Worker(format!("bad /models json: {e}")))?;
403
404        // OpenAI shape: { "data": [ { "id", ... } ] }. Some platforms return a
405        // bare array. Pricing/context fields are platform-specific (OpenRouter).
406        let items = v
407            .get("data")
408            .and_then(|d| d.as_array())
409            .or_else(|| v.as_array())
410            .cloned()
411            .unwrap_or_default();
412
413        let mut models: Vec<DiscoveredModel> = items
414            .iter()
415            .filter_map(|m| {
416                let id = m.get("id").and_then(|x| x.as_str())?.to_string();
417                let prompt_price = m
418                    .get("pricing")
419                    .and_then(|p| p.get("prompt"))
420                    .and_then(to_f64);
421                let context = m
422                    .get("context_length")
423                    .or_else(|| m.get("context_window"))
424                    .and_then(|c| c.as_u64());
425                Some(DiscoveredModel {
426                    id,
427                    prompt_price,
428                    context,
429                })
430            })
431            .collect();
432
433        // Cheapest first; models without pricing sink to the end.
434        models.sort_by(|a, b| match (a.prompt_price, b.prompt_price) {
435            (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
436            (Some(_), None) => std::cmp::Ordering::Less,
437            (None, Some(_)) => std::cmp::Ordering::Greater,
438            (None, None) => a.id.cmp(&b.id),
439        });
440        Ok(models)
441    }
442
443    /// Run one non-streaming chat completion offering `tools`, returning whole
444    /// tool calls (streaming tool-call deltas are fiddly; the host loop wants
445    /// them complete). When `tools` is empty this is a plain completion.
446    pub async fn chat_with_tools(&self, req: &ChatRequest, tools: &[ToolSpec]) -> Result<ChatTurn> {
447        let url = format!("{}/chat/completions", self.base_url);
448        let mut body = serde_json::json!({
449            "model": req.model,
450            "messages": req.messages,
451            "temperature": req.temperature,
452            "stream": false,
453        });
454        if !tools.is_empty() {
455            let defs: Vec<serde_json::Value> = tools
456                .iter()
457                .map(|t| {
458                    serde_json::json!({
459                        "type": "function",
460                        "function": {
461                            "name": t.id,
462                            "description": t.description,
463                            "parameters": t.schema,
464                        }
465                    })
466                })
467                .collect();
468            if let Some(obj) = body.as_object_mut() {
469                obj.insert("tools".into(), serde_json::Value::Array(defs));
470                obj.insert("tool_choice".into(), serde_json::json!("auto"));
471            }
472        }
473        // Merge provider-specific extra params, as the streaming path does.
474        if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
475            (&req.extra, body.as_object_mut())
476        {
477            for (k, v) in extra {
478                obj.insert(k.clone(), v.clone());
479            }
480        }
481
482        // Non-streaming completion → a total per-request timeout is safe (no long
483        // stream to cut off) and bounds a stalled host tool-loop turn.
484        let mut builder = self
485            .http
486            .post(&url)
487            .timeout(std::time::Duration::from_secs(120))
488            .json(&body);
489        if let Some(key) = &self.api_key {
490            builder = builder.bearer_auth(key);
491        }
492        let resp = builder
493            .send()
494            .await
495            .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
496        if !resp.status().is_success() {
497            let status = resp.status();
498            let text = resp.text().await.unwrap_or_default();
499            return Err(RinneError::Worker(format!(
500                "chat completion HTTP {status}: {text}"
501            )));
502        }
503
504        let v: serde_json::Value = resp
505            .json()
506            .await
507            .map_err(|e| RinneError::Worker(format!("bad completion json: {e}")))?;
508        let message = &v["choices"][0]["message"];
509        let content = message["content"].as_str().unwrap_or("").to_string();
510        let tool_calls: Vec<ToolCall> = message
511            .get("tool_calls")
512            .filter(|t| !t.is_null())
513            .and_then(|t| serde_json::from_value(t.clone()).ok())
514            .unwrap_or_default();
515        let finish_reason = v["choices"][0]["finish_reason"].as_str().map(String::from);
516        let usage = Usage {
517            prompt_tokens: v["usage"]["prompt_tokens"].as_u64().unwrap_or(0),
518            completion_tokens: v["usage"]["completion_tokens"].as_u64().unwrap_or(0),
519            wall_ms: 0,
520        };
521        Ok(ChatTurn {
522            content,
523            tool_calls,
524            usage,
525            finish_reason,
526        })
527    }
528
529    /// Stream a chat completion, emitting each content delta as a
530    /// [`WorkerEvent::Message`] and returning the accumulated response.
531    pub async fn chat_stream(
532        &self,
533        req: &ChatRequest,
534        events: &EventSink,
535        cancel: &CancellationToken,
536    ) -> Result<ChatResponse> {
537        let url = format!("{}/chat/completions", self.base_url);
538        let mut body = serde_json::json!({
539            "model": req.model,
540            "messages": req.messages,
541            "temperature": req.temperature,
542            "stream": true,
543            "stream_options": { "include_usage": true },
544        });
545        // Merge provider-specific extra params (e.g. chat_template_kwargs).
546        if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
547            (&req.extra, body.as_object_mut())
548        {
549            for (k, v) in extra {
550                obj.insert(k.clone(), v.clone());
551            }
552        }
553
554        let mut builder = self.http.post(&url).json(&body);
555        if let Some(key) = &self.api_key {
556            builder = builder.bearer_auth(key);
557        }
558
559        let resp = builder
560            .send()
561            .await
562            .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
563
564        if !resp.status().is_success() {
565            let status = resp.status();
566            let text = resp.text().await.unwrap_or_default();
567            return Err(RinneError::Worker(format!(
568                "chat completion HTTP {status}: {text}"
569            )));
570        }
571
572        let mut content = String::new();
573        let mut usage = Usage::default();
574        let mut finish_reason = None;
575        // Accumulate raw bytes and decode only complete lines: a multi-byte UTF-8
576        // codepoint can straddle two network chunks, so decoding each chunk in
577        // isolation would corrupt it (`�`). `\n` (0x0A) never appears inside a
578        // multi-byte sequence, so splitting on it is safe.
579        let mut buf: Vec<u8> = Vec::new();
580
581        let mut stream = resp.bytes_stream();
582        loop {
583            tokio::select! {
584                _ = cancel.cancelled() => {
585                    return Ok(ChatResponse { content, usage, finish_reason: Some("cancelled".into()) });
586                }
587                chunk = stream.next() => {
588                    let Some(chunk) = chunk else { break };
589                    let bytes = chunk.map_err(|e| RinneError::Worker(format!("stream error: {e}")))?;
590                    buf.extend_from_slice(&bytes);
591                    // SSE frames are separated by newlines; process complete lines.
592                    while let Some(nl) = buf.iter().position(|&b| b == b'\n') {
593                        let line = String::from_utf8_lossy(&buf[..nl]).trim().to_string();
594                        buf.drain(..=nl);
595                        let parsed = parse_sse_line(&line, &mut usage, &mut finish_reason)?;
596                        if let Some(reasoning) = parsed.reasoning {
597                            if !reasoning.is_empty() {
598                                emit(events, WorkerEvent::Thinking(reasoning));
599                            }
600                        }
601                        if let Some(delta) = parsed.content {
602                            if !delta.is_empty() {
603                                emit(events, WorkerEvent::Token(delta.clone()));
604                                content.push_str(&delta);
605                            }
606                        }
607                    }
608                }
609            }
610        }
611
612        emit(events, WorkerEvent::Done);
613        Ok(ChatResponse {
614            content,
615            usage,
616            finish_reason,
617        })
618    }
619}
620
621/// Normalize an OpenAI-compatible base URL. We append our own path
622/// (`/chat/completions`, `/models`), so a user who pastes a full endpoint URL
623/// from a provider's docs gets it stripped back to the base rather than a
624/// doubled path (`…/chat/completions/chat/completions` → 404).
625pub fn normalize_base_url(raw: &str) -> String {
626    let mut b = raw.trim().trim_end_matches('/');
627    for suffix in ["/chat/completions", "/responses", "/completions", "/models"] {
628        if let Some(stripped) = b.strip_suffix(suffix) {
629            b = stripped.trim_end_matches('/');
630            break;
631        }
632    }
633    b.to_string()
634}
635
636/// Parse a JSON value that may be a number or a numeric string into `f64`
637/// (OpenRouter reports prices as strings like `"0.0000001"`).
638fn to_f64(v: &serde_json::Value) -> Option<f64> {
639    v.as_f64()
640        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn base_url_normalization_strips_pasted_endpoints() {
649        let base = "https://openrouter.ai/api/v1";
650        assert_eq!(normalize_base_url(base), base);
651        assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/"), base);
652        assert_eq!(
653            normalize_base_url("https://openrouter.ai/api/v1/chat/completions"),
654            base
655        );
656        assert_eq!(
657            normalize_base_url("https://openrouter.ai/api/v1/responses"),
658            base
659        );
660        assert_eq!(
661            normalize_base_url("  https://openrouter.ai/api/v1/models  "),
662            base
663        );
664    }
665
666    #[test]
667    fn plain_message_serializes_without_tool_fields() {
668        let v = serde_json::to_value(ChatMessage::user("hi")).unwrap();
669        assert_eq!(v, serde_json::json!({"role": "user", "content": "hi"}));
670    }
671
672    #[test]
673    fn assistant_tool_call_message_omits_empty_content() {
674        let call = ToolCall {
675            id: "call_1".into(),
676            kind: "function".into(),
677            function: FunctionCall {
678                name: "github.search_issues".into(),
679                arguments: r#"{"q":"bug"}"#.into(),
680            },
681        };
682        let v = serde_json::to_value(ChatMessage::assistant_tool_calls(vec![call])).unwrap();
683        assert_eq!(v["role"], "assistant");
684        assert!(v.get("content").is_none(), "empty content is skipped");
685        assert_eq!(v["tool_calls"][0]["id"], "call_1");
686        assert_eq!(v["tool_calls"][0]["type"], "function");
687        assert_eq!(
688            v["tool_calls"][0]["function"]["name"],
689            "github.search_issues"
690        );
691    }
692
693    #[test]
694    fn tool_result_message_carries_call_id() {
695        let v = serde_json::to_value(ChatMessage::tool_result("call_1", "42 issues")).unwrap();
696        assert_eq!(
697            v,
698            serde_json::json!({
699                "role": "tool",
700                "content": "42 issues",
701                "tool_call_id": "call_1",
702            })
703        );
704    }
705
706    #[test]
707    fn tool_calls_parse_from_a_response_message() {
708        let message = serde_json::json!({
709            "tool_calls": [
710                {"id": "c1", "type": "function",
711                 "function": {"name": "fs.read", "arguments": "{\"path\":\"a\"}"}}
712            ]
713        });
714        let calls: Vec<ToolCall> = serde_json::from_value(message["tool_calls"].clone()).unwrap();
715        assert_eq!(calls.len(), 1);
716        assert_eq!(calls[0].function.name, "fs.read");
717        assert_eq!(calls[0].id, "c1");
718    }
719}
720
721/// The content + reasoning deltas extracted from one SSE chunk.
722#[derive(Default)]
723struct SseDelta {
724    content: Option<String>,
725    reasoning: Option<String>,
726}
727
728/// Parse one SSE line into its content and reasoning deltas. Side-effects usage
729/// and finish_reason as they appear. Reasoning is read from the de-facto fields
730/// (`reasoning_content` — DeepSeek; `reasoning` — OpenRouter and others).
731fn parse_sse_line(
732    line: &str,
733    usage: &mut Usage,
734    finish_reason: &mut Option<String>,
735) -> Result<SseDelta> {
736    let Some(data) = line.strip_prefix("data:") else {
737        return Ok(SseDelta::default());
738    };
739    let data = data.trim();
740    if data.is_empty() || data == "[DONE]" {
741        return Ok(SseDelta::default());
742    }
743
744    let chunk: ChatChunk =
745        serde_json::from_str(data).map_err(|e| RinneError::Worker(format!("bad SSE json: {e}")))?;
746
747    if let Some(u) = chunk.usage {
748        usage.prompt_tokens = u.prompt_tokens;
749        usage.completion_tokens = u.completion_tokens;
750    }
751
752    let mut content = String::new();
753    let mut reasoning = String::new();
754    for choice in chunk.choices {
755        if let Some(fr) = choice.finish_reason {
756            *finish_reason = Some(fr);
757        }
758        if let Some(c) = choice.delta.content {
759            content.push_str(&c);
760        }
761        if let Some(r) = choice.delta.reasoning_content.or(choice.delta.reasoning) {
762            reasoning.push_str(&r);
763        }
764    }
765    Ok(SseDelta {
766        content: (!content.is_empty()).then_some(content),
767        reasoning: (!reasoning.is_empty()).then_some(reasoning),
768    })
769}
770
771#[derive(Deserialize)]
772struct ChatChunk {
773    #[serde(default)]
774    choices: Vec<ChunkChoice>,
775    #[serde(default)]
776    usage: Option<ApiUsage>,
777}
778
779#[derive(Deserialize)]
780struct ChunkChoice {
781    delta: Delta,
782    #[serde(default)]
783    finish_reason: Option<String>,
784}
785
786#[derive(Deserialize)]
787struct Delta {
788    #[serde(default)]
789    content: Option<String>,
790    /// DeepSeek-style reasoning stream.
791    #[serde(default)]
792    reasoning_content: Option<String>,
793    /// OpenRouter/others-style reasoning stream.
794    #[serde(default)]
795    reasoning: Option<String>,
796}
797
798#[derive(Deserialize)]
799struct ApiUsage {
800    #[serde(default)]
801    prompt_tokens: u64,
802    #[serde(default)]
803    completion_tokens: u64,
804}
805
806/// Marker trait tie-in kept minimal for Phase 2; the API worker adapter wraps
807/// this client and implements `Worker`.
808#[async_trait]
809pub trait ChatBackend: Send + Sync {
810    async fn complete(
811        &self,
812        req: &ChatRequest,
813        events: &EventSink,
814        cancel: &CancellationToken,
815    ) -> Result<ChatResponse>;
816}
817
818#[async_trait]
819impl ChatBackend for OpenAiClient {
820    async fn complete(
821        &self,
822        req: &ChatRequest,
823        events: &EventSink,
824        cancel: &CancellationToken,
825    ) -> Result<ChatResponse> {
826        self.chat_stream(req, events, cancel).await
827    }
828}