1use eyre::{Result, WrapErr};
2use rig_core::OneOrMany;
3use rig_core::client::CompletionClient;
4use rig_core::completion::CompletionError;
5use rig_core::completion::message::ReasoningContent;
6use rig_core::completion::message::ToolCall;
7use rig_core::completion::message::ToolChoice;
8use rig_core::completion::{AssistantContent, CompletionModel, Message};
9use rig_core::providers::{anthropic, gemini, openai, openrouter};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::future::Future;
13use std::pin::Pin;
14use std::sync::Arc;
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16use tokio::sync::Semaphore;
17use tracing::warn;
18
19const MAX_COMPLETION_ATTEMPTS: usize = 4;
20const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
21const BASE_BACKOFF_MS: u64 = 250;
22const MAX_BACKOFF_MS: u64 = 5_000;
23const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
24const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
25const ANTHROPIC_DEFAULT_MAX_TOKENS: u64 = 8_192;
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Completion {
29 pub model: String,
30 pub prompt: Message,
31 pub preamble: Option<String>,
32 pub history: Vec<Message>,
33 pub tools: Vec<rig_core::completion::ToolDefinition>,
34 pub tool_choice: Option<ToolChoice>,
35 pub max_tokens: Option<u64>,
36 pub additional_params: Option<Value>,
37}
38
39impl Completion {
40 pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
41 self.preamble = Some(preamble.into());
42 self
43 }
44
45 pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
46 self.tools = tools;
47 self
48 }
49
50 pub fn history(mut self, history: Vec<Message>) -> Self {
51 self.history = history;
52 self
53 }
54
55 pub fn max_tokens(mut self, max_tokens: u64) -> Self {
56 self.max_tokens = Some(max_tokens);
57 self
58 }
59
60 pub fn additional_params(mut self, additional_params: Value) -> Self {
61 self.additional_params = Some(additional_params);
62 self
63 }
64}
65
66impl From<Completion> for rig_core::completion::CompletionRequest {
67 fn from(value: Completion) -> Self {
68 let chat_history = value
69 .history
70 .into_iter()
71 .chain(std::iter::once(value.prompt))
72 .collect::<Vec<_>>();
73 rig_core::completion::CompletionRequest {
74 model: None,
75 chat_history: OneOrMany::many(chat_history)
76 .expect("completion request must include at least one message"),
77 preamble: value.preamble,
78 documents: Vec::new(),
79 tools: value.tools,
80 temperature: None,
81 max_tokens: value.max_tokens,
82 additional_params: value.additional_params,
83 output_schema: None,
84 tool_choice: value.tool_choice,
85 record_telemetry_content: false,
87 }
88 }
89}
90
91#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
92pub enum FinishReason {
93 None,
94 Stop,
95 MaxTokens,
96 ToolUse,
97 Other(String),
98}
99
100#[derive(Debug, Clone, Deserialize, Serialize)]
101pub struct CompletionResponse {
102 pub choice: OneOrMany<AssistantContent>,
103 pub finish_reason: FinishReason,
104 pub usage: TokenUsage,
105 pub selected_model: Option<String>,
106}
107
108#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
109pub struct TokenUsage {
110 pub input_tokens: u64,
112 pub output_tokens: u64,
113 pub total_tokens: u64,
115 #[serde(default)]
117 pub cached_input_tokens: u64,
118 #[serde(default)]
120 pub cache_creation_input_tokens: u64,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum CacheAccounting {
128 OutsidePrompt,
130 InsidePrompt,
132}
133
134impl TokenUsage {
135 pub fn from_provider(usage: &rig_core::completion::Usage, accounting: CacheAccounting) -> Self {
143 let input_tokens = match accounting {
144 CacheAccounting::OutsidePrompt => usage
145 .input_tokens
146 .saturating_add(usage.cached_input_tokens)
147 .saturating_add(usage.cache_creation_input_tokens),
148 CacheAccounting::InsidePrompt => usage.input_tokens,
149 };
150 Self {
151 input_tokens,
152 output_tokens: usage.output_tokens,
153 total_tokens: input_tokens.saturating_add(usage.output_tokens),
154 cached_input_tokens: usage.cached_input_tokens,
155 cache_creation_input_tokens: usage.cache_creation_input_tokens,
156 }
157 }
158}
159
160#[derive(Debug, Clone, Default)]
161pub struct ConversationUsageWindow {
162 compact_threshold: Option<u64>,
163 usage: TokenUsage,
164}
165
166impl ConversationUsageWindow {
167 pub fn new(compact_threshold: Option<u64>) -> Self {
168 Self {
169 compact_threshold,
170 usage: TokenUsage::default(),
171 }
172 }
173
174 pub fn should_compact(&self) -> bool {
175 self.compact_threshold
176 .map(|threshold| self.usage.total_tokens >= threshold)
177 .unwrap_or(false)
178 }
179
180 pub fn usage(&self) -> TokenUsage {
181 self.usage
182 }
183
184 pub fn record(&mut self, usage: TokenUsage) {
185 self.usage = usage;
189 }
190
191 pub fn reset(&mut self) {
192 self.usage = TokenUsage::default();
193 }
194}
195
196impl CompletionResponse {
197 pub fn message(&self) -> Message {
198 Message::Assistant {
199 id: None,
200 content: self.choice.clone(),
201 }
202 }
203
204 pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
205 if self.finish_reason != FinishReason::ToolUse {
206 return None;
207 }
208 let calls = self
209 .choice
210 .iter()
211 .filter_map(|content| match content {
212 AssistantContent::ToolCall(call) => Some(call.clone()),
213 _ => None,
214 })
215 .collect::<Vec<_>>();
216 if calls.is_empty() { None } else { Some(calls) }
217 }
218
219 pub fn text(&self) -> String {
220 let raw = self
224 .choice
225 .iter()
226 .filter_map(|content| match content {
227 AssistantContent::Text(text) => Some(text.text().to_string()),
228 _ => None,
229 })
230 .collect::<Vec<_>>()
231 .join("\n");
232 let (stripped, unclosed_body) = scan_think_blocks(&raw);
233 let Some(start) = unclosed_body else {
236 return stripped;
237 };
238 let recovered = self.recover_unterminated_think(&raw[start..]);
241 match (stripped.is_empty(), recovered.is_empty()) {
242 (_, true) => stripped,
243 (true, false) => recovered,
244 (false, false) => format!("{stripped}\n\n{recovered}"),
245 }
246 }
247
248 fn recover_unterminated_think(&self, body: &str) -> String {
254 let Some(reasoning) = self.reasoning_text() else {
255 return String::new();
256 };
257 let body = body.trim_start();
258 let Some(answer) = body.strip_prefix(reasoning.trim()) else {
259 return String::new();
260 };
261 let cuts_mid_word = reasoning
264 .trim()
265 .chars()
266 .next_back()
267 .is_some_and(char::is_alphanumeric)
268 && answer.starts_with(char::is_alphanumeric);
269 match cuts_mid_word {
270 true => String::new(),
271 false => answer.trim().to_string(),
272 }
273 }
274
275 fn reasoning_text(&self) -> Option<String> {
277 let text = self
278 .choice
279 .iter()
280 .filter_map(|content| match content {
281 AssistantContent::Reasoning(reasoning) => Some(&reasoning.content),
282 _ => None,
283 })
284 .flatten()
285 .filter_map(|block| match block {
286 ReasoningContent::Text { text, .. } => Some(text.as_str()),
287 _ => None,
290 })
291 .collect::<String>();
292 match text.trim().is_empty() {
293 true => None,
294 false => Some(text),
295 }
296 }
297}
298
299fn scan_think_blocks(text: &str) -> (String, Option<usize>) {
314 fn match_think_tag(s: &str, close: bool) -> Option<usize> {
318 let prefix = if close { "</think" } else { "<think" };
319 if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
320 return None;
321 }
322 let after = &s[prefix.len()..];
323 let ws = after.len() - after.trim_start().len();
324 after[ws..]
325 .starts_with('>')
326 .then_some(prefix.len() + ws + 1)
327 }
328
329 let mut out = String::with_capacity(text.len());
330 let mut depth: usize = 0;
331 let mut consumed = 0usize;
332 let mut open_body_start = None;
333 let mut rest = text;
334 while !rest.is_empty() {
335 if rest.starts_with('<') {
336 if let Some(len) = match_think_tag(rest, false) {
337 depth += 1;
338 consumed += len;
339 if depth == 1 {
340 open_body_start = Some(consumed);
341 }
342 rest = &rest[len..];
343 continue;
344 }
345 if let Some(len) = match_think_tag(rest, true) {
346 depth = depth.saturating_sub(1);
347 if depth == 0 {
348 open_body_start = None;
349 }
350 consumed += len;
351 rest = &rest[len..];
352 continue;
353 }
354 }
355 let ch = rest.chars().next().expect("rest is non-empty");
356 if depth == 0 {
357 out.push(ch);
358 }
359 consumed += ch.len_utf8();
360 rest = &rest[ch.len_utf8()..];
361 }
362 let unclosed_body = match depth > 0 {
363 true => open_body_start,
364 false => None,
365 };
366 (out.trim().to_string(), unclosed_body)
367}
368
369pub trait LLMClient: Send + Sync {
370 fn completion(
371 &self,
372 completion: Completion,
373 ) -> impl Future<Output = Result<CompletionResponse>> + Send;
374
375 fn into_arc(self) -> Arc<dyn LLMClientDyn>
376 where
377 Self: Sized + 'static,
378 {
379 Arc::new(self)
380 }
381}
382
383pub trait LLMClientDyn: Send + Sync {
384 fn completion(
385 &self,
386 completion: Completion,
387 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
388}
389
390impl<T: LLMClient> LLMClientDyn for T {
391 fn completion(
392 &self,
393 completion: Completion,
394 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
395 Box::pin(LLMClient::completion(self, completion))
396 }
397}
398
399impl LLMClient for Box<dyn LLMClientDyn> {
400 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
401 (**self).completion(completion).await
402 }
403}
404
405fn empty_response_diagnosis(response: &CompletionResponse) -> String {
408 let output_tokens = response.usage.output_tokens;
409 match &response.finish_reason {
410 FinishReason::MaxTokens => format!(
411 "hit the output limit after {output_tokens} tokens without emitting content — \
412 reasoning consumed the whole budget, so raise max_tokens or leave it unset to use \
413 the provider's own limit"
414 ),
415 other => format!("finish_reason {other:?}, {output_tokens} output tokens"),
416 }
417}
418
419pub struct RetryingLLM<C> {
420 inner: C,
421}
422
423pub trait WithRetryExt: Sized {
424 fn with_retry(self) -> RetryingLLM<Self> {
425 RetryingLLM { inner: self }
426 }
427}
428
429impl<T: LLMClient> WithRetryExt for T {}
430
431impl<C: LLMClient> LLMClient for RetryingLLM<C> {
432 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
433 let mut attempt = 0usize;
434 loop {
435 attempt += 1;
436 match self.inner.completion(completion.clone()).await {
437 Ok(response) => {
438 if response.text().is_empty() && response.tool_calls().is_none() {
439 let diagnosis = empty_response_diagnosis(&response);
440 if attempt >= MAX_COMPLETION_ATTEMPTS {
441 eyre::bail!(
442 "model returned empty response after {attempt} attempts: {diagnosis}"
443 );
444 }
445 let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
446 warn!(
447 model = %completion.model,
448 attempt,
449 max_attempts = MAX_COMPLETION_ATTEMPTS,
450 backoff_ms = backoff.as_millis(),
451 diagnosis,
452 "retrying after empty model response"
453 );
454 tokio::time::sleep(backoff).await;
455 continue;
456 }
457 return Ok(response);
458 }
459 Err(err) => {
460 let policy = retry_policy(&err);
461 if !policy.retry || attempt >= policy.max_attempts {
462 return Err(err);
463 }
464 let backoff =
465 jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
466 warn!(
467 model = %completion.model,
468 attempt,
469 max_attempts = policy.max_attempts,
470 backoff_ms = backoff.as_millis(),
471 error = %err,
472 "retrying model completion after error"
473 );
474 tokio::time::sleep(backoff).await;
475 }
476 }
477 }
478 }
479}
480
481pub struct AlloySlot {
486 pub client: Arc<dyn LLMClientDyn>,
487 pub model: String,
488 pub max_tokens: Option<u64>,
489}
490
491pub struct AlloyClient {
492 slots: Vec<AlloySlot>,
493}
494
495impl AlloyClient {
496 pub fn new(slots: Vec<AlloySlot>) -> Result<Self> {
497 if slots.is_empty() {
498 eyre::bail!("AlloyClient requires at least one slot");
499 }
500 Ok(Self { slots })
501 }
502
503 fn pick_idx(&self) -> usize {
504 use rand::RngExt;
505 rand::rng().random_range(0..self.slots.len())
506 }
507}
508
509impl LLMClientDyn for AlloyClient {
510 fn completion(
511 &self,
512 mut completion: Completion,
513 ) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
514 let slot = &self.slots[self.pick_idx()];
515 completion.model = slot.model.clone();
516 completion.max_tokens = slot.max_tokens;
518 let client = Arc::clone(&slot.client);
519 let model = slot.model.clone();
520 Box::pin(async move {
521 let mut response = client.completion(completion).await?;
522 response.selected_model = Some(model);
523 Ok(response)
524 })
525 }
526}
527
528pub async fn throttled_completion(
533 semaphore: &Semaphore,
534 client: &Arc<dyn LLMClientDyn>,
535 completion: Completion,
536) -> Result<CompletionResponse> {
537 let _permit = semaphore.acquire().await.expect("llm semaphore closed");
538 client.completion(completion).await
539}
540
541struct RetryPolicy {
542 retry: bool,
543 max_attempts: usize,
544 base_backoff_ms: u64,
545 max_backoff_ms: u64,
546}
547
548fn retry_policy(err: &eyre::Report) -> RetryPolicy {
549 if is_rate_limit_error(err) {
550 return RetryPolicy {
551 retry: true,
552 max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
553 base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
554 max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
555 };
556 }
557
558 if is_non_retryable_client_error(err) {
559 return RetryPolicy {
560 retry: false,
561 max_attempts: 0,
562 base_backoff_ms: 0,
563 max_backoff_ms: 0,
564 };
565 }
566
567 RetryPolicy {
568 retry: true,
569 max_attempts: MAX_COMPLETION_ATTEMPTS,
570 base_backoff_ms: BASE_BACKOFF_MS,
571 max_backoff_ms: MAX_BACKOFF_MS,
572 }
573}
574
575const STATUS_REASONS: &[(u16, &str)] = &[
579 (400, "bad request"),
580 (401, "unauthorized"),
581 (402, "payment required"),
582 (403, "forbidden"),
583 (404, "not found"),
584 (429, "too many requests"),
585 (500, "internal server error"),
586 (502, "bad gateway"),
587 (503, "service unavailable"),
588 (504, "gateway timeout"),
589];
590
591const STATUS_KEY_WINDOW: usize = 24;
595
596pub(crate) fn mentions_http_status(msg: &str, status: u16) -> bool {
607 let lower = msg.to_ascii_lowercase();
608 let needle = status.to_string();
609 let reason = STATUS_REASONS
610 .iter()
611 .find(|(code, _)| *code == status)
612 .map(|(_, phrase)| *phrase);
613 let bytes = lower.as_bytes();
614 let mut from = 0;
615 while let Some(rel) = lower[from..].find(&needle) {
616 let start = from + rel;
617 let end = start + needle.len();
618 let prev_digit = start > 0 && bytes[start - 1].is_ascii_digit();
619 let next_digit = end < bytes.len() && bytes[end].is_ascii_digit();
620 if !prev_digit && !next_digit && status_in_context(&lower, start, end, reason) {
621 return true;
622 }
623 from = start + 1;
624 }
625 false
626}
627
628fn status_in_context(lower: &str, start: usize, end: usize, reason: Option<&str>) -> bool {
634 if let Some(reason) = reason {
635 if lower[end..].trim_start().starts_with(reason) {
636 return true;
637 }
638 }
639 let mut window_start = start.saturating_sub(STATUS_KEY_WINDOW);
640 while !lower.is_char_boundary(window_start) {
641 window_start += 1;
642 }
643 key_word_present(lower, window_start, start, "status")
646 || key_word_present(lower, window_start, start, "code")
647 || key_word_present(lower, window_start, start, "statuscode")
648}
649
650fn key_word_present(lower: &str, lo: usize, hi: usize, key: &str) -> bool {
657 let bytes = lower.as_bytes();
658 let region = &lower[lo..hi];
659 let mut from = 0;
660 while let Some(rel) = region[from..].find(key) {
661 let abs = lo + from + rel;
662 let left_ok = abs == 0 || {
663 let b = bytes[abs - 1];
664 !b.is_ascii_alphanumeric() && b != b'_'
665 };
666 let after = abs + key.len();
667 let right_ok = after >= bytes.len() || !bytes[after].is_ascii_alphanumeric();
668 if left_ok && right_ok {
669 return true;
670 }
671 from += rel + 1;
672 }
673 false
674}
675
676const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
683 "authentication_error",
684 "invalid_api_key",
685 "permission_error",
686 "permission_denied",
687 "invalid_request_error",
688 "not_found_error",
689 "context_length_exceeded",
690 "insufficient_quota",
691];
692
693const RATE_LIMIT_ERROR_TYPES: &[&str] = &[
695 "rate_limit_error",
696 "rate_limit_exceeded",
697 "overloaded_error",
698];
699
700const PERMANENT_QUOTA_ERROR_TYPES: &[&str] = &["insufficient_quota"];
702
703fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
704 let msg = format!("{err:#}");
708 if [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
713 .iter()
714 .any(|&status| mentions_http_status(&msg, status))
715 {
716 return false;
717 }
718 if [400, 401, 402, 403, 404]
719 .iter()
720 .any(|&status| mentions_http_status(&msg, status))
721 {
722 return true;
723 }
724 let lower = msg.to_ascii_lowercase();
725 NON_RETRYABLE_ERROR_TYPES.iter().any(|t| lower.contains(t))
726}
727
728fn is_rate_limit_error(err: &eyre::Report) -> bool {
729 let msg = format!("{err:#}").to_ascii_lowercase();
733 if PERMANENT_QUOTA_ERROR_TYPES.iter().any(|t| msg.contains(t)) {
734 return false;
735 }
736 mentions_http_status(&msg, 429)
737 || msg.contains("rate limit")
738 || msg.contains("too many requests")
739 || msg.contains("tokens per minute")
740 || msg.contains("requests per minute")
741 || RATE_LIMIT_ERROR_TYPES.iter().any(|t| msg.contains(t))
742}
743
744fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
745 let exp = 2u64.saturating_pow((attempt - 1) as u32);
746 let base = (base_backoff_ms * exp).min(max_backoff_ms);
747 let jitter = jitter_factor();
748 let jittered = (base as f64 * jitter).round() as u64;
749 Duration::from_millis(jittered.max(1))
750}
751
752fn jitter_factor() -> f64 {
753 let nanos = SystemTime::now()
754 .duration_since(UNIX_EPOCH)
755 .map(|d| d.subsec_nanos())
756 .unwrap_or(0);
757 let scaled = (nanos % 1000) as f64 / 1000.0;
758 0.5 + scaled
759}
760
761#[derive(Debug, Deserialize)]
762struct OpenRouterErrorEnvelope {
763 error: OpenRouterErrorBody,
764}
765
766#[derive(Debug, Deserialize)]
767struct OpenRouterErrorBody {
768 message: String,
769 code: Option<u16>,
770}
771
772fn normalize_openrouter_completion_error(err: &CompletionError) -> eyre::Report {
773 match err {
774 CompletionError::ResponseError(msg) => normalize_openrouter_response_error(msg),
775 CompletionError::ProviderError(msg) => eyre::eyre!("ProviderError: {msg}"),
776 _ => eyre::eyre!("{err}"),
777 }
778}
779
780fn normalize_openrouter_response_error(msg: &str) -> eyre::Report {
781 if msg.contains("no message or tool call") || msg.contains("no choices") {
782 return eyre::eyre!("empty response from model (no message or tool call)");
783 }
784
785 if let Some(err) = parse_openrouter_error_envelope(msg) {
786 return match err.code {
787 Some(code) => eyre::eyre!(
788 "HttpError: Invalid status code {code} OpenRouter provider error: {}",
789 err.message
790 ),
791 None => eyre::eyre!("ProviderError: {}", err.message),
792 };
793 }
794
795 eyre::eyre!("ResponseError: {msg}")
796}
797
798fn parse_openrouter_error_envelope(msg: &str) -> Option<OpenRouterErrorBody> {
799 let body = msg.split_once("response body:")?.1.trim();
800 serde_json::from_str::<OpenRouterErrorEnvelope>(body)
801 .ok()
802 .map(|envelope| envelope.error)
803}
804
805fn is_local_base_url(base_url: Option<&str>) -> bool {
806 base_url
807 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
808 .unwrap_or(false)
809}
810
811fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
814 if is_local_base_url(base_url) {
815 Ok("local".to_string())
816 } else {
817 Err(eyre::eyre!("missing env var {key_env}"))
818 }
819}
820
821pub enum LLMProvider {
822 Anthropic {
823 base_url: Option<String>,
824 api_key_env: Option<String>,
825 },
826 Gemini {
827 base_url: Option<String>,
828 api_key_env: Option<String>,
829 },
830 OpenAi {
831 base_url: Option<String>,
832 api_key_env: Option<String>,
833 },
834 OpenRouter {
835 api_key_env: String,
836 },
837}
838
839impl LLMProvider {
840 pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
841 match self {
842 LLMProvider::Anthropic {
843 base_url,
844 api_key_env,
845 } => {
846 let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
847 let api_key = std::env::var(key_env)
848 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
849 let mut builder = anthropic::Client::builder().api_key(api_key);
850 if let Some(url) = base_url {
851 builder = builder.base_url(url);
852 }
853 Ok(Box::new(builder.build()?))
854 }
855 LLMProvider::Gemini {
856 base_url,
857 api_key_env,
858 } => {
859 let api_key = match api_key_env {
862 Some(key_env) => std::env::var(key_env)
863 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
864 None => std::env::var("GEMINI_API_KEY")
865 .or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
866 .or_else(|_| {
867 missing_or_local(
868 "GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
869 base_url.as_deref(),
870 )
871 })?,
872 };
873 let mut builder = gemini::Client::builder().api_key(api_key);
874 if let Some(url) = base_url {
875 builder = builder.base_url(url);
876 }
877 let client = builder
878 .build()
879 .map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
880 Ok(Box::new(client))
881 }
882 LLMProvider::OpenAi {
883 base_url,
884 api_key_env,
885 } => {
886 let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
887 let api_key = std::env::var(key_env)
888 .or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
889 let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
890 if let Some(url) = base_url {
891 builder = builder.base_url(url);
892 }
893 Ok(Box::new(builder.build()?))
894 }
895 LLMProvider::OpenRouter { api_key_env } => {
896 let api_key = std::env::var(api_key_env)
897 .map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
898 let client = openrouter::Client::builder()
899 .api_key(&api_key)
900 .http_headers(openrouter_headers()?)
901 .build()?;
902 Ok(Box::new(client))
903 }
904 }
905 }
906}
907
908pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
909 let mut headers = reqwest::header::HeaderMap::new();
910 headers.insert(
911 "HTTP-Referer",
912 "https://github.com/arsenyinfo/nitpicker".parse()?,
913 );
914 headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
915 headers.insert(
916 "X-OpenRouter-Categories",
917 "cli-agent,programming-app".parse()?,
918 );
919 Ok(headers)
920}
921
922impl LLMClient for openrouter::Client {
923 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
924 let model_name = completion.model.clone();
925 let mut request: rig_core::completion::CompletionRequest = completion.into();
926 request.model = Some(model_name.clone());
927 let model = self.completion_model(&model_name);
928 let response = model
929 .completion(request)
930 .await
931 .map_err(|e| normalize_openrouter_completion_error(&e))?;
932 let finish_reason = response
933 .raw_response
934 .choices
935 .first()
936 .and_then(|c| c.finish_reason.as_deref())
937 .map(|reason| match reason {
938 "stop" => FinishReason::Stop,
939 "length" => FinishReason::MaxTokens,
940 "tool_calls" => FinishReason::ToolUse,
941 other => FinishReason::Other(other.to_string()),
942 })
943 .unwrap_or(FinishReason::None);
944 let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
945 Ok(CompletionResponse {
946 choice: response.choice,
947 finish_reason,
948 usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
949 selected_model: Some(model_name),
950 })
951 }
952}
953
954#[cfg(feature = "antigravity")]
956pub fn create_gemini_client_with_proxy(
957 proxy_url: &str,
958) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
959 let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
962 let client = gemini::Client::builder()
963 .api_key(api_key)
964 .base_url(proxy_url)
965 .build()?;
966 Ok(client.with_retry().into_arc())
967}
968
969impl LLMClient for anthropic::Client {
970 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
971 let model_name = completion.model.clone();
972 let mut request: rig_core::completion::CompletionRequest = completion.into();
973 request.model = Some(model_name.clone());
974 request
978 .max_tokens
979 .get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
980 let model = self.completion_model(model_name.clone());
981 let response = model
982 .completion(request)
983 .await
984 .wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
985 let finish_reason = response
986 .raw_response
987 .stop_reason
988 .clone()
989 .map(|reason| match reason.as_str() {
990 "end_turn" => FinishReason::Stop,
991 "max_tokens" => FinishReason::MaxTokens,
992 "tool_use" => FinishReason::ToolUse,
993 other => FinishReason::Other(other.to_string()),
994 })
995 .unwrap_or(FinishReason::None);
996 let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
997 Ok(CompletionResponse {
998 choice: response.choice,
999 finish_reason,
1000 usage: TokenUsage::from_provider(&response.usage, CacheAccounting::OutsidePrompt),
1001 selected_model: Some(model_name),
1002 })
1003 }
1004}
1005
1006impl LLMClient for gemini::Client {
1007 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
1008 let model_name = completion.model.clone();
1009 let params = build_gemini_additional_params(&completion)?;
1010 let mut request: rig_core::completion::CompletionRequest = completion.into();
1011 request.model = Some(model_name.clone());
1012 request.additional_params = Some(params);
1013 let model = self.completion_model(model_name.clone());
1014 let response = model
1015 .completion(request)
1016 .await
1017 .wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
1018 let finish_reason = response
1019 .raw_response
1020 .candidates
1021 .first()
1022 .and_then(|candidate| candidate.finish_reason.clone())
1023 .map(map_gemini_finish_reason)
1024 .unwrap_or(FinishReason::None);
1025 let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1026 Ok(CompletionResponse {
1027 choice: response.choice,
1028 finish_reason,
1029 usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1030 selected_model: Some(model_name),
1031 })
1032 }
1033}
1034
1035fn model_needs_max_completion_tokens(model: &str) -> bool {
1036 model.starts_with("o1")
1037 || model.starts_with("o3")
1038 || model.starts_with("o4")
1039 || model.starts_with("gpt-4o")
1040 || model.starts_with("gpt-4.1")
1041 || model.starts_with("gpt-4.5")
1042 || model.starts_with("gpt-5")
1043}
1044
1045pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
1049 match (base, extra) {
1050 (Value::Object(mut base_obj), Value::Object(extra_obj)) => {
1051 for (k, v) in extra_obj {
1052 let merged = match base_obj.remove(&k) {
1053 Some(existing) => merge_json(existing, v),
1054 None => v,
1055 };
1056 base_obj.insert(k, merged);
1057 }
1058 Value::Object(base_obj)
1059 }
1060 (_, extra) => extra,
1061 }
1062}
1063
1064impl LLMClient for openai::CompletionsClient {
1065 async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
1066 if let Some(max) = completion.max_tokens {
1070 if model_needs_max_completion_tokens(&completion.model) {
1071 let extra = serde_json::json!({ "max_completion_tokens": max });
1072 completion.additional_params = Some(match completion.additional_params.take() {
1073 Some(existing) => merge_json(existing, extra),
1074 None => extra,
1075 });
1076 completion.max_tokens = None;
1077 }
1078 }
1079 let model_name = completion.model.clone();
1080 let mut request: rig_core::completion::CompletionRequest = completion.into();
1081 request.model = Some(model_name.clone());
1082 let model = self.completion_model(model_name.clone());
1083 let response = model
1084 .completion(request)
1085 .await
1086 .wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
1087 let finish_reason = response
1088 .raw_response
1089 .choices
1090 .first()
1091 .map(|choice| match choice.finish_reason.as_str() {
1092 "stop" => FinishReason::Stop,
1093 "length" => FinishReason::MaxTokens,
1094 "tool_calls" => FinishReason::ToolUse,
1095 other => FinishReason::Other(other.to_string()),
1096 })
1097 .unwrap_or(FinishReason::None);
1098 let finish_reason = resolve_finish_reason(&response.choice, finish_reason);
1099 Ok(CompletionResponse {
1100 choice: response.choice,
1101 finish_reason,
1102 usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
1103 selected_model: Some(model_name),
1104 })
1105 }
1106}
1107
1108#[derive(Debug, Serialize)]
1109struct GeminiAdditionalParams {
1110 generation_config: Option<GenerationConfig>,
1111}
1112
1113impl GeminiAdditionalParams {
1114 fn from_completion(completion: &Completion) -> Self {
1115 let config = GenerationConfig {
1116 max_output_tokens: completion
1118 .max_tokens
1119 .map(|value| i32::try_from(value).unwrap_or(i32::MAX)),
1120 };
1121 Self {
1122 generation_config: Some(config),
1123 }
1124 }
1125}
1126
1127fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
1132 let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
1133 Ok(match &completion.additional_params {
1134 Some(existing) => merge_json(existing.clone(), computed),
1135 None => computed,
1136 })
1137}
1138
1139#[derive(Debug, Serialize, Default)]
1140struct GenerationConfig {
1141 #[serde(skip_serializing_if = "Option::is_none")]
1142 max_output_tokens: Option<i32>,
1143}
1144
1145fn resolve_finish_reason(
1149 choice: &OneOrMany<AssistantContent>,
1150 wire_reason: FinishReason,
1151) -> FinishReason {
1152 match choice
1153 .iter()
1154 .any(|content| matches!(content, AssistantContent::ToolCall(_)))
1155 {
1156 true => FinishReason::ToolUse,
1157 false => wire_reason,
1158 }
1159}
1160
1161fn map_gemini_finish_reason(
1162 reason: gemini::completion::gemini_api_types::FinishReason,
1163) -> FinishReason {
1164 use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
1165 match reason {
1166 GeminiFinishReason::Stop => FinishReason::Stop,
1167 GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
1168 GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
1169 other => FinishReason::Other(format!("{other:?}")),
1170 }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175 use super::*;
1176 use rig_core::completion::Usage;
1177
1178 fn strip_think_blocks(text: &str) -> String {
1179 scan_think_blocks(text).0
1180 }
1181 use serde_json::json;
1182
1183 fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
1184 CompletionResponse {
1185 choice: OneOrMany::many(choice).expect("non-empty choice"),
1186 finish_reason: FinishReason::Stop,
1187 usage: TokenUsage::default(),
1188 selected_model: None,
1189 }
1190 }
1191
1192 fn reasoning_item(text: &str) -> AssistantContent {
1193 AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
1194 }
1195
1196 #[test]
1199 fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
1200 let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
1201 let response = response_with(vec![
1202 reasoning_item(reasoning),
1203 AssistantContent::text(format!(
1204 "<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
1205 )),
1206 ]);
1207 assert_eq!(
1208 response.text(),
1209 "### Verdict\n**Agreed: use `eyre` for applications.**"
1210 );
1211 }
1212
1213 #[test]
1216 fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
1217 let reasoning = "Weighing both sides.";
1218 let response = response_with(vec![
1219 reasoning_item(reasoning),
1220 AssistantContent::text(format!(
1221 "Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
1222 )),
1223 ]);
1224 assert_eq!(
1225 response.text(),
1226 "Here is my review.\n\n### Verdict\nShip it."
1227 );
1228 }
1229
1230 #[test]
1233 fn fragmented_reasoning_is_concatenated_without_separators() {
1234 let response = response_with(vec![
1235 reasoning_item("weighing the options"),
1236 reasoning_item(" carefully."),
1237 AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
1238 ]);
1239 assert_eq!(response.text(), "Verdict: ship it.");
1240 }
1241
1242 #[test]
1246 fn unterminated_think_without_structured_reasoning_stays_empty() {
1247 let response = response_with(vec![AssistantContent::text(
1248 "<think>\nweighing it up\n\nVerdict: ship it.",
1249 )]);
1250 assert!(response.text().is_empty());
1251 }
1252
1253 #[test]
1256 fn summary_reasoning_is_not_used_to_split_the_body() {
1257 let response = response_with(vec![
1258 AssistantContent::Reasoning(rig_core::completion::message::Reasoning::summaries(vec![
1259 "brief".to_string(),
1260 ])),
1261 AssistantContent::text("<think>private chain"),
1262 ]);
1263 assert!(response.text().is_empty());
1264 }
1265
1266 #[test]
1269 fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
1270 let response = response_with(vec![
1271 reasoning_item("Ver"),
1272 AssistantContent::text("<think>Verdict: ship it."),
1273 ]);
1274 assert!(response.text().is_empty());
1275 }
1276
1277 #[test]
1280 fn recovery_targets_the_block_that_stayed_open() {
1281 let response = response_with(vec![
1282 reasoning_item("secret"),
1283 AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
1284 ]);
1285 assert_eq!(response.text(), "FINAL");
1286 }
1287
1288 #[test]
1291 fn a_stray_closing_tag_does_not_misdirect_recovery() {
1292 let response = response_with(vec![
1293 reasoning_item("secret"),
1294 AssistantContent::text("</think><think>secret\n\nFINAL"),
1295 ]);
1296 assert_eq!(response.text(), "FINAL");
1297 }
1298
1299 #[test]
1302 fn a_reasoning_only_response_is_still_empty() {
1303 let reasoning = "still thinking about it";
1304 let response = response_with(vec![
1305 reasoning_item(reasoning),
1306 AssistantContent::text(format!("<think>\n{reasoning}")),
1307 ]);
1308 assert!(response.text().is_empty());
1309 let closed = response_with(vec![AssistantContent::text(
1310 "<think>done deliberating</think>",
1311 )]);
1312 assert!(closed.text().is_empty());
1313 }
1314
1315 #[test]
1317 fn closed_think_block_still_yields_only_the_answer() {
1318 let response = response_with(vec![AssistantContent::text(
1319 "<think>weighing it up</think>Verdict: ship it.",
1320 )]);
1321 assert_eq!(response.text(), "Verdict: ship it.");
1322 }
1323
1324 fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
1327 let mut usage = Usage::new();
1328 usage.input_tokens = input;
1329 usage.output_tokens = output;
1330 usage.cached_input_tokens = cached;
1331 usage.cache_creation_input_tokens = creation;
1332 usage.total_tokens = input + cached + creation + output;
1333 usage
1334 }
1335
1336 fn anthropic(usage: &Usage) -> TokenUsage {
1337 TokenUsage::from_provider(usage, CacheAccounting::OutsidePrompt)
1338 }
1339
1340 fn prompt_inclusive(usage: &Usage) -> TokenUsage {
1341 TokenUsage::from_provider(usage, CacheAccounting::InsidePrompt)
1342 }
1343
1344 #[test]
1349 fn provider_shapes_meter_a_cache_hit_identically() {
1350 let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
1351 let mut openai = Usage::new();
1352 openai.input_tokens = 3508;
1353 openai.output_tokens = 8;
1354 openai.cached_input_tokens = 3456;
1355 openai.total_tokens = 3516;
1356 let from_openai = prompt_inclusive(&openai);
1357
1358 assert_eq!(from_anthropic.input_tokens, 3508);
1359 assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
1360 assert_eq!(
1361 from_anthropic.cached_input_tokens,
1362 from_openai.cached_input_tokens
1363 );
1364 for usage in [from_anthropic, from_openai] {
1365 assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
1366 }
1367 }
1368
1369 #[test]
1375 fn gemini_cache_reads_are_never_added_to_its_prompt() {
1376 let mut usage = Usage::new();
1377 usage.input_tokens = 40;
1378 usage.output_tokens = 30;
1379 usage.reasoning_tokens = 10;
1380 usage.tool_use_prompt_tokens = 12;
1381 usage.cached_input_tokens = 8;
1382 usage.total_tokens = 100;
1383 let usage = prompt_inclusive(&usage);
1384 assert_eq!(usage.input_tokens, 40);
1385 assert_eq!(usage.cached_input_tokens, 8);
1386 }
1387
1388 #[test]
1391 fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
1392 let mut usage = Usage::new();
1393 usage.input_tokens = 500;
1394 usage.output_tokens = 10;
1395 usage.cached_input_tokens = 5;
1396 usage.total_tokens = 515;
1397 let usage = prompt_inclusive(&usage);
1398 assert_eq!(usage.input_tokens, 500);
1399 assert_eq!(usage.total_tokens, 510);
1400 }
1401
1402 #[test]
1404 fn missing_provider_total_still_meters_reported_input() {
1405 let mut usage = Usage::new();
1406 usage.input_tokens = 1200;
1407 usage.output_tokens = 40;
1408 let usage = prompt_inclusive(&usage);
1409 assert_eq!(usage.input_tokens, 1200);
1410 assert_eq!(usage.total_tokens, 1240);
1411 }
1412
1413 #[test]
1415 fn anthropic_cache_writes_count_toward_the_prompt() {
1416 let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
1417 assert_eq!(usage.cache_creation_input_tokens, 4100);
1418 assert_eq!(usage.input_tokens, 4190);
1419 assert_eq!(usage.total_tokens, 4200);
1420 }
1421
1422 #[test]
1426 fn contradictory_cache_metadata_is_not_papered_over() {
1427 let mut usage = Usage::new();
1428 usage.input_tokens = 10;
1429 usage.output_tokens = 5;
1430 usage.total_tokens = 15;
1431 usage.cached_input_tokens = 5_000;
1432 usage.cache_creation_input_tokens = 700;
1433 let usage = prompt_inclusive(&usage);
1434 assert_eq!(usage.input_tokens, 10);
1435 assert_eq!(usage.total_tokens, 15);
1436 assert_eq!(usage.cached_input_tokens, 5_000);
1437 assert_eq!(usage.cache_creation_input_tokens, 700);
1438 }
1439
1440 #[test]
1443 fn compaction_threshold_sees_the_cached_prompt() {
1444 let mut window = ConversationUsageWindow::new(Some(3_000));
1445 window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
1446 assert!(window.should_compact());
1447 }
1448
1449 #[test]
1452 fn usage_without_cache_fields_still_deserializes() {
1453 let usage: TokenUsage = serde_json::from_value(
1454 json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
1455 )
1456 .expect("legacy usage payload must decode");
1457 assert_eq!(usage.input_tokens, 10);
1458 assert_eq!(usage.cached_input_tokens, 0);
1459 }
1460
1461 fn wrapped_provider_error(body: &str) -> eyre::Report {
1466 let inner = eyre::eyre!("ProviderError: {body}");
1467 Err::<(), _>(inner)
1468 .wrap_err("Anthropic completion failed for model 'claude'")
1469 .unwrap_err()
1470 }
1471
1472 fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
1473 Completion {
1474 model: "gemini-3-pro".to_string(),
1475 prompt: Message::user("hi".to_string()),
1476 preamble: None,
1477 history: Vec::new(),
1478 tools: Vec::new(),
1479 tool_choice: None,
1480 max_tokens,
1481 additional_params,
1482 }
1483 }
1484
1485 #[test]
1486 fn merge_json_is_deep_and_extra_wins() {
1487 let merged = merge_json(
1489 json!({"generation_config": {"temperature": 0.2}, "a": 1}),
1490 json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
1491 );
1492 assert_eq!(
1493 merged,
1494 json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
1495 );
1496 }
1497
1498 #[test]
1499 fn gemini_params_preserve_caller_config() {
1500 let params = build_gemini_additional_params(&gemini_completion(
1502 Some(50),
1503 Some(json!({
1504 "generation_config": {"temperature": 0.2},
1505 "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1506 })),
1507 ))
1508 .unwrap();
1509 assert_eq!(
1510 params,
1511 json!({
1512 "generation_config": {"temperature": 0.2, "max_output_tokens": 50},
1513 "safetySettings": [{"category": "HARM", "threshold": "NONE"}]
1514 })
1515 );
1516 }
1517
1518 #[test]
1519 fn gemini_params_none_yields_generation_config_only() {
1520 let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
1521 assert_eq!(
1522 params,
1523 json!({"generation_config": {"max_output_tokens": 50}})
1524 );
1525 }
1526
1527 #[test]
1528 fn strips_full_think_block() {
1529 let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
1530 assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
1531 }
1532
1533 #[test]
1534 fn strips_stray_empty_think_tags() {
1535 let raw = "<think></think>\n## Findings\n- looks fine";
1537 assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
1538 }
1539
1540 #[test]
1541 fn strips_unbalanced_and_multiline_think() {
1542 let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
1543 assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
1544 }
1545
1546 #[test]
1547 fn leaves_non_think_text_untouched() {
1548 let raw = "no reasoning tags here, just review text";
1549 assert_eq!(strip_think_blocks(raw), raw);
1550 }
1551
1552 #[test]
1553 fn strips_unterminated_think_to_eof() {
1554 let raw = "answer first\n<think>reasoning that never closes\nstep 2";
1556 assert_eq!(strip_think_blocks(raw), "answer first");
1557 }
1558
1559 #[test]
1560 fn all_reasoning_collapses_to_empty() {
1561 let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
1564 assert_eq!(strip_think_blocks(&joined), "");
1565 }
1566
1567 #[test]
1568 fn strips_nested_think_blocks() {
1569 let raw = "<think>outer <think>inner</think> still hidden</think>answer";
1572 assert_eq!(strip_think_blocks(raw), "answer");
1573 }
1574
1575 #[test]
1576 fn strips_whitespace_padded_think_tags() {
1577 let raw = "<think >hidden</think >visible";
1579 assert_eq!(strip_think_blocks(raw), "visible");
1580 }
1581
1582 #[test]
1583 fn leaves_thinking_word_untouched() {
1584 let raw = "see <thinking>kept</thinking> here";
1586 assert_eq!(
1587 strip_think_blocks(raw),
1588 "see <thinking>kept</thinking> here"
1589 );
1590 }
1591
1592 #[test]
1593 fn non_retryable_detects_status_in_wrapped_source() {
1594 let err = wrapped_provider_error(r#"{"statusCode": 401, "message": "Unauthorized"}"#);
1595 assert!(!err.to_string().contains("401"));
1597 assert!(is_non_retryable_client_error(&err));
1598 }
1599
1600 #[test]
1601 fn non_retryable_false_for_server_error() {
1602 let err = wrapped_provider_error(r#"{"statusCode": 500, "message": "boom"}"#);
1603 assert!(!is_non_retryable_client_error(&err));
1604 }
1605
1606 #[test]
1607 fn rate_limit_detects_429_in_wrapped_source() {
1608 let err = wrapped_provider_error(r#"{"statusCode": 429, "message": "Too Many Requests"}"#);
1609 assert!(is_rate_limit_error(&err));
1610 }
1611
1612 #[test]
1613 fn classifiers_detect_compact_json_status() {
1614 let unauthorized = wrapped_provider_error(r#"{"statusCode":401,"message":"nope"}"#);
1617 assert!(is_non_retryable_client_error(&unauthorized));
1618 let throttled = wrapped_provider_error(r#"{"statusCode":429,"message":"slow down"}"#);
1619 assert!(is_rate_limit_error(&throttled));
1620 }
1621
1622 #[test]
1623 fn mentions_http_status_requires_standalone_number() {
1624 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)); }
1629
1630 #[test]
1631 fn mentions_http_status_requires_status_context() {
1632 assert!(!mentions_http_status("max 400 tokens allowed", 400));
1635 assert!(!mentions_http_status("trace 404 emitted", 404));
1636 assert!(!mentions_http_status("req_402abc failed", 402)); assert!(!mentions_http_status("retry after 429 seconds", 429)); assert!(mentions_http_status(
1640 r#"{"statusCode":429,"message":"slow"}"#,
1641 429
1642 ));
1643 assert!(mentions_http_status(
1644 "HttpError: Invalid status code 401",
1645 401
1646 ));
1647 assert!(mentions_http_status("429 Too Many Requests", 429)); }
1649
1650 #[test]
1651 fn key_must_be_a_whole_word_not_a_substring() {
1652 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));
1660 assert!(!mentions_http_status("statuslike 401 marker", 401));
1661 assert!(!mentions_http_status("xxxxxxxxxxxxxxxxxunicode 404", 404));
1664 assert!(mentions_http_status(r#"{"status_code": 401}"#, 401));
1666 }
1667
1668 #[test]
1669 fn classifies_provider_error_types_without_numeric_status() {
1670 let anthropic_auth = wrapped_provider_error(
1673 r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
1674 );
1675 assert!(!anthropic_auth.to_string().contains("401"));
1676 assert!(is_non_retryable_client_error(&anthropic_auth));
1677 assert!(!is_rate_limit_error(&anthropic_auth));
1678
1679 let openai_key =
1680 wrapped_provider_error(r#"{"error":{"code":"invalid_api_key","message":"bad key"}}"#);
1681 assert!(is_non_retryable_client_error(&openai_key));
1682
1683 let bad_request = wrapped_provider_error(
1684 r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
1685 );
1686 assert!(is_non_retryable_client_error(&bad_request));
1687
1688 let ctx_len = wrapped_provider_error(r#"{"error":{"code":"context_length_exceeded"}}"#);
1689 assert!(is_non_retryable_client_error(&ctx_len));
1690
1691 let quota = wrapped_provider_error(
1693 r#"{"error":{"type":"insufficient_quota","message":"exceeded your current quota"}}"#,
1694 );
1695 assert!(is_non_retryable_client_error("a));
1696 assert!(!is_rate_limit_error("a));
1697
1698 let quota_with_429 = wrapped_provider_error(
1699 r#"{"statusCode":429,"error":{"type":"insufficient_quota","message":"Too Many Requests"}}"#,
1700 );
1701 assert!(is_non_retryable_client_error("a_with_429));
1702 assert!(!is_rate_limit_error("a_with_429));
1703 assert!(!retry_policy("a_with_429).retry);
1704
1705 let overloaded =
1707 wrapped_provider_error(r#"{"type":"error","error":{"type":"overloaded_error"}}"#);
1708 assert!(is_rate_limit_error(&overloaded));
1709 assert!(!is_non_retryable_client_error(&overloaded));
1710
1711 let throttled = wrapped_provider_error(r#"{"error":{"code":"rate_limit_exceeded"}}"#);
1712 assert!(is_rate_limit_error(&throttled));
1713 }
1714
1715 #[test]
1716 fn server_error_takes_precedence_over_nested_4xx() {
1717 let err = wrapped_provider_error(r#"{"statusCode":502,"error":{"code":403}}"#);
1720 assert!(!is_non_retryable_client_error(&err));
1721 let nested = wrapped_provider_error(r#"{"statusCode":501,"error":{"code":403}}"#);
1723 assert!(!is_non_retryable_client_error(&nested));
1724 let pure_4xx = wrapped_provider_error(r#"{"statusCode":403,"message":"forbidden"}"#);
1726 assert!(is_non_retryable_client_error(&pure_4xx));
1727 }
1728
1729 fn tool_call_content() -> AssistantContent {
1730 use rig_core::completion::message::ToolFunction;
1731 AssistantContent::ToolCall(ToolCall::new(
1732 "call-1".to_string(),
1733 ToolFunction::new("read_file".to_string(), serde_json::json!({ "path": "x" })),
1734 ))
1735 }
1736
1737 #[test]
1740 fn a_structured_tool_call_overrides_any_wire_finish_reason() {
1741 let alone = OneOrMany::one(tool_call_content());
1742 let beside_text = OneOrMany::many(vec![
1743 AssistantContent::text("narration before the call"),
1744 tool_call_content(),
1745 ])
1746 .expect("two items");
1747 for choice in [alone, beside_text] {
1748 for wire in [
1749 FinishReason::Stop,
1750 FinishReason::MaxTokens,
1751 FinishReason::None,
1752 FinishReason::Other("length_capped".to_string()),
1753 ] {
1754 assert_eq!(resolve_finish_reason(&choice, wire), FinishReason::ToolUse);
1755 }
1756 }
1757 }
1758
1759 #[test]
1760 fn without_tool_calls_the_wire_finish_reason_stands() {
1761 let choice = OneOrMany::one(AssistantContent::text("done"));
1762 for wire in [
1763 FinishReason::Stop,
1764 FinishReason::MaxTokens,
1765 FinishReason::None,
1766 FinishReason::Other("content_filter".to_string()),
1767 ] {
1768 assert_eq!(resolve_finish_reason(&choice, wire.clone()), wire);
1769 }
1770 }
1771}