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, ToolSpec, Usage, WorkerEvent};
14use rinne_core::{Result, RinneError};
15
16#[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 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 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#[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 #[serde(default)]
81 pub arguments: String,
82}
83
84fn function_kind() -> String {
85 "function".into()
86}
87
88#[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#[derive(Debug, Clone)]
100pub struct ChatRequest {
101 pub model: String,
102 pub messages: Vec<ChatMessage>,
103 pub temperature: Option<f32>,
104 pub extra: Option<serde_json::Value>,
106}
107
108#[derive(Debug, Clone)]
110pub struct ChatResponse {
111 pub content: String,
112 pub usage: Usage,
113 pub finish_reason: Option<String>,
114}
115
116#[derive(Debug, Clone)]
119pub struct DiscoveredModel {
120 pub id: String,
121 pub prompt_price: Option<f64>,
123 pub context: Option<u64>,
125}
126
127pub 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 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 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 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 if !lower.is_empty()
211 && !lower.contains("text generation")
212 && !lower.contains("text-generation")
213 && !lower.contains("conversational")
214 && lower != "llm"
215 {
216 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 if !id.contains('/') {
251 id = format!("@cf/{id}");
252 } else if !id.starts_with('@') && !id.starts_with("cf/") {
253 }
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 return Ok(cloudflare_text_model_fallback());
280 }
281 Ok(all)
282}
283
284pub 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
321pub 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#[derive(Clone)]
350pub struct OpenAiClient {
351 http: reqwest::Client,
352 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 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 pub async fn list_models(&self) -> Result<Vec<DiscoveredModel>> {
380 let url = format!("{}/models", self.base_url);
381 let mut builder = self.http.get(&url).timeout(std::time::Duration::from_secs(30));
382 if let Some(key) = &self.api_key {
383 builder = builder.bearer_auth(key);
384 }
385 let resp = builder
386 .send()
387 .await
388 .map_err(|e| RinneError::Worker(format!("models request failed: {e}")))?;
389 if !resp.status().is_success() {
390 let status = resp.status();
391 let text = resp.text().await.unwrap_or_default();
392 return Err(RinneError::Worker(format!("GET /models HTTP {status}: {text}")));
393 }
394 let v: serde_json::Value = resp
395 .json()
396 .await
397 .map_err(|e| RinneError::Worker(format!("bad /models json: {e}")))?;
398
399 let items = v
402 .get("data")
403 .and_then(|d| d.as_array())
404 .or_else(|| v.as_array())
405 .cloned()
406 .unwrap_or_default();
407
408 let mut models: Vec<DiscoveredModel> = items
409 .iter()
410 .filter_map(|m| {
411 let id = m.get("id").and_then(|x| x.as_str())?.to_string();
412 let prompt_price = m
413 .get("pricing")
414 .and_then(|p| p.get("prompt"))
415 .and_then(to_f64);
416 let context = m
417 .get("context_length")
418 .or_else(|| m.get("context_window"))
419 .and_then(|c| c.as_u64());
420 Some(DiscoveredModel {
421 id,
422 prompt_price,
423 context,
424 })
425 })
426 .collect();
427
428 models.sort_by(|a, b| match (a.prompt_price, b.prompt_price) {
430 (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
431 (Some(_), None) => std::cmp::Ordering::Less,
432 (None, Some(_)) => std::cmp::Ordering::Greater,
433 (None, None) => a.id.cmp(&b.id),
434 });
435 Ok(models)
436 }
437
438 pub async fn chat_with_tools(&self, req: &ChatRequest, tools: &[ToolSpec]) -> Result<ChatTurn> {
442 let url = format!("{}/chat/completions", self.base_url);
443 let mut body = serde_json::json!({
444 "model": req.model,
445 "messages": req.messages,
446 "temperature": req.temperature,
447 "stream": false,
448 });
449 if !tools.is_empty() {
450 let defs: Vec<serde_json::Value> = tools
451 .iter()
452 .map(|t| {
453 serde_json::json!({
454 "type": "function",
455 "function": {
456 "name": t.id,
457 "description": t.description,
458 "parameters": t.schema,
459 }
460 })
461 })
462 .collect();
463 if let Some(obj) = body.as_object_mut() {
464 obj.insert("tools".into(), serde_json::Value::Array(defs));
465 obj.insert("tool_choice".into(), serde_json::json!("auto"));
466 }
467 }
468 if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
470 (&req.extra, body.as_object_mut())
471 {
472 for (k, v) in extra {
473 obj.insert(k.clone(), v.clone());
474 }
475 }
476
477 let mut builder = self
480 .http
481 .post(&url)
482 .timeout(std::time::Duration::from_secs(120))
483 .json(&body);
484 if let Some(key) = &self.api_key {
485 builder = builder.bearer_auth(key);
486 }
487 let resp = builder
488 .send()
489 .await
490 .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
491 if !resp.status().is_success() {
492 let status = resp.status();
493 let text = resp.text().await.unwrap_or_default();
494 return Err(RinneError::Worker(format!(
495 "chat completion HTTP {status}: {text}"
496 )));
497 }
498
499 let v: serde_json::Value = resp
500 .json()
501 .await
502 .map_err(|e| RinneError::Worker(format!("bad completion json: {e}")))?;
503 let message = &v["choices"][0]["message"];
504 let content = message["content"].as_str().unwrap_or("").to_string();
505 let tool_calls: Vec<ToolCall> = message
506 .get("tool_calls")
507 .filter(|t| !t.is_null())
508 .and_then(|t| serde_json::from_value(t.clone()).ok())
509 .unwrap_or_default();
510 let finish_reason = v["choices"][0]["finish_reason"].as_str().map(String::from);
511 let usage = Usage {
512 prompt_tokens: v["usage"]["prompt_tokens"].as_u64().unwrap_or(0),
513 completion_tokens: v["usage"]["completion_tokens"].as_u64().unwrap_or(0),
514 wall_ms: 0,
515 };
516 Ok(ChatTurn {
517 content,
518 tool_calls,
519 usage,
520 finish_reason,
521 })
522 }
523
524 pub async fn chat_stream(
527 &self,
528 req: &ChatRequest,
529 events: &EventSink,
530 cancel: &CancellationToken,
531 ) -> Result<ChatResponse> {
532 let url = format!("{}/chat/completions", self.base_url);
533 let mut body = serde_json::json!({
534 "model": req.model,
535 "messages": req.messages,
536 "temperature": req.temperature,
537 "stream": true,
538 "stream_options": { "include_usage": true },
539 });
540 if let (Some(serde_json::Value::Object(extra)), Some(obj)) =
542 (&req.extra, body.as_object_mut())
543 {
544 for (k, v) in extra {
545 obj.insert(k.clone(), v.clone());
546 }
547 }
548
549 let mut builder = self.http.post(&url).json(&body);
550 if let Some(key) = &self.api_key {
551 builder = builder.bearer_auth(key);
552 }
553
554 let resp = builder
555 .send()
556 .await
557 .map_err(|e| RinneError::Worker(format!("request failed: {e}")))?;
558
559 if !resp.status().is_success() {
560 let status = resp.status();
561 let text = resp.text().await.unwrap_or_default();
562 return Err(RinneError::Worker(format!(
563 "chat completion HTTP {status}: {text}"
564 )));
565 }
566
567 let mut content = String::new();
568 let mut usage = Usage::default();
569 let mut finish_reason = None;
570 let mut buf: Vec<u8> = Vec::new();
575
576 let mut stream = resp.bytes_stream();
577 loop {
578 tokio::select! {
579 _ = cancel.cancelled() => {
580 return Ok(ChatResponse { content, usage, finish_reason: Some("cancelled".into()) });
581 }
582 chunk = stream.next() => {
583 let Some(chunk) = chunk else { break };
584 let bytes = chunk.map_err(|e| RinneError::Worker(format!("stream error: {e}")))?;
585 buf.extend_from_slice(&bytes);
586 while let Some(nl) = buf.iter().position(|&b| b == b'\n') {
588 let line = String::from_utf8_lossy(&buf[..nl]).trim().to_string();
589 buf.drain(..=nl);
590 let parsed = parse_sse_line(&line, &mut usage, &mut finish_reason)?;
591 if let Some(reasoning) = parsed.reasoning {
592 if !reasoning.is_empty() {
593 emit(events, WorkerEvent::Thinking(reasoning));
594 }
595 }
596 if let Some(delta) = parsed.content {
597 if !delta.is_empty() {
598 emit(events, WorkerEvent::Token(delta.clone()));
599 content.push_str(&delta);
600 }
601 }
602 }
603 }
604 }
605 }
606
607 emit(events, WorkerEvent::Done);
608 Ok(ChatResponse {
609 content,
610 usage,
611 finish_reason,
612 })
613 }
614}
615
616pub fn normalize_base_url(raw: &str) -> String {
621 let mut b = raw.trim().trim_end_matches('/');
622 for suffix in ["/chat/completions", "/responses", "/completions", "/models"] {
623 if let Some(stripped) = b.strip_suffix(suffix) {
624 b = stripped.trim_end_matches('/');
625 break;
626 }
627 }
628 b.to_string()
629}
630
631fn to_f64(v: &serde_json::Value) -> Option<f64> {
634 v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok()))
635}
636
637#[cfg(test)]
638mod tests {
639 use super::*;
640
641 #[test]
642 fn base_url_normalization_strips_pasted_endpoints() {
643 let base = "https://openrouter.ai/api/v1";
644 assert_eq!(normalize_base_url(base), base);
645 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/"), base);
646 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/chat/completions"), base);
647 assert_eq!(normalize_base_url("https://openrouter.ai/api/v1/responses"), base);
648 assert_eq!(normalize_base_url(" https://openrouter.ai/api/v1/models "), base);
649 }
650
651 #[test]
652 fn plain_message_serializes_without_tool_fields() {
653 let v = serde_json::to_value(ChatMessage::user("hi")).unwrap();
654 assert_eq!(v, serde_json::json!({"role": "user", "content": "hi"}));
655 }
656
657 #[test]
658 fn assistant_tool_call_message_omits_empty_content() {
659 let call = ToolCall {
660 id: "call_1".into(),
661 kind: "function".into(),
662 function: FunctionCall {
663 name: "github.search_issues".into(),
664 arguments: r#"{"q":"bug"}"#.into(),
665 },
666 };
667 let v = serde_json::to_value(ChatMessage::assistant_tool_calls(vec![call])).unwrap();
668 assert_eq!(v["role"], "assistant");
669 assert!(v.get("content").is_none(), "empty content is skipped");
670 assert_eq!(v["tool_calls"][0]["id"], "call_1");
671 assert_eq!(v["tool_calls"][0]["type"], "function");
672 assert_eq!(v["tool_calls"][0]["function"]["name"], "github.search_issues");
673 }
674
675 #[test]
676 fn tool_result_message_carries_call_id() {
677 let v = serde_json::to_value(ChatMessage::tool_result("call_1", "42 issues")).unwrap();
678 assert_eq!(v, serde_json::json!({
679 "role": "tool",
680 "content": "42 issues",
681 "tool_call_id": "call_1",
682 }));
683 }
684
685 #[test]
686 fn tool_calls_parse_from_a_response_message() {
687 let message = serde_json::json!({
688 "tool_calls": [
689 {"id": "c1", "type": "function",
690 "function": {"name": "fs.read", "arguments": "{\"path\":\"a\"}"}}
691 ]
692 });
693 let calls: Vec<ToolCall> =
694 serde_json::from_value(message["tool_calls"].clone()).unwrap();
695 assert_eq!(calls.len(), 1);
696 assert_eq!(calls[0].function.name, "fs.read");
697 assert_eq!(calls[0].id, "c1");
698 }
699}
700
701#[derive(Default)]
703struct SseDelta {
704 content: Option<String>,
705 reasoning: Option<String>,
706}
707
708fn parse_sse_line(
712 line: &str,
713 usage: &mut Usage,
714 finish_reason: &mut Option<String>,
715) -> Result<SseDelta> {
716 let Some(data) = line.strip_prefix("data:") else {
717 return Ok(SseDelta::default());
718 };
719 let data = data.trim();
720 if data.is_empty() || data == "[DONE]" {
721 return Ok(SseDelta::default());
722 }
723
724 let chunk: ChatChunk =
725 serde_json::from_str(data).map_err(|e| RinneError::Worker(format!("bad SSE json: {e}")))?;
726
727 if let Some(u) = chunk.usage {
728 usage.prompt_tokens = u.prompt_tokens;
729 usage.completion_tokens = u.completion_tokens;
730 }
731
732 let mut content = String::new();
733 let mut reasoning = String::new();
734 for choice in chunk.choices {
735 if let Some(fr) = choice.finish_reason {
736 *finish_reason = Some(fr);
737 }
738 if let Some(c) = choice.delta.content {
739 content.push_str(&c);
740 }
741 if let Some(r) = choice.delta.reasoning_content.or(choice.delta.reasoning) {
742 reasoning.push_str(&r);
743 }
744 }
745 Ok(SseDelta {
746 content: (!content.is_empty()).then_some(content),
747 reasoning: (!reasoning.is_empty()).then_some(reasoning),
748 })
749}
750
751#[derive(Deserialize)]
752struct ChatChunk {
753 #[serde(default)]
754 choices: Vec<ChunkChoice>,
755 #[serde(default)]
756 usage: Option<ApiUsage>,
757}
758
759#[derive(Deserialize)]
760struct ChunkChoice {
761 delta: Delta,
762 #[serde(default)]
763 finish_reason: Option<String>,
764}
765
766#[derive(Deserialize)]
767struct Delta {
768 #[serde(default)]
769 content: Option<String>,
770 #[serde(default)]
772 reasoning_content: Option<String>,
773 #[serde(default)]
775 reasoning: Option<String>,
776}
777
778#[derive(Deserialize)]
779struct ApiUsage {
780 #[serde(default)]
781 prompt_tokens: u64,
782 #[serde(default)]
783 completion_tokens: u64,
784}
785
786#[async_trait]
789pub trait ChatBackend: Send + Sync {
790 async fn complete(
791 &self,
792 req: &ChatRequest,
793 events: &EventSink,
794 cancel: &CancellationToken,
795 ) -> Result<ChatResponse>;
796}
797
798#[async_trait]
799impl ChatBackend for OpenAiClient {
800 async fn complete(
801 &self,
802 req: &ChatRequest,
803 events: &EventSink,
804 cancel: &CancellationToken,
805 ) -> Result<ChatResponse> {
806 self.chat_stream(req, events, cancel).await
807 }
808}