1use eyre::{Result, WrapErr};
2use rig_core::OneOrMany;
3use rig_core::client::CompletionClient;
4use rig_core::completion::CompletionError;
5use rig_core::completion::message::ToolCall;
6use rig_core::completion::message::ToolChoice;
7use rig_core::completion::{AssistantContent, CompletionModel, Message};
8use rig_core::providers::{anthropic, gemini, openai, openrouter};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::time::{Duration, SystemTime, UNIX_EPOCH};
15use tokio::sync::Semaphore;
16use tracing::warn;
17
18const MAX_COMPLETION_ATTEMPTS: usize = 4;
19const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
20const BASE_BACKOFF_MS: u64 = 250;
21const MAX_BACKOFF_MS: u64 = 5_000;
22const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
23const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct Completion {
27 pub model: String,
28 pub prompt: Message,
29 pub preamble: Option<String>,
30 pub history: Vec<Message>,
31 pub tools: Vec<rig_core::completion::ToolDefinition>,
32 pub tool_choice: Option<ToolChoice>,
33 pub max_tokens: Option<u64>,
34 pub additional_params: Option<Value>,
35}
36
37impl Completion {
38 pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
39 self.preamble = Some(preamble.into());
40 self
41 }
42
43 pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
44 self.tools = tools;
45 self
46 }
47
48 pub fn history(mut self, history: Vec<Message>) -> Self {
49 self.history = history;
50 self
51 }
52
53 pub fn max_tokens(mut self, max_tokens: u64) -> Self {
54 self.max_tokens = Some(max_tokens);
55 self
56 }
57
58 pub fn additional_params(mut self, additional_params: Value) -> Self {
59 self.additional_params = Some(additional_params);
60 self
61 }
62}
63
64impl From<Completion> for rig_core::completion::CompletionRequest {
65 fn from(value: Completion) -> Self {
66 let chat_history = value
67 .history
68 .into_iter()
69 .chain(std::iter::once(value.prompt))
70 .collect::<Vec<_>>();
71 rig_core::completion::CompletionRequest {
72 model: None,
73 chat_history: OneOrMany::many(chat_history)
74 .expect("completion request must include at least one message"),
75 preamble: value.preamble,
76 documents: Vec::new(),
77 tools: value.tools,
78 temperature: None,
79 max_tokens: value.max_tokens,
80 additional_params: value.additional_params,
81 output_schema: None,
82 tool_choice: value.tool_choice,
83 }
84 }
85}
86
87#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
88pub enum FinishReason {
89 None,
90 Stop,
91 MaxTokens,
92 ToolUse,
93 Other(String),
94}
95
96#[derive(Debug, Clone, Deserialize, Serialize)]
97pub struct CompletionResponse {
98 pub choice: OneOrMany<AssistantContent>,
99 pub finish_reason: FinishReason,
100 pub usage: TokenUsage,
101 pub selected_model: Option<String>,
102}
103
104#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
105pub struct TokenUsage {
106 pub input_tokens: u64,
107 pub output_tokens: u64,
108 pub total_tokens: u64,
109}
110
111impl TokenUsage {
112 pub fn new(input_tokens: u64, output_tokens: u64) -> Self {
113 Self {
114 input_tokens,
115 output_tokens,
116 total_tokens: input_tokens.saturating_add(output_tokens),
117 }
118 }
119}
120
121#[derive(Debug, Clone, Default)]
122pub struct ConversationUsageWindow {
123 compact_threshold: Option<u64>,
124 usage: TokenUsage,
125}
126
127impl ConversationUsageWindow {
128 pub fn new(compact_threshold: Option<u64>) -> Self {
129 Self {
130 compact_threshold,
131 usage: TokenUsage::default(),
132 }
133 }
134
135 pub fn should_compact(&self) -> bool {
136 self.compact_threshold
137 .map(|threshold| self.usage.total_tokens >= threshold)
138 .unwrap_or(false)
139 }
140
141 pub fn usage(&self) -> TokenUsage {
142 self.usage
143 }
144
145 pub fn record(&mut self, usage: TokenUsage) {
146 self.usage = usage;
150 }
151
152 pub fn reset(&mut self) {
153 self.usage = TokenUsage::default();
154 }
155}
156
157impl CompletionResponse {
158 pub fn message(&self) -> Message {
159 Message::Assistant {
160 id: None,
161 content: self.choice.clone(),
162 }
163 }
164
165 pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
166 if self.finish_reason != FinishReason::ToolUse {
167 return None;
168 }
169 let calls = self
170 .choice
171 .iter()
172 .filter_map(|content| match content {
173 AssistantContent::ToolCall(call) => Some(call.clone()),
174 _ => None,
175 })
176 .collect::<Vec<_>>();
177 if calls.is_empty() { None } else { Some(calls) }
178 }
179
180 pub fn text(&self) -> String {
181 let raw = self
185 .choice
186 .iter()
187 .filter_map(|content| match content {
188 AssistantContent::Text(text) => Some(text.text().to_string()),
189 _ => None,
190 })
191 .collect::<Vec<_>>()
192 .join("\n");
193 strip_think_blocks(&raw)
194 }
195}
196
197fn strip_think_blocks(text: &str) -> String {
209 fn match_think_tag(s: &str, close: bool) -> Option<usize> {
213 let prefix = if close { "</think" } else { "<think" };
214 if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
215 return None;
216 }
217 let after = &s[prefix.len()..];
218 let ws = after.len() - after.trim_start().len();
219 after[ws..]
220 .starts_with('>')
221 .then_some(prefix.len() + ws + 1)
222 }
223
224 let mut out = String::with_capacity(text.len());
225 let mut depth: usize = 0;
226 let mut rest = text;
227 while !rest.is_empty() {
228 if rest.starts_with('<') {
229 if let Some(len) = match_think_tag(rest, false) {
230 depth += 1;
231 rest = &rest[len..];
232 continue;
233 }
234 if let Some(len) = match_think_tag(rest, true) {
235 depth = depth.saturating_sub(1);
236 rest = &rest[len..];
237 continue;
238 }
239 }
240 let ch = rest.chars().next().expect("rest is non-empty");
241 if depth == 0 {
242 out.push(ch);
243 }
244 rest = &rest[ch.len_utf8()..];
245 }
246 out.trim().to_string()
247}
248
249pub trait LLMClient: Send + Sync {
250 fn completion(
251 &self,
252 completion: Completion,
253 ) -> impl Future<Output = Result<CompletionResponse>> + Send;
254
255 fn into_arc(self) -> Arc<dyn LLMClientDyn>
256 where
257 Self: Sized + 'static,
258 {
259 Arc::new(self)
260 }
261}
262
263pub trait LLMClientDyn: Send + Sync {
264 fn completion(
265 &self,
266 completion: Completion,
267 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
268}
269
270impl<T: LLMClient> LLMClientDyn for T {
271 fn completion(
272 &self,
273 completion: Completion,
274 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
275 Box::pin(LLMClient::completion(self, completion))
276 }
277}
278
279impl LLMClient for Box<dyn LLMClientDyn> {
280 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
281 (**self).completion(completion).await
282 }
283}
284
285pub struct RetryingLLM<C> {
286 inner: C,
287}
288
289pub trait WithRetryExt: Sized {
290 fn with_retry(self) -> RetryingLLM<Self> {
291 RetryingLLM { inner: self }
292 }
293}
294
295impl<T: LLMClient> WithRetryExt for T {}
296
297impl<C: LLMClient> LLMClient for RetryingLLM<C> {
298 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
299 let mut attempt = 0usize;
300 loop {
301 attempt += 1;
302 match self.inner.completion(completion.clone()).await {
303 Ok(response) => {
304 if response.text().is_empty() && response.tool_calls().is_none() {
305 if attempt >= MAX_COMPLETION_ATTEMPTS {
306 eyre::bail!("model returned empty response after {attempt} attempts");
307 }
308 let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
309 warn!(
310 model = %completion.model,
311 attempt,
312 max_attempts = MAX_COMPLETION_ATTEMPTS,
313 backoff_ms = backoff.as_millis(),
314 "retrying after empty model response"
315 );
316 tokio::time::sleep(backoff).await;
317 continue;
318 }
319 return Ok(response);
320 }
321 Err(err) => {
322 let policy = retry_policy(&err);
323 if !policy.retry || attempt >= policy.max_attempts {
324 return Err(err);
325 }
326 let backoff =
327 jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
328 warn!(
329 model = %completion.model,
330 attempt,
331 max_attempts = policy.max_attempts,
332 backoff_ms = backoff.as_millis(),
333 error = %err,
334 "retrying model completion after error"
335 );
336 tokio::time::sleep(backoff).await;
337 }
338 }
339 }
340 }
341}
342
343pub struct AlloyClient {
347 slots: Vec<(Arc<dyn LLMClientDyn>, String)>,
348}
349
350impl AlloyClient {
351 pub fn new(slots: Vec<(Arc<dyn LLMClientDyn>, String)>) -> Result<Self> {
352 if slots.is_empty() {
353 eyre::bail!("AlloyClient requires at least one slot");
354 }
355 Ok(Self { slots })
356 }
357
358 fn pick_idx(&self) -> usize {
359 use rand::RngExt;
360 rand::rng().random_range(0..self.slots.len())
361 }
362}
363
364impl LLMClientDyn for AlloyClient {
365 fn completion(
366 &self,
367 mut completion: Completion,
368 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
369 let (client, model) = &self.slots[self.pick_idx()];
370 completion.model = model.clone();
371 let client = Arc::clone(client);
372 let model = model.clone();
373 Box::pin(async move {
374 let mut response = client.completion(completion).await?;
375 response.selected_model = Some(model);
376 Ok(response)
377 })
378 }
379}
380
381pub async fn throttled_completion(
386 semaphore: &Semaphore,
387 client: &Arc<dyn LLMClientDyn>,
388 completion: Completion,
389) -> Result<CompletionResponse> {
390 let _permit = semaphore.acquire().await.expect("llm semaphore closed");
391 client.completion(completion).await
392}
393
394struct RetryPolicy {
395 retry: bool,
396 max_attempts: usize,
397 base_backoff_ms: u64,
398 max_backoff_ms: u64,
399}
400
401fn retry_policy(err: &eyre::Report) -> RetryPolicy {
402 if is_rate_limit_error(err) {
403 return RetryPolicy {
404 retry: true,
405 max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
406 base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
407 max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
408 };
409 }
410
411 if is_non_retryable_client_error(err) {
412 return RetryPolicy {
413 retry: false,
414 max_attempts: 0,
415 base_backoff_ms: 0,
416 max_backoff_ms: 0,
417 };
418 }
419
420 RetryPolicy {
421 retry: true,
422 max_attempts: MAX_COMPLETION_ATTEMPTS,
423 base_backoff_ms: BASE_BACKOFF_MS,
424 max_backoff_ms: MAX_BACKOFF_MS,
425 }
426}
427
428const STATUS_REASONS: &[(u16, &str)] = &[
432 (400, "bad request"),
433 (401, "unauthorized"),
434 (402, "payment required"),
435 (403, "forbidden"),
436 (404, "not found"),
437 (429, "too many requests"),
438 (500, "internal server error"),
439 (502, "bad gateway"),
440 (503, "service unavailable"),
441 (504, "gateway timeout"),
442];
443
444const STATUS_KEY_WINDOW: usize = 24;
448
449pub(crate) fn mentions_http_status(msg: &str, status: u16) -> bool {
460 let lower = msg.to_ascii_lowercase();
461 let needle = status.to_string();
462 let reason = STATUS_REASONS
463 .iter()
464 .find(|(code, _)| *code == status)
465 .map(|(_, phrase)| *phrase);
466 let bytes = lower.as_bytes();
467 let mut from = 0;
468 while let Some(rel) = lower[from..].find(&needle) {
469 let start = from + rel;
470 let end = start + needle.len();
471 let prev_digit = start > 0 && bytes[start - 1].is_ascii_digit();
472 let next_digit = end < bytes.len() && bytes[end].is_ascii_digit();
473 if !prev_digit && !next_digit && status_in_context(&lower, start, end, reason) {
474 return true;
475 }
476 from = start + 1;
477 }
478 false
479}
480
481fn status_in_context(lower: &str, start: usize, end: usize, reason: Option<&str>) -> bool {
487 if let Some(reason) = reason {
488 if lower[end..].trim_start().starts_with(reason) {
489 return true;
490 }
491 }
492 let mut window_start = start.saturating_sub(STATUS_KEY_WINDOW);
493 while !lower.is_char_boundary(window_start) {
494 window_start += 1;
495 }
496 key_word_present(lower, window_start, start, "status")
499 || key_word_present(lower, window_start, start, "code")
500 || key_word_present(lower, window_start, start, "statuscode")
501}
502
503fn key_word_present(lower: &str, lo: usize, hi: usize, key: &str) -> bool {
510 let bytes = lower.as_bytes();
511 let region = &lower[lo..hi];
512 let mut from = 0;
513 while let Some(rel) = region[from..].find(key) {
514 let abs = lo + from + rel;
515 let left_ok = abs == 0 || {
516 let b = bytes[abs - 1];
517 !b.is_ascii_alphanumeric() && b != b'_'
518 };
519 let after = abs + key.len();
520 let right_ok = after >= bytes.len() || !bytes[after].is_ascii_alphanumeric();
521 if left_ok && right_ok {
522 return true;
523 }
524 from += rel + 1;
525 }
526 false
527}
528
529const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
536 "authentication_error",
537 "invalid_api_key",
538 "permission_error",
539 "permission_denied",
540 "invalid_request_error",
541 "not_found_error",
542 "context_length_exceeded",
543 "insufficient_quota",
544];
545
546const RATE_LIMIT_ERROR_TYPES: &[&str] = &[
548 "rate_limit_error",
549 "rate_limit_exceeded",
550 "overloaded_error",
551];
552
553const PERMANENT_QUOTA_ERROR_TYPES: &[&str] = &["insufficient_quota"];
555
556fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
557 let msg = format!("{err:#}");
561 if [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
566 .iter()
567 .any(|&status| mentions_http_status(&msg, status))
568 {
569 return false;
570 }
571 if [400, 401, 402, 403, 404]
572 .iter()
573 .any(|&status| mentions_http_status(&msg, status))
574 {
575 return true;
576 }
577 let lower = msg.to_ascii_lowercase();
578 NON_RETRYABLE_ERROR_TYPES.iter().any(|t| lower.contains(t))
579}
580
581fn is_rate_limit_error(err: &eyre::Report) -> bool {
582 let msg = format!("{err:#}").to_ascii_lowercase();
586 if PERMANENT_QUOTA_ERROR_TYPES.iter().any(|t| msg.contains(t)) {
587 return false;
588 }
589 mentions_http_status(&msg, 429)
590 || msg.contains("rate limit")
591 || msg.contains("too many requests")
592 || msg.contains("tokens per minute")
593 || msg.contains("requests per minute")
594 || RATE_LIMIT_ERROR_TYPES.iter().any(|t| msg.contains(t))
595}
596
597fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
598 let exp = 2u64.saturating_pow((attempt - 1) as u32);
599 let base = (base_backoff_ms * exp).min(max_backoff_ms);
600 let jitter = jitter_factor();
601 let jittered = (base as f64 * jitter).round() as u64;
602 Duration::from_millis(jittered.max(1))
603}
604
605fn jitter_factor() -> f64 {
606 let nanos = SystemTime::now()
607 .duration_since(UNIX_EPOCH)
608 .map(|d| d.subsec_nanos())
609 .unwrap_or(0);
610 let scaled = (nanos % 1000) as f64 / 1000.0;
611 0.5 + scaled
612}
613
614#[derive(Debug, Deserialize)]
615struct OpenRouterErrorEnvelope {
616 error: OpenRouterErrorBody,
617}
618
619#[derive(Debug, Deserialize)]
620struct OpenRouterErrorBody {
621 message: String,
622 code: Option<u16>,
623}
624
625fn normalize_openrouter_completion_error(err: &CompletionError) -> eyre::Report {
626 match err {
627 CompletionError::ResponseError(msg) => normalize_openrouter_response_error(msg),
628 CompletionError::ProviderError(msg) => eyre::eyre!("ProviderError: {msg}"),
629 _ => eyre::eyre!("{err}"),
630 }
631}
632
633fn normalize_openrouter_response_error(msg: &str) -> eyre::Report {
634 if msg.contains("no message or tool call") || msg.contains("no choices") {
635 return eyre::eyre!("empty response from model (no message or tool call)");
636 }
637
638 if let Some(err) = parse_openrouter_error_envelope(msg) {
639 return match err.code {
640 Some(code) => eyre::eyre!(
641 "HttpError: Invalid status code {code} OpenRouter provider error: {}",
642 err.message
643 ),
644 None => eyre::eyre!("ProviderError: {}", err.message),
645 };
646 }
647
648 eyre::eyre!("ResponseError: {msg}")
649}
650
651fn parse_openrouter_error_envelope(msg: &str) -> Option<OpenRouterErrorBody> {
652 let body = msg.split_once("response body:")?.1.trim();
653 serde_json::from_str::<OpenRouterErrorEnvelope>(body)
654 .ok()
655 .map(|envelope| envelope.error)
656}
657
658fn is_local_base_url(base_url: Option<&str>) -> bool {
659 base_url
660 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
661 .unwrap_or(false)
662}
663
664fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
667 if is_local_base_url(base_url) {
668 Ok("local".to_string())
669 } else {
670 Err(eyre::eyre!("missing env var {key_env}"))
671 }
672}
673
674pub enum LLMProvider {
675 Anthropic {
676 base_url: Option<String>,
677 api_key_env: Option<String>,
678 },
679 Gemini {
680 base_url: Option<String>,
681 api_key_env: Option<String>,
682 },
683 OpenAi {
684 base_url: Option<String>,
685 api_key_env: Option<String>,
686 },
687 OpenRouter {
688 api_key_env: String,
689 },
690}
691
692impl LLMProvider {
693 pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
694 match self {
695 LLMProvider::Anthropic {
696 base_url,
697 api_key_env,
698 } => {
699 let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
700 let api_key = std::env::var(key_env)
701 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
702 let mut builder = anthropic::Client::builder().api_key(api_key);
703 if let Some(url) = base_url {
704 builder = builder.base_url(url);
705 }
706 Ok(Box::new(builder.build()?))
707 }
708 LLMProvider::Gemini {
709 base_url,
710 api_key_env,
711 } => {
712 let api_key = match api_key_env {
715 Some(key_env) => std::env::var(key_env)
716 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
717 None => std::env::var("GEMINI_API_KEY")
718 .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
719 .or_else(|_| {
720 missing_or_local(
721 "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
722 base_url.as_deref(),
723 )
724 })?,
725 };
726 let mut builder = gemini::Client::builder().api_key(api_key);
727 if let Some(url) = base_url {
728 builder = builder.base_url(url);
729 }
730 let client = builder
731 .build()
732 .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
733 Ok(Box::new(client))
734 }
735 LLMProvider::OpenAi {
736 base_url,
737 api_key_env,
738 } => {
739 let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
740 let api_key = std::env::var(key_env)
741 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
742 let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
743 if let Some(url) = base_url {
744 builder = builder.base_url(url);
745 }
746 Ok(Box::new(builder.build()?))
747 }
748 LLMProvider::OpenRouter { api_key_env } => {
749 let api_key = std::env::var(api_key_env)
750 .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
751 let client = openrouter::Client::builder()
752 .api_key(&api_key)
753 .http_headers(openrouter_headers()?)
754 .build()?;
755 Ok(Box::new(client))
756 }
757 }
758 }
759}
760
761pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
762 let mut headers = reqwest::header::HeaderMap::new();
763 headers.insert(
764 "HTTP-Referer",
765 "https://github.com/arsenyinfo/nitpicker".parse()?,
766 );
767 headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
768 headers.insert(
769 "X-OpenRouter-Categories",
770 "cli-agent,programming-app".parse()?,
771 );
772 Ok(headers)
773}
774
775impl LLMClient for openrouter::Client {
776 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
777 let model_name = completion.model.clone();
778 let mut request: rig_core::completion::CompletionRequest = completion.into();
779 request.model = Some(model_name.clone());
780 let model = self.completion_model(&model_name);
781 let response = model
782 .completion(request)
783 .await
784 .map_err(|e| normalize_openrouter_completion_error(&e))?;
785 let mut finish_reason = response
786 .raw_response
787 .choices
788 .first()
789 .and_then(|c| c.finish_reason.as_deref())
790 .map(|reason| match reason {
791 "stop" => FinishReason::Stop,
792 "length" => FinishReason::MaxTokens,
793 "tool_calls" => FinishReason::ToolUse,
794 other => FinishReason::Other(other.to_string()),
795 })
796 .unwrap_or(FinishReason::None);
797 if response
798 .choice
799 .iter()
800 .any(|content| matches!(content, AssistantContent::ToolCall(_)))
801 {
802 finish_reason = FinishReason::ToolUse;
803 }
804 let usage = response
805 .raw_response
806 .usage
807 .map(|u| TokenUsage::new(u.prompt_tokens as u64, u.completion_tokens as u64))
808 .unwrap_or_default();
809 Ok(CompletionResponse {
810 choice: response.choice,
811 finish_reason,
812 usage,
813 selected_model: Some(model_name),
814 })
815 }
816}
817
818#[cfg(feature = "antigravity")]
820pub fn create_gemini_client_with_proxy(
821 proxy_url: &str,
822) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
823 let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
826 let client = gemini::Client::builder()
827 .api_key(api_key)
828 .base_url(proxy_url)
829 .build()?;
830 Ok(client.with_retry().into_arc())
831}
832
833impl LLMClient for anthropic::Client {
834 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
835 let model_name = completion.model.clone();
836 let mut request: rig_core::completion::CompletionRequest = completion.into();
837 request.model = Some(model_name.clone());
838 let model = self.completion_model(model_name.clone());
839 let response = model
840 .completion(request)
841 .await
842 .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
843 let mut finish_reason = response
844 .raw_response
845 .stop_reason
846 .clone()
847 .map(|reason| match reason.as_str() {
848 "end_turn" => FinishReason::Stop,
849 "max_tokens" => FinishReason::MaxTokens,
850 "tool_use" => FinishReason::ToolUse,
851 other => FinishReason::Other(other.to_string()),
852 })
853 .unwrap_or(FinishReason::None);
854 if response
855 .choice
856 .iter()
857 .any(|content| matches!(content, AssistantContent::ToolCall(_)))
858 {
859 finish_reason = FinishReason::ToolUse;
860 }
861 Ok(CompletionResponse {
862 choice: response.choice,
863 finish_reason,
864 usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
865 selected_model: Some(model_name),
866 })
867 }
868}
869
870impl LLMClient for gemini::Client {
871 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
872 let model_name = completion.model.clone();
873 let params = build_gemini_additional_params(&completion)?;
874 let mut request: rig_core::completion::CompletionRequest = completion.into();
875 request.model = Some(model_name.clone());
876 request.additional_params = Some(params);
877 let model = self.completion_model(model_name.clone());
878 let response = model
879 .completion(request)
880 .await
881 .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
882 let mut finish_reason = response
883 .raw_response
884 .candidates
885 .first()
886 .and_then(|candidate| candidate.finish_reason.clone())
887 .map(map_gemini_finish_reason)
888 .unwrap_or(FinishReason::None);
889 if response
890 .choice
891 .iter()
892 .any(|content| matches!(content, AssistantContent::ToolCall(_)))
893 {
894 finish_reason = FinishReason::ToolUse;
895 }
896 Ok(CompletionResponse {
897 choice: response.choice,
898 finish_reason,
899 usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
900 selected_model: Some(model_name),
901 })
902 }
903}
904
905fn model_needs_max_completion_tokens(model: &str) -> bool {
906 model.starts_with("o1")
907 || model.starts_with("o3")
908 || model.starts_with("o4")
909 || model.starts_with("gpt-4o")
910 || model.starts_with("gpt-4.1")
911 || model.starts_with("gpt-4.5")
912 || model.starts_with("gpt-5")
913}
914
915pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
919 match (base, extra) {
920 (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
921 for (k, v) in extra_obj {
922 let merged = match base_obj.remove(&k) {
923 Some(existing) => merge_json(existing, v),
924 None => v,
925 };
926 base_obj.insert(k, merged);
927 }
928 Value::Object(base_obj)
929 }
930 (_, extra) => extra,
931 }
932}
933
934impl LLMClient for openai::CompletionsClient {
935 async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
936 if let Some(max) = completion.max_tokens {
940 if model_needs_max_completion_tokens(&completion.model) {
941 let extra = serde_json::json!({ "max_completion_tokens": max });
942 completion.additional_params = Some(match completion.additional_params.take() {
943 Some(existing) => merge_json(existing, extra),
944 None => extra,
945 });
946 completion.max_tokens = None;
947 }
948 }
949 let model_name = completion.model.clone();
950 let mut request: rig_core::completion::CompletionRequest = completion.into();
951 request.model = Some(model_name.clone());
952 let model = self.completion_model(model_name.clone());
953 let response = model
954 .completion(request)
955 .await
956 .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
957 let mut finish_reason = response
958 .raw_response
959 .choices
960 .first()
961 .map(|choice| match choice.finish_reason.as_str() {
962 "stop" => FinishReason::Stop,
963 "length" => FinishReason::MaxTokens,
964 "tool_calls" => FinishReason::ToolUse,
965 other => FinishReason::Other(other.to_string()),
966 })
967 .unwrap_or(FinishReason::None);
968 if response
969 .choice
970 .iter()
971 .any(|content| matches!(content, AssistantContent::ToolCall(_)))
972 {
973 finish_reason = FinishReason::ToolUse;
974 }
975 Ok(CompletionResponse {
976 choice: response.choice,
977 finish_reason,
978 usage: TokenUsage::new(response.usage.input_tokens, response.usage.output_tokens),
979 selected_model: Some(model_name),
980 })
981 }
982}
983
984#[derive(Debug, Serialize)]
985struct GeminiAdditionalParams {
986 generation_config: Option<GenerationConfig>,
987}
988
989impl GeminiAdditionalParams {
990 fn from_completion(completion: &Completion) -> Self {
991 let config = GenerationConfig {
992 max_output_tokens: completion.max_tokens.map(|value| value as i32),
993 };
994 Self {
995 generation_config: Some(config),
996 }
997 }
998}
999
1000fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
1005 let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
1006 Ok(match &completion.additional_params {
1007 Some(existing) => merge_json(existing.clone(), computed),
1008 None => computed,
1009 })
1010}
1011
1012#[derive(Debug, Serialize, Default)]
1013struct GenerationConfig {
1014 #[serde(skip_serializing_if = "Option::is_none")]
1015 max_output_tokens: Option<i32>,
1016}
1017
1018fn map_gemini_finish_reason(
1019 reason: gemini::completion::gemini_api_types::FinishReason,
1020) -> FinishReason {
1021 use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1022 match reason {
1023 GeminiFinishReason::Stop => FinishReason::Stop,
1024 GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1025 GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1026 other => FinishReason::Other(format!("{other:?}")),
1027 }
1028}
1029
1030#[cfg(test)]
1031mod tests {
1032 use super::*;
1033 use serde_json::json;
1034
1035 fn wrapped_provider_error(body: &str) -> eyre::Report {
1040 let inner = eyre::eyre!("ProviderError: {body}");
1041 Err::<(), _>(inner)
1042 .wrap_err("Anthropic completion failed for model 'claude'")
1043 .unwrap_err()
1044 }
1045
1046 fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
1047 Completion {
1048 model: "gemini-3-pro".to_string(),
1049 prompt: Message::user("hi".to_string()),
1050 preamble: None,
1051 history: Vec::new(),
1052 tools: Vec::new(),
1053 tool_choice: None,
1054 max_tokens,
1055 additional_params,
1056 }
1057 }
1058
1059 #[test]
1060 fn merge_json_is_deep_and_extra_wins() {
1061 let merged = merge_json(
1063 json!({"generation_config": {"temperature": 0.2}, "a": 1}),
1064 json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
1065 );
1066 assert_eq!(
1067 merged,
1068 json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
1069 );
1070 }
1071
1072 #[test]
1073 fn gemini_params_preserve_caller_config() {
1074 let params = build_gemini_additional_params(&gemini_completion(
1076 Some(50),
1077 Some(json!({
1078 "generation_config": {"temperature": 0.2},
1079 "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1080 })),
1081 ))
1082 .unwrap();
1083 assert_eq!(
1084 params,
1085 json!({
1086 "generation_config": {"temperature": 0.2, "max_output_tokens": 50},
1087 "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1088 })
1089 );
1090 }
1091
1092 #[test]
1093 fn gemini_params_none_yields_generation_config_only() {
1094 let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
1095 assert_eq!(params, json!({"generation_config": {"max_output_tokens": 50}}));
1096 }
1097
1098 #[test]
1099 fn strips_full_think_block() {
1100 let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
1101 assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
1102 }
1103
1104 #[test]
1105 fn strips_stray_empty_think_tags() {
1106 let raw = "<think></think>\n## Findings\n- looks fine";
1108 assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
1109 }
1110
1111 #[test]
1112 fn strips_unbalanced_and_multiline_think() {
1113 let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
1114 assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
1115 }
1116
1117 #[test]
1118 fn leaves_non_think_text_untouched() {
1119 let raw = "no reasoning tags here, just review text";
1120 assert_eq!(strip_think_blocks(raw), raw);
1121 }
1122
1123 #[test]
1124 fn strips_unterminated_think_to_eof() {
1125 let raw = "answer first\n<think>reasoning that never closes\nstep 2";
1127 assert_eq!(strip_think_blocks(raw), "answer first");
1128 }
1129
1130 #[test]
1131 fn all_reasoning_collapses_to_empty() {
1132 let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
1135 assert_eq!(strip_think_blocks(&joined), "");
1136 }
1137
1138 #[test]
1139 fn strips_nested_think_blocks() {
1140 let raw = "<think>outer <think>inner</think> still hidden</think>answer";
1143 assert_eq!(strip_think_blocks(raw), "answer");
1144 }
1145
1146 #[test]
1147 fn strips_whitespace_padded_think_tags() {
1148 let raw = "<think >hidden</think >visible";
1150 assert_eq!(strip_think_blocks(raw), "visible");
1151 }
1152
1153 #[test]
1154 fn leaves_thinking_word_untouched() {
1155 let raw = "see <thinking>kept</thinking> here";
1157 assert_eq!(
1158 strip_think_blocks(raw),
1159 "see <thinking>kept</thinking> here"
1160 );
1161 }
1162
1163 #[test]
1164 fn non_retryable_detects_status_in_wrapped_source() {
1165 let err = wrapped_provider_error(r#"{"statusCode": 401, "message": "Unauthorized"}"#);
1166 assert!(!err.to_string().contains("401"));
1168 assert!(is_non_retryable_client_error(&err));
1169 }
1170
1171 #[test]
1172 fn non_retryable_false_for_server_error() {
1173 let err = wrapped_provider_error(r#"{"statusCode": 500, "message": "boom"}"#);
1174 assert!(!is_non_retryable_client_error(&err));
1175 }
1176
1177 #[test]
1178 fn rate_limit_detects_429_in_wrapped_source() {
1179 let err = wrapped_provider_error(r#"{"statusCode": 429, "message": "Too Many Requests"}"#);
1180 assert!(is_rate_limit_error(&err));
1181 }
1182
1183 #[test]
1184 fn classifiers_detect_compact_json_status() {
1185 let unauthorized = wrapped_provider_error(r#"{"statusCode":401,"message":"nope"}"#);
1188 assert!(is_non_retryable_client_error(&unauthorized));
1189 let throttled = wrapped_provider_error(r#"{"statusCode":429,"message":"slow down"}"#);
1190 assert!(is_rate_limit_error(&throttled));
1191 }
1192
1193 #[test]
1194 fn mentions_http_status_requires_standalone_number() {
1195 assert!(mentions_http_status(r#"{"code":401}"#, 401)); assert!(mentions_http_status("got 401 unauthorized", 401)); assert!(!mentions_http_status("request id 4017 failed", 401)); assert!(!mentions_http_status("token count 1401", 401)); }
1200
1201 #[test]
1202 fn mentions_http_status_requires_status_context() {
1203 assert!(!mentions_http_status("max 400 tokens allowed", 400));
1206 assert!(!mentions_http_status("trace 404 emitted", 404));
1207 assert!(!mentions_http_status("req_402abc failed", 402)); assert!(!mentions_http_status("retry after 429 seconds", 429)); assert!(mentions_http_status(
1211 r#"{"statusCode":429,"message":"slow"}"#,
1212 429
1213 ));
1214 assert!(mentions_http_status(
1215 "HttpError: Invalid status code 401",
1216 401
1217 ));
1218 assert!(mentions_http_status("429 Too Many Requests", 429)); }
1220
1221 #[test]
1222 fn key_must_be_a_whole_word_not_a_substring() {
1223 assert!(!mentions_http_status("decode error 404", 404)); assert!(!mentions_http_status("unicode error 400", 400)); assert!(!mentions_http_status("encode failure 403", 403)); assert!(!mentions_http_status("error_code 402 seen", 402)); assert!(!mentions_http_status("codec 404 negotiation failed", 404));
1231 assert!(!mentions_http_status("statuslike 401 marker", 401));
1232 assert!(!mentions_http_status("xxxxxxxxxxxxxxxxxunicode 404", 404));
1235 assert!(mentions_http_status(r#"{"status_code": 401}"#, 401));
1237 }
1238
1239 #[test]
1240 fn classifies_provider_error_types_without_numeric_status() {
1241 let anthropic_auth = wrapped_provider_error(
1244 r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
1245 );
1246 assert!(!anthropic_auth.to_string().contains("401"));
1247 assert!(is_non_retryable_client_error(&anthropic_auth));
1248 assert!(!is_rate_limit_error(&anthropic_auth));
1249
1250 let openai_key =
1251 wrapped_provider_error(r#"{"error":{"code":"invalid_api_key","message":"bad key"}}"#);
1252 assert!(is_non_retryable_client_error(&openai_key));
1253
1254 let bad_request = wrapped_provider_error(
1255 r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
1256 );
1257 assert!(is_non_retryable_client_error(&bad_request));
1258
1259 let ctx_len = wrapped_provider_error(r#"{"error":{"code":"context_length_exceeded"}}"#);
1260 assert!(is_non_retryable_client_error(&ctx_len));
1261
1262 let quota = wrapped_provider_error(
1264 r#"{"error":{"type":"insufficient_quota","message":"exceeded your current quota"}}"#,
1265 );
1266 assert!(is_non_retryable_client_error("a));
1267 assert!(!is_rate_limit_error("a));
1268
1269 let quota_with_429 = wrapped_provider_error(
1270 r#"{"statusCode":429,"error":{"type":"insufficient_quota","message":"Too Many Requests"}}"#,
1271 );
1272 assert!(is_non_retryable_client_error("a_with_429));
1273 assert!(!is_rate_limit_error("a_with_429));
1274 assert!(!retry_policy("a_with_429).retry);
1275
1276 let overloaded =
1278 wrapped_provider_error(r#"{"type":"error","error":{"type":"overloaded_error"}}"#);
1279 assert!(is_rate_limit_error(&overloaded));
1280 assert!(!is_non_retryable_client_error(&overloaded));
1281
1282 let throttled = wrapped_provider_error(r#"{"error":{"code":"rate_limit_exceeded"}}"#);
1283 assert!(is_rate_limit_error(&throttled));
1284 }
1285
1286 #[test]
1287 fn server_error_takes_precedence_over_nested_4xx() {
1288 let err = wrapped_provider_error(r#"{"statusCode":502,"error":{"code":403}}"#);
1291 assert!(!is_non_retryable_client_error(&err));
1292 let nested = wrapped_provider_error(r#"{"statusCode":501,"error":{"code":403}}"#);
1294 assert!(!is_non_retryable_client_error(&nested));
1295 let pure_4xx = wrapped_provider_error(r#"{"statusCode":403,"message":"forbidden"}"#);
1297 assert!(is_non_retryable_client_error(&pure_4xx));
1298 }
1299}