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
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 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 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 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 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 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 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 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 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 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
621pub 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
636fn 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#[derive(Default)]
723struct SseDelta {
724 content: Option<String>,
725 reasoning: Option<String>,
726}
727
728fn 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 #[serde(default)]
792 reasoning_content: Option<String>,
793 #[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#[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}