use eyre::{Result, WrapErr};
use rig_core::OneOrMany;
use rig_core::client::CompletionClient;
use rig_core::completion::CompletionError;
use rig_core::completion::message::ReasoningContent;
use rig_core::completion::message::ToolCall;
use rig_core::completion::message::ToolChoice;
use rig_core::completion::{AssistantContent, CompletionModel, Message};
use rig_core::providers::{anthropic, gemini, openai, openrouter};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::Semaphore;
use tracing::warn;
const MAX_COMPLETION_ATTEMPTS: usize = 4;
const RATE_LIMIT_MAX_COMPLETION_ATTEMPTS: usize = 8;
const BASE_BACKOFF_MS: u64 = 250;
const MAX_BACKOFF_MS: u64 = 5_000;
const RATE_LIMIT_BASE_BACKOFF_MS: u64 = 5_000;
const RATE_LIMIT_MAX_BACKOFF_MS: u64 = 60_000;
const ANTHROPIC_DEFAULT_MAX_TOKENS: u64 = 8_192;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Completion {
pub model: String,
pub prompt: Message,
pub preamble: Option<String>,
pub history: Vec<Message>,
pub tools: Vec<rig_core::completion::ToolDefinition>,
pub tool_choice: Option<ToolChoice>,
pub max_tokens: Option<u64>,
pub additional_params: Option<Value>,
}
impl Completion {
pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
self.preamble = Some(preamble.into());
self
}
pub fn tools(mut self, tools: Vec<rig_core::completion::ToolDefinition>) -> Self {
self.tools = tools;
self
}
pub fn history(mut self, history: Vec<Message>) -> Self {
self.history = history;
self
}
pub fn max_tokens(mut self, max_tokens: u64) -> Self {
self.max_tokens = Some(max_tokens);
self
}
pub fn additional_params(mut self, additional_params: Value) -> Self {
self.additional_params = Some(additional_params);
self
}
}
impl From<Completion> for rig_core::completion::CompletionRequest {
fn from(value: Completion) -> Self {
let chat_history = value
.history
.into_iter()
.chain(std::iter::once(value.prompt))
.collect::<Vec<_>>();
rig_core::completion::CompletionRequest {
model: None,
chat_history: OneOrMany::many(chat_history)
.expect("completion request must include at least one message"),
preamble: value.preamble,
documents: Vec::new(),
tools: value.tools,
temperature: None,
max_tokens: value.max_tokens,
additional_params: value.additional_params,
output_schema: None,
tool_choice: value.tool_choice,
record_telemetry_content: false,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum FinishReason {
None,
Stop,
MaxTokens,
ToolUse,
Other(String),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CompletionResponse {
pub choice: OneOrMany<AssistantContent>,
pub finish_reason: FinishReason,
pub usage: TokenUsage,
pub selected_model: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
pub struct TokenUsage {
pub input_tokens: u64,
pub output_tokens: u64,
pub total_tokens: u64,
#[serde(default)]
pub cached_input_tokens: u64,
#[serde(default)]
pub cache_creation_input_tokens: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheAccounting {
OutsidePrompt,
InsidePrompt,
}
impl TokenUsage {
pub fn from_provider(usage: &rig_core::completion::Usage, accounting: CacheAccounting) -> Self {
let input_tokens = match accounting {
CacheAccounting::OutsidePrompt => usage
.input_tokens
.saturating_add(usage.cached_input_tokens)
.saturating_add(usage.cache_creation_input_tokens),
CacheAccounting::InsidePrompt => usage.input_tokens,
};
Self {
input_tokens,
output_tokens: usage.output_tokens,
total_tokens: input_tokens.saturating_add(usage.output_tokens),
cached_input_tokens: usage.cached_input_tokens,
cache_creation_input_tokens: usage.cache_creation_input_tokens,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ConversationUsageWindow {
compact_threshold: Option<u64>,
usage: TokenUsage,
}
impl ConversationUsageWindow {
pub fn new(compact_threshold: Option<u64>) -> Self {
Self {
compact_threshold,
usage: TokenUsage::default(),
}
}
pub fn should_compact(&self) -> bool {
self.compact_threshold
.map(|threshold| self.usage.total_tokens >= threshold)
.unwrap_or(false)
}
pub fn usage(&self) -> TokenUsage {
self.usage
}
pub fn record(&mut self, usage: TokenUsage) {
self.usage = usage;
}
pub fn reset(&mut self) {
self.usage = TokenUsage::default();
}
}
impl CompletionResponse {
pub fn message(&self) -> Message {
Message::Assistant {
id: None,
content: self.choice.clone(),
}
}
pub fn tool_calls(&self) -> Option<Vec<ToolCall>> {
if self.finish_reason != FinishReason::ToolUse {
return None;
}
let calls = self
.choice
.iter()
.filter_map(|content| match content {
AssistantContent::ToolCall(call) => Some(call.clone()),
_ => None,
})
.collect::<Vec<_>>();
if calls.is_empty() { None } else { Some(calls) }
}
pub fn text(&self) -> String {
let raw = self
.choice
.iter()
.filter_map(|content| match content {
AssistantContent::Text(text) => Some(text.text().to_string()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
let (stripped, unclosed_body) = scan_think_blocks(&raw);
let Some(start) = unclosed_body else {
return stripped;
};
let recovered = self.recover_unterminated_think(&raw[start..]);
match (stripped.is_empty(), recovered.is_empty()) {
(_, true) => stripped,
(true, false) => recovered,
(false, false) => format!("{stripped}\n\n{recovered}"),
}
}
fn recover_unterminated_think(&self, body: &str) -> String {
let Some(reasoning) = self.reasoning_text() else {
return String::new();
};
let body = body.trim_start();
let Some(answer) = body.strip_prefix(reasoning.trim()) else {
return String::new();
};
let cuts_mid_word = reasoning
.trim()
.chars()
.next_back()
.is_some_and(char::is_alphanumeric)
&& answer.starts_with(char::is_alphanumeric);
match cuts_mid_word {
true => String::new(),
false => answer.trim().to_string(),
}
}
fn reasoning_text(&self) -> Option<String> {
let text = self
.choice
.iter()
.filter_map(|content| match content {
AssistantContent::Reasoning(reasoning) => Some(&reasoning.content),
_ => None,
})
.flatten()
.filter_map(|block| match block {
ReasoningContent::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect::<String>();
match text.trim().is_empty() {
true => None,
false => Some(text),
}
}
}
fn scan_think_blocks(text: &str) -> (String, Option<usize>) {
fn match_think_tag(s: &str, close: bool) -> Option<usize> {
let prefix = if close { "</think" } else { "<think" };
if !s.get(..prefix.len())?.eq_ignore_ascii_case(prefix) {
return None;
}
let after = &s[prefix.len()..];
let ws = after.len() - after.trim_start().len();
after[ws..]
.starts_with('>')
.then_some(prefix.len() + ws + 1)
}
let mut out = String::with_capacity(text.len());
let mut depth: usize = 0;
let mut consumed = 0usize;
let mut open_body_start = None;
let mut rest = text;
while !rest.is_empty() {
if rest.starts_with('<') {
if let Some(len) = match_think_tag(rest, false) {
depth += 1;
consumed += len;
if depth == 1 {
open_body_start = Some(consumed);
}
rest = &rest[len..];
continue;
}
if let Some(len) = match_think_tag(rest, true) {
depth = depth.saturating_sub(1);
if depth == 0 {
open_body_start = None;
}
consumed += len;
rest = &rest[len..];
continue;
}
}
let ch = rest.chars().next().expect("rest is non-empty");
if depth == 0 {
out.push(ch);
}
consumed += ch.len_utf8();
rest = &rest[ch.len_utf8()..];
}
let unclosed_body = match depth > 0 {
true => open_body_start,
false => None,
};
(out.trim().to_string(), unclosed_body)
}
pub trait LLMClient: Send + Sync {
fn completion(
&self,
completion: Completion,
) -> impl Future<Output = Result<CompletionResponse>> + Send;
fn into_arc(self) -> Arc<dyn LLMClientDyn>
where
Self: Sized + 'static,
{
Arc::new(self)
}
}
pub trait LLMClientDyn: Send + Sync {
fn completion(
&self,
completion: Completion,
) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>>;
}
impl<T: LLMClient> LLMClientDyn for T {
fn completion(
&self,
completion: Completion,
) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
Box::pin(LLMClient::completion(self, completion))
}
}
impl LLMClient for Box<dyn LLMClientDyn> {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
(**self).completion(completion).await
}
}
fn empty_response_diagnosis(response: &CompletionResponse) -> String {
let output_tokens = response.usage.output_tokens;
match &response.finish_reason {
FinishReason::MaxTokens => format!(
"hit the output limit after {output_tokens} tokens without emitting content — \
reasoning consumed the whole budget, so raise max_tokens or leave it unset to use \
the provider's own limit"
),
other => format!("finish_reason {other:?}, {output_tokens} output tokens"),
}
}
pub struct RetryingLLM<C> {
inner: C,
}
pub trait WithRetryExt: Sized {
fn with_retry(self) -> RetryingLLM<Self> {
RetryingLLM { inner: self }
}
}
impl<T: LLMClient> WithRetryExt for T {}
impl<C: LLMClient> LLMClient for RetryingLLM<C> {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let mut attempt = 0usize;
loop {
attempt += 1;
match self.inner.completion(completion.clone()).await {
Ok(response) => {
if response.text().is_empty() && response.tool_calls().is_none() {
let diagnosis = empty_response_diagnosis(&response);
if attempt >= MAX_COMPLETION_ATTEMPTS {
eyre::bail!(
"model returned empty response after {attempt} attempts: {diagnosis}"
);
}
let backoff = jittered_backoff(attempt, BASE_BACKOFF_MS, MAX_BACKOFF_MS);
warn!(
model = %completion.model,
attempt,
max_attempts = MAX_COMPLETION_ATTEMPTS,
backoff_ms = backoff.as_millis(),
diagnosis,
"retrying after empty model response"
);
tokio::time::sleep(backoff).await;
continue;
}
return Ok(response);
}
Err(err) => {
let policy = retry_policy(&err);
if !policy.retry || attempt >= policy.max_attempts {
return Err(err);
}
let backoff =
jittered_backoff(attempt, policy.base_backoff_ms, policy.max_backoff_ms);
warn!(
model = %completion.model,
attempt,
max_attempts = policy.max_attempts,
backoff_ms = backoff.as_millis(),
error = %err,
"retrying model completion after error"
);
tokio::time::sleep(backoff).await;
}
}
}
}
}
pub struct AlloySlot {
pub client: Arc<dyn LLMClientDyn>,
pub model: String,
pub max_tokens: Option<u64>,
}
pub struct AlloyClient {
slots: Vec<AlloySlot>,
}
impl AlloyClient {
pub fn new(slots: Vec<AlloySlot>) -> Result<Self> {
if slots.is_empty() {
eyre::bail!("AlloyClient requires at least one slot");
}
Ok(Self { slots })
}
fn pick_idx(&self) -> usize {
use rand::RngExt;
rand::rng().random_range(0..self.slots.len())
}
}
impl LLMClientDyn for AlloyClient {
fn completion(
&self,
mut completion: Completion,
) -> Pin<Box<dyn Future<Output = Result<CompletionResponse>> + Send + '_>> {
let slot = &self.slots[self.pick_idx()];
completion.model = slot.model.clone();
completion.max_tokens = slot.max_tokens;
let client = Arc::clone(&slot.client);
let model = slot.model.clone();
Box::pin(async move {
let mut response = client.completion(completion).await?;
response.selected_model = Some(model);
Ok(response)
})
}
}
pub async fn throttled_completion(
semaphore: &Semaphore,
client: &Arc<dyn LLMClientDyn>,
completion: Completion,
) -> Result<CompletionResponse> {
let _permit = semaphore.acquire().await.expect("llm semaphore closed");
client.completion(completion).await
}
struct RetryPolicy {
retry: bool,
max_attempts: usize,
base_backoff_ms: u64,
max_backoff_ms: u64,
}
fn retry_policy(err: &eyre::Report) -> RetryPolicy {
if is_rate_limit_error(err) {
return RetryPolicy {
retry: true,
max_attempts: RATE_LIMIT_MAX_COMPLETION_ATTEMPTS,
base_backoff_ms: RATE_LIMIT_BASE_BACKOFF_MS,
max_backoff_ms: RATE_LIMIT_MAX_BACKOFF_MS,
};
}
if is_non_retryable_client_error(err) {
return RetryPolicy {
retry: false,
max_attempts: 0,
base_backoff_ms: 0,
max_backoff_ms: 0,
};
}
RetryPolicy {
retry: true,
max_attempts: MAX_COMPLETION_ATTEMPTS,
base_backoff_ms: BASE_BACKOFF_MS,
max_backoff_ms: MAX_BACKOFF_MS,
}
}
const STATUS_REASONS: &[(u16, &str)] = &[
(400, "bad request"),
(401, "unauthorized"),
(402, "payment required"),
(403, "forbidden"),
(404, "not found"),
(429, "too many requests"),
(500, "internal server error"),
(502, "bad gateway"),
(503, "service unavailable"),
(504, "gateway timeout"),
];
const STATUS_KEY_WINDOW: usize = 24;
pub(crate) fn mentions_http_status(msg: &str, status: u16) -> bool {
let lower = msg.to_ascii_lowercase();
let needle = status.to_string();
let reason = STATUS_REASONS
.iter()
.find(|(code, _)| *code == status)
.map(|(_, phrase)| *phrase);
let bytes = lower.as_bytes();
let mut from = 0;
while let Some(rel) = lower[from..].find(&needle) {
let start = from + rel;
let end = start + needle.len();
let prev_digit = start > 0 && bytes[start - 1].is_ascii_digit();
let next_digit = end < bytes.len() && bytes[end].is_ascii_digit();
if !prev_digit && !next_digit && status_in_context(&lower, start, end, reason) {
return true;
}
from = start + 1;
}
false
}
fn status_in_context(lower: &str, start: usize, end: usize, reason: Option<&str>) -> bool {
if let Some(reason) = reason {
if lower[end..].trim_start().starts_with(reason) {
return true;
}
}
let mut window_start = start.saturating_sub(STATUS_KEY_WINDOW);
while !lower.is_char_boundary(window_start) {
window_start += 1;
}
key_word_present(lower, window_start, start, "status")
|| key_word_present(lower, window_start, start, "code")
|| key_word_present(lower, window_start, start, "statuscode")
}
fn key_word_present(lower: &str, lo: usize, hi: usize, key: &str) -> bool {
let bytes = lower.as_bytes();
let region = &lower[lo..hi];
let mut from = 0;
while let Some(rel) = region[from..].find(key) {
let abs = lo + from + rel;
let left_ok = abs == 0 || {
let b = bytes[abs - 1];
!b.is_ascii_alphanumeric() && b != b'_'
};
let after = abs + key.len();
let right_ok = after >= bytes.len() || !bytes[after].is_ascii_alphanumeric();
if left_ok && right_ok {
return true;
}
from += rel + 1;
}
false
}
const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
"authentication_error",
"invalid_api_key",
"permission_error",
"permission_denied",
"invalid_request_error",
"not_found_error",
"context_length_exceeded",
"insufficient_quota",
];
const RATE_LIMIT_ERROR_TYPES: &[&str] = &[
"rate_limit_error",
"rate_limit_exceeded",
"overloaded_error",
];
const PERMANENT_QUOTA_ERROR_TYPES: &[&str] = &["insufficient_quota"];
fn is_non_retryable_client_error(err: &eyre::Report) -> bool {
let msg = format!("{err:#}");
if [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
.iter()
.any(|&status| mentions_http_status(&msg, status))
{
return false;
}
if [400, 401, 402, 403, 404]
.iter()
.any(|&status| mentions_http_status(&msg, status))
{
return true;
}
let lower = msg.to_ascii_lowercase();
NON_RETRYABLE_ERROR_TYPES.iter().any(|t| lower.contains(t))
}
fn is_rate_limit_error(err: &eyre::Report) -> bool {
let msg = format!("{err:#}").to_ascii_lowercase();
if PERMANENT_QUOTA_ERROR_TYPES.iter().any(|t| msg.contains(t)) {
return false;
}
mentions_http_status(&msg, 429)
|| msg.contains("rate limit")
|| msg.contains("too many requests")
|| msg.contains("tokens per minute")
|| msg.contains("requests per minute")
|| RATE_LIMIT_ERROR_TYPES.iter().any(|t| msg.contains(t))
}
fn jittered_backoff(attempt: usize, base_backoff_ms: u64, max_backoff_ms: u64) -> Duration {
let exp = 2u64.saturating_pow((attempt - 1) as u32);
let base = (base_backoff_ms * exp).min(max_backoff_ms);
let jitter = jitter_factor();
let jittered = (base as f64 * jitter).round() as u64;
Duration::from_millis(jittered.max(1))
}
fn jitter_factor() -> f64 {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let scaled = (nanos % 1000) as f64 / 1000.0;
0.5 + scaled
}
#[derive(Debug, Deserialize)]
struct OpenRouterErrorEnvelope {
error: OpenRouterErrorBody,
}
#[derive(Debug, Deserialize)]
struct OpenRouterErrorBody {
message: String,
code: Option<u16>,
}
fn normalize_openrouter_completion_error(err: &CompletionError) -> eyre::Report {
match err {
CompletionError::ResponseError(msg) => normalize_openrouter_response_error(msg),
CompletionError::ProviderError(msg) => eyre::eyre!("ProviderError: {msg}"),
_ => eyre::eyre!("{err}"),
}
}
fn normalize_openrouter_response_error(msg: &str) -> eyre::Report {
if msg.contains("no message or tool call") || msg.contains("no choices") {
return eyre::eyre!("empty response from model (no message or tool call)");
}
if let Some(err) = parse_openrouter_error_envelope(msg) {
return match err.code {
Some(code) => eyre::eyre!(
"HttpError: Invalid status code {code} OpenRouter provider error: {}",
err.message
),
None => eyre::eyre!("ProviderError: {}", err.message),
};
}
eyre::eyre!("ResponseError: {msg}")
}
fn parse_openrouter_error_envelope(msg: &str) -> Option<OpenRouterErrorBody> {
let body = msg.split_once("response body:")?.1.trim();
serde_json::from_str::<OpenRouterErrorEnvelope>(body)
.ok()
.map(|envelope| envelope.error)
}
fn is_local_base_url(base_url: Option<&str>) -> bool {
base_url
.map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
.unwrap_or(false)
}
fn missing_or_local(key_env: &str, base_url: Option<&str>) -> Result<String> {
if is_local_base_url(base_url) {
Ok("local".to_string())
} else {
Err(eyre::eyre!("missing env var {key_env}"))
}
}
pub enum LLMProvider {
Anthropic {
base_url: Option<String>,
api_key_env: Option<String>,
},
Gemini {
base_url: Option<String>,
api_key_env: Option<String>,
},
OpenAi {
base_url: Option<String>,
api_key_env: Option<String>,
},
OpenRouter {
api_key_env: String,
},
}
impl LLMProvider {
pub fn client_from_env(&self) -> Result<Box<dyn LLMClientDyn>> {
match self {
LLMProvider::Anthropic {
base_url,
api_key_env,
} => {
let key_env = api_key_env.as_deref().unwrap_or("ANTHROPIC_API_KEY");
let api_key = std::env::var(key_env)
.or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
let mut builder = anthropic::Client::builder().api_key(api_key);
if let Some(url) = base_url {
builder = builder.base_url(url);
}
Ok(Box::new(builder.build()?))
}
LLMProvider::Gemini {
base_url,
api_key_env,
} => {
let api_key = match api_key_env {
Some(key_env) => std::env::var(key_env)
.or_else(|_| missing_or_local(key_env, base_url.as_deref()))?,
None => std::env::var("GEMINI_API_KEY")
.or_else(|_| std::env::var("GOOGLE_AI_API_KEY"))
.or_else(|_| {
missing_or_local(
"GEMINI_API_KEY (or GOOGLE_AI_API_KEY)",
base_url.as_deref(),
)
})?,
};
let mut builder = gemini::Client::builder().api_key(api_key);
if let Some(url) = base_url {
builder = builder.base_url(url);
}
let client = builder
.build()
.map_err(|e| eyre::eyre!("failed to create Gemini client: {e}"))?;
Ok(Box::new(client))
}
LLMProvider::OpenAi {
base_url,
api_key_env,
} => {
let key_env = api_key_env.as_deref().unwrap_or("OPENAI_API_KEY");
let api_key = std::env::var(key_env)
.or_else(|_| missing_or_local(key_env, base_url.as_deref()))?;
let mut builder = openai::CompletionsClient::builder().api_key(&api_key);
if let Some(url) = base_url {
builder = builder.base_url(url);
}
Ok(Box::new(builder.build()?))
}
LLMProvider::OpenRouter { api_key_env } => {
let api_key = std::env::var(api_key_env)
.map_err(|_| eyre::eyre!("missing env var {api_key_env}"))?;
let client = openrouter::Client::builder()
.api_key(&api_key)
.http_headers(openrouter_headers()?)
.build()?;
Ok(Box::new(client))
}
}
}
}
pub fn openrouter_headers() -> Result<reqwest::header::HeaderMap> {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
"HTTP-Referer",
"https://github.com/arsenyinfo/nitpicker".parse()?,
);
headers.insert("X-OpenRouter-Title", "nitpicker".parse()?);
headers.insert(
"X-OpenRouter-Categories",
"cli-agent,programming-app".parse()?,
);
Ok(headers)
}
impl LLMClient for openrouter::Client {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let model_name = completion.model.clone();
let mut request: rig_core::completion::CompletionRequest = completion.into();
request.model = Some(model_name.clone());
let model = self.completion_model(&model_name);
let response = model
.completion(request)
.await
.map_err(|e| normalize_openrouter_completion_error(&e))?;
let mut finish_reason = response
.raw_response
.choices
.first()
.and_then(|c| c.finish_reason.as_deref())
.map(|reason| match reason {
"stop" => FinishReason::Stop,
"length" => FinishReason::MaxTokens,
"tool_calls" => FinishReason::ToolUse,
other => FinishReason::Other(other.to_string()),
})
.unwrap_or(FinishReason::None);
if response
.choice
.iter()
.any(|content| matches!(content, AssistantContent::ToolCall(_)))
{
finish_reason = FinishReason::ToolUse;
}
Ok(CompletionResponse {
choice: response.choice,
finish_reason,
usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
selected_model: Some(model_name),
})
}
}
#[cfg(feature = "antigravity")]
pub fn create_gemini_client_with_proxy(
proxy_url: &str,
) -> Result<std::sync::Arc<dyn LLMClientDyn>> {
let api_key = std::env::var("GEMINI_API_KEY").unwrap_or_else(|_| "oauth-proxy".to_string());
let client = gemini::Client::builder()
.api_key(api_key)
.base_url(proxy_url)
.build()?;
Ok(client.with_retry().into_arc())
}
impl LLMClient for anthropic::Client {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let model_name = completion.model.clone();
let mut request: rig_core::completion::CompletionRequest = completion.into();
request.model = Some(model_name.clone());
request
.max_tokens
.get_or_insert(ANTHROPIC_DEFAULT_MAX_TOKENS);
let model = self.completion_model(model_name.clone());
let response = model
.completion(request)
.await
.wrap_err_with(|| format!("Anthropic completion failed for model '{model_name}'"))?;
let mut finish_reason = response
.raw_response
.stop_reason
.clone()
.map(|reason| match reason.as_str() {
"end_turn" => FinishReason::Stop,
"max_tokens" => FinishReason::MaxTokens,
"tool_use" => FinishReason::ToolUse,
other => FinishReason::Other(other.to_string()),
})
.unwrap_or(FinishReason::None);
if response
.choice
.iter()
.any(|content| matches!(content, AssistantContent::ToolCall(_)))
{
finish_reason = FinishReason::ToolUse;
}
Ok(CompletionResponse {
choice: response.choice,
finish_reason,
usage: TokenUsage::from_provider(&response.usage, CacheAccounting::OutsidePrompt),
selected_model: Some(model_name),
})
}
}
impl LLMClient for gemini::Client {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let model_name = completion.model.clone();
let params = build_gemini_additional_params(&completion)?;
let mut request: rig_core::completion::CompletionRequest = completion.into();
request.model = Some(model_name.clone());
request.additional_params = Some(params);
let model = self.completion_model(model_name.clone());
let response = model
.completion(request)
.await
.wrap_err_with(|| format!("Gemini completion failed for model '{model_name}'"))?;
let mut finish_reason = response
.raw_response
.candidates
.first()
.and_then(|candidate| candidate.finish_reason.clone())
.map(map_gemini_finish_reason)
.unwrap_or(FinishReason::None);
if response
.choice
.iter()
.any(|content| matches!(content, AssistantContent::ToolCall(_)))
{
finish_reason = FinishReason::ToolUse;
}
Ok(CompletionResponse {
choice: response.choice,
finish_reason,
usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
selected_model: Some(model_name),
})
}
}
fn model_needs_max_completion_tokens(model: &str) -> bool {
model.starts_with("o1")
|| model.starts_with("o3")
|| model.starts_with("o4")
|| model.starts_with("gpt-4o")
|| model.starts_with("gpt-4.1")
|| model.starts_with("gpt-4.5")
|| model.starts_with("gpt-5")
}
pub(crate) fn merge_json(base: Value, extra: Value) -> Value {
match (base, extra) {
(Value::Object(mut base_obj), Value::Object(extra_obj)) => {
for (k, v) in extra_obj {
let merged = match base_obj.remove(&k) {
Some(existing) => merge_json(existing, v),
None => v,
};
base_obj.insert(k, merged);
}
Value::Object(base_obj)
}
(_, extra) => extra,
}
}
impl LLMClient for openai::CompletionsClient {
async fn completion(&self, mut completion: Completion) -> Result<CompletionResponse> {
if let Some(max) = completion.max_tokens {
if model_needs_max_completion_tokens(&completion.model) {
let extra = serde_json::json!({ "max_completion_tokens": max });
completion.additional_params = Some(match completion.additional_params.take() {
Some(existing) => merge_json(existing, extra),
None => extra,
});
completion.max_tokens = None;
}
}
let model_name = completion.model.clone();
let mut request: rig_core::completion::CompletionRequest = completion.into();
request.model = Some(model_name.clone());
let model = self.completion_model(model_name.clone());
let response = model
.completion(request)
.await
.wrap_err_with(|| format!("OpenAI completion failed for model '{model_name}'"))?;
let mut finish_reason = response
.raw_response
.choices
.first()
.map(|choice| match choice.finish_reason.as_str() {
"stop" => FinishReason::Stop,
"length" => FinishReason::MaxTokens,
"tool_calls" => FinishReason::ToolUse,
other => FinishReason::Other(other.to_string()),
})
.unwrap_or(FinishReason::None);
if response
.choice
.iter()
.any(|content| matches!(content, AssistantContent::ToolCall(_)))
{
finish_reason = FinishReason::ToolUse;
}
Ok(CompletionResponse {
choice: response.choice,
finish_reason,
usage: TokenUsage::from_provider(&response.usage, CacheAccounting::InsidePrompt),
selected_model: Some(model_name),
})
}
}
#[derive(Debug, Serialize)]
struct GeminiAdditionalParams {
generation_config: Option<GenerationConfig>,
}
impl GeminiAdditionalParams {
fn from_completion(completion: &Completion) -> Self {
let config = GenerationConfig {
max_output_tokens: completion
.max_tokens
.map(|value| i32::try_from(value).unwrap_or(i32::MAX)),
};
Self {
generation_config: Some(config),
}
}
}
fn build_gemini_additional_params(completion: &Completion) -> Result<Value> {
let computed = serde_json::to_value(GeminiAdditionalParams::from_completion(completion))?;
Ok(match &completion.additional_params {
Some(existing) => merge_json(existing.clone(), computed),
None => computed,
})
}
#[derive(Debug, Serialize, Default)]
struct GenerationConfig {
#[serde(skip_serializing_if = "Option::is_none")]
max_output_tokens: Option<i32>,
}
fn map_gemini_finish_reason(
reason: gemini::completion::gemini_api_types::FinishReason,
) -> FinishReason {
use gemini::completion::gemini_api_types::FinishReason as GeminiFinishReason;
match reason {
GeminiFinishReason::Stop => FinishReason::Stop,
GeminiFinishReason::MaxTokens => FinishReason::MaxTokens,
GeminiFinishReason::FinishReasonUnspecified => FinishReason::None,
other => FinishReason::Other(format!("{other:?}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use rig_core::completion::Usage;
fn strip_think_blocks(text: &str) -> String {
scan_think_blocks(text).0
}
use serde_json::json;
fn response_with(choice: Vec<AssistantContent>) -> CompletionResponse {
CompletionResponse {
choice: OneOrMany::many(choice).expect("non-empty choice"),
finish_reason: FinishReason::Stop,
usage: TokenUsage::default(),
selected_model: None,
}
}
fn reasoning_item(text: &str) -> AssistantContent {
AssistantContent::Reasoning(rig_core::completion::message::Reasoning::new(text))
}
#[test]
fn unterminated_think_keeps_the_answer_and_drops_the_duplicated_reasoning() {
let reasoning = "The debate is extremely brief. The Actor suggested `eyre`.";
let response = response_with(vec![
reasoning_item(reasoning),
AssistantContent::text(format!(
"<think>\n{reasoning}\n\n### Verdict\n**Agreed: use `eyre` for applications.**"
)),
]);
assert_eq!(
response.text(),
"### Verdict\n**Agreed: use `eyre` for applications.**"
);
}
#[test]
fn unterminated_think_after_a_prefix_still_recovers_the_answer() {
let reasoning = "Weighing both sides.";
let response = response_with(vec![
reasoning_item(reasoning),
AssistantContent::text(format!(
"Here is my review.\n<think>\n{reasoning}\n\n### Verdict\nShip it."
)),
]);
assert_eq!(
response.text(),
"Here is my review.\n\n### Verdict\nShip it."
);
}
#[test]
fn fragmented_reasoning_is_concatenated_without_separators() {
let response = response_with(vec![
reasoning_item("weighing the options"),
reasoning_item(" carefully."),
AssistantContent::text("<think>\nweighing the options carefully.\n\nVerdict: ship it."),
]);
assert_eq!(response.text(), "Verdict: ship it.");
}
#[test]
fn unterminated_think_without_structured_reasoning_stays_empty() {
let response = response_with(vec![AssistantContent::text(
"<think>\nweighing it up\n\nVerdict: ship it.",
)]);
assert!(response.text().is_empty());
}
#[test]
fn summary_reasoning_is_not_used_to_split_the_body() {
let response = response_with(vec![
AssistantContent::Reasoning(rig_core::completion::message::Reasoning::summaries(vec![
"brief".to_string(),
])),
AssistantContent::text("<think>private chain"),
]);
assert!(response.text().is_empty());
}
#[test]
fn a_prefix_that_cuts_mid_word_is_not_treated_as_reasoning() {
let response = response_with(vec![
reasoning_item("Ver"),
AssistantContent::text("<think>Verdict: ship it."),
]);
assert!(response.text().is_empty());
}
#[test]
fn recovery_targets_the_block_that_stayed_open() {
let response = response_with(vec![
reasoning_item("secret"),
AssistantContent::text("<think>old</think>\n<think>secret\n\nFINAL"),
]);
assert_eq!(response.text(), "FINAL");
}
#[test]
fn a_stray_closing_tag_does_not_misdirect_recovery() {
let response = response_with(vec![
reasoning_item("secret"),
AssistantContent::text("</think><think>secret\n\nFINAL"),
]);
assert_eq!(response.text(), "FINAL");
}
#[test]
fn a_reasoning_only_response_is_still_empty() {
let reasoning = "still thinking about it";
let response = response_with(vec![
reasoning_item(reasoning),
AssistantContent::text(format!("<think>\n{reasoning}")),
]);
assert!(response.text().is_empty());
let closed = response_with(vec![AssistantContent::text(
"<think>done deliberating</think>",
)]);
assert!(closed.text().is_empty());
}
#[test]
fn closed_think_block_still_yields_only_the_answer() {
let response = response_with(vec![AssistantContent::text(
"<think>weighing it up</think>Verdict: ship it.",
)]);
assert_eq!(response.text(), "Verdict: ship it.");
}
fn anthropic_usage(input: u64, output: u64, cached: u64, creation: u64) -> Usage {
let mut usage = Usage::new();
usage.input_tokens = input;
usage.output_tokens = output;
usage.cached_input_tokens = cached;
usage.cache_creation_input_tokens = creation;
usage.total_tokens = input + cached + creation + output;
usage
}
fn anthropic(usage: &Usage) -> TokenUsage {
TokenUsage::from_provider(usage, CacheAccounting::OutsidePrompt)
}
fn prompt_inclusive(usage: &Usage) -> TokenUsage {
TokenUsage::from_provider(usage, CacheAccounting::InsidePrompt)
}
#[test]
fn provider_shapes_meter_a_cache_hit_identically() {
let from_anthropic = anthropic(&anthropic_usage(52, 8, 3456, 0));
let mut openai = Usage::new();
openai.input_tokens = 3508;
openai.output_tokens = 8;
openai.cached_input_tokens = 3456;
openai.total_tokens = 3516;
let from_openai = prompt_inclusive(&openai);
assert_eq!(from_anthropic.input_tokens, 3508);
assert_eq!(from_anthropic.input_tokens, from_openai.input_tokens);
assert_eq!(
from_anthropic.cached_input_tokens,
from_openai.cached_input_tokens
);
for usage in [from_anthropic, from_openai] {
assert_eq!(usage.total_tokens, usage.input_tokens + usage.output_tokens);
}
}
#[test]
fn gemini_cache_reads_are_never_added_to_its_prompt() {
let mut usage = Usage::new();
usage.input_tokens = 40;
usage.output_tokens = 30;
usage.reasoning_tokens = 10;
usage.tool_use_prompt_tokens = 12;
usage.cached_input_tokens = 8;
usage.total_tokens = 100;
let usage = prompt_inclusive(&usage);
assert_eq!(usage.input_tokens, 40);
assert_eq!(usage.cached_input_tokens, 8);
}
#[test]
fn openrouter_total_disagreement_does_not_inflate_the_prompt() {
let mut usage = Usage::new();
usage.input_tokens = 500;
usage.output_tokens = 10;
usage.cached_input_tokens = 5;
usage.total_tokens = 515;
let usage = prompt_inclusive(&usage);
assert_eq!(usage.input_tokens, 500);
assert_eq!(usage.total_tokens, 510);
}
#[test]
fn missing_provider_total_still_meters_reported_input() {
let mut usage = Usage::new();
usage.input_tokens = 1200;
usage.output_tokens = 40;
let usage = prompt_inclusive(&usage);
assert_eq!(usage.input_tokens, 1200);
assert_eq!(usage.total_tokens, 1240);
}
#[test]
fn anthropic_cache_writes_count_toward_the_prompt() {
let usage = anthropic(&anthropic_usage(90, 10, 0, 4100));
assert_eq!(usage.cache_creation_input_tokens, 4100);
assert_eq!(usage.input_tokens, 4190);
assert_eq!(usage.total_tokens, 4200);
}
#[test]
fn contradictory_cache_metadata_is_not_papered_over() {
let mut usage = Usage::new();
usage.input_tokens = 10;
usage.output_tokens = 5;
usage.total_tokens = 15;
usage.cached_input_tokens = 5_000;
usage.cache_creation_input_tokens = 700;
let usage = prompt_inclusive(&usage);
assert_eq!(usage.input_tokens, 10);
assert_eq!(usage.total_tokens, 15);
assert_eq!(usage.cached_input_tokens, 5_000);
assert_eq!(usage.cache_creation_input_tokens, 700);
}
#[test]
fn compaction_threshold_sees_the_cached_prompt() {
let mut window = ConversationUsageWindow::new(Some(3_000));
window.record(anthropic(&anthropic_usage(52, 8, 3456, 0)));
assert!(window.should_compact());
}
#[test]
fn usage_without_cache_fields_still_deserializes() {
let usage: TokenUsage = serde_json::from_value(
json!({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),
)
.expect("legacy usage payload must decode");
assert_eq!(usage.input_tokens, 10);
assert_eq!(usage.cached_input_tokens, 0);
}
fn wrapped_provider_error(body: &str) -> eyre::Report {
let inner = eyre::eyre!("ProviderError: {body}");
Err::<(), _>(inner)
.wrap_err("Anthropic completion failed for model 'claude'")
.unwrap_err()
}
fn gemini_completion(max_tokens: Option<u64>, additional_params: Option<Value>) -> Completion {
Completion {
model: "gemini-3-pro".to_string(),
prompt: Message::user("hi".to_string()),
preamble: None,
history: Vec::new(),
tools: Vec::new(),
tool_choice: None,
max_tokens,
additional_params,
}
}
#[test]
fn merge_json_is_deep_and_extra_wins() {
let merged = merge_json(
json!({"generation_config": {"temperature": 0.2}, "a": 1}),
json!({"generation_config": {"max_output_tokens": 50}, "a": 2}),
);
assert_eq!(
merged,
json!({"generation_config": {"temperature": 0.2, "max_output_tokens": 50}, "a": 2})
);
}
#[test]
fn gemini_params_preserve_caller_config() {
let params = build_gemini_additional_params(&gemini_completion(
Some(50),
Some(json!({
"generation_config": {"temperature": 0.2},
"safetySettings": [{"category": "HARM", "threshold": "NONE"}]
})),
))
.unwrap();
assert_eq!(
params,
json!({
"generation_config": {"temperature": 0.2, "max_output_tokens": 50},
"safetySettings": [{"category": "HARM", "threshold": "NONE"}]
})
);
}
#[test]
fn gemini_params_none_yields_generation_config_only() {
let params = build_gemini_additional_params(&gemini_completion(Some(50), None)).unwrap();
assert_eq!(
params,
json!({"generation_config": {"max_output_tokens": 50}})
);
}
#[test]
fn strips_full_think_block() {
let raw = "<think>let me reason about this</think>\n\nThe bug is in foo().";
assert_eq!(strip_think_blocks(raw), "The bug is in foo().");
}
#[test]
fn strips_stray_empty_think_tags() {
let raw = "<think></think>\n## Findings\n- looks fine";
assert_eq!(strip_think_blocks(raw), "## Findings\n- looks fine");
}
#[test]
fn strips_unbalanced_and_multiline_think() {
let raw = "intro\n<think>\nstep 1\nstep 2\n</think>verdict: ok</think>";
assert_eq!(strip_think_blocks(raw), "intro\nverdict: ok");
}
#[test]
fn leaves_non_think_text_untouched() {
let raw = "no reasoning tags here, just review text";
assert_eq!(strip_think_blocks(raw), raw);
}
#[test]
fn strips_unterminated_think_to_eof() {
let raw = "answer first\n<think>reasoning that never closes\nstep 2";
assert_eq!(strip_think_blocks(raw), "answer first");
}
#[test]
fn all_reasoning_collapses_to_empty() {
let joined = format!("{}\n{}", "<think>round one</think>", "<think>round two");
assert_eq!(strip_think_blocks(&joined), "");
}
#[test]
fn strips_nested_think_blocks() {
let raw = "<think>outer <think>inner</think> still hidden</think>answer";
assert_eq!(strip_think_blocks(raw), "answer");
}
#[test]
fn strips_whitespace_padded_think_tags() {
let raw = "<think >hidden</think >visible";
assert_eq!(strip_think_blocks(raw), "visible");
}
#[test]
fn leaves_thinking_word_untouched() {
let raw = "see <thinking>kept</thinking> here";
assert_eq!(
strip_think_blocks(raw),
"see <thinking>kept</thinking> here"
);
}
#[test]
fn non_retryable_detects_status_in_wrapped_source() {
let err = wrapped_provider_error(r#"{"statusCode": 401, "message": "Unauthorized"}"#);
assert!(!err.to_string().contains("401"));
assert!(is_non_retryable_client_error(&err));
}
#[test]
fn non_retryable_false_for_server_error() {
let err = wrapped_provider_error(r#"{"statusCode": 500, "message": "boom"}"#);
assert!(!is_non_retryable_client_error(&err));
}
#[test]
fn rate_limit_detects_429_in_wrapped_source() {
let err = wrapped_provider_error(r#"{"statusCode": 429, "message": "Too Many Requests"}"#);
assert!(is_rate_limit_error(&err));
}
#[test]
fn classifiers_detect_compact_json_status() {
let unauthorized = wrapped_provider_error(r#"{"statusCode":401,"message":"nope"}"#);
assert!(is_non_retryable_client_error(&unauthorized));
let throttled = wrapped_provider_error(r#"{"statusCode":429,"message":"slow down"}"#);
assert!(is_rate_limit_error(&throttled));
}
#[test]
fn mentions_http_status_requires_standalone_number() {
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)); }
#[test]
fn mentions_http_status_requires_status_context() {
assert!(!mentions_http_status("max 400 tokens allowed", 400));
assert!(!mentions_http_status("trace 404 emitted", 404));
assert!(!mentions_http_status("req_402abc failed", 402)); assert!(!mentions_http_status("retry after 429 seconds", 429)); assert!(mentions_http_status(
r#"{"statusCode":429,"message":"slow"}"#,
429
));
assert!(mentions_http_status(
"HttpError: Invalid status code 401",
401
));
assert!(mentions_http_status("429 Too Many Requests", 429)); }
#[test]
fn key_must_be_a_whole_word_not_a_substring() {
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));
assert!(!mentions_http_status("statuslike 401 marker", 401));
assert!(!mentions_http_status("xxxxxxxxxxxxxxxxxunicode 404", 404));
assert!(mentions_http_status(r#"{"status_code": 401}"#, 401));
}
#[test]
fn classifies_provider_error_types_without_numeric_status() {
let anthropic_auth = wrapped_provider_error(
r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
);
assert!(!anthropic_auth.to_string().contains("401"));
assert!(is_non_retryable_client_error(&anthropic_auth));
assert!(!is_rate_limit_error(&anthropic_auth));
let openai_key =
wrapped_provider_error(r#"{"error":{"code":"invalid_api_key","message":"bad key"}}"#);
assert!(is_non_retryable_client_error(&openai_key));
let bad_request = wrapped_provider_error(
r#"{"error":{"type":"invalid_request_error","message":"prompt is too long"}}"#,
);
assert!(is_non_retryable_client_error(&bad_request));
let ctx_len = wrapped_provider_error(r#"{"error":{"code":"context_length_exceeded"}}"#);
assert!(is_non_retryable_client_error(&ctx_len));
let quota = wrapped_provider_error(
r#"{"error":{"type":"insufficient_quota","message":"exceeded your current quota"}}"#,
);
assert!(is_non_retryable_client_error("a));
assert!(!is_rate_limit_error("a));
let quota_with_429 = wrapped_provider_error(
r#"{"statusCode":429,"error":{"type":"insufficient_quota","message":"Too Many Requests"}}"#,
);
assert!(is_non_retryable_client_error("a_with_429));
assert!(!is_rate_limit_error("a_with_429));
assert!(!retry_policy("a_with_429).retry);
let overloaded =
wrapped_provider_error(r#"{"type":"error","error":{"type":"overloaded_error"}}"#);
assert!(is_rate_limit_error(&overloaded));
assert!(!is_non_retryable_client_error(&overloaded));
let throttled = wrapped_provider_error(r#"{"error":{"code":"rate_limit_exceeded"}}"#);
assert!(is_rate_limit_error(&throttled));
}
#[test]
fn server_error_takes_precedence_over_nested_4xx() {
let err = wrapped_provider_error(r#"{"statusCode":502,"error":{"code":403}}"#);
assert!(!is_non_retryable_client_error(&err));
let nested = wrapped_provider_error(r#"{"statusCode":501,"error":{"code":403}}"#);
assert!(!is_non_retryable_client_error(&nested));
let pure_4xx = wrapped_provider_error(r#"{"statusCode":403,"message":"forbidden"}"#);
assert!(is_non_retryable_client_error(&pure_4xx));
}
}