| 1 | use std::collections::HashMap; |
| 2 | use std::io::BufRead |
| 3 | use std::sync::Mutex |
| 4 | use std::sync::atomic |
| 5 | use std::time::Duration |
| 6 | |
| 7 | use anyhow::{Context |
| 8 | use hmac::{Hmac |
| 9 | use serde::{Deserialize |
| 10 | use serde_json::{Value |
| 11 | use sha2::{Digest |
| 12 | |
| 13 | use crate::db::StoredMessage |
| 14 | use crate::events; |
| 15 | use crate::tools::ToolDef |
| 16 | |
| 17 | pub(crate) mod |
| 18 | use providers_data::PROVIDER_ROWS |
| 19 | |
| 20 | #[derive(Clone |
| 21 | pub enum ApiFormat |
| 22 | Compatible, |
| 23 | Anthropic, |
| 24 | Gemini, |
| 25 | Bedrock, |
| 26 | } |
| 27 | |
| 28 | #[derive(Clone |
| 29 | pub struct ProviderConfig |
| 30 | pub name: String |
| 31 | pub api_format: ApiFormat |
| 32 | pub base_url: String |
| 33 | pub api_key: Option |
| 34 | pub default_model: String |
| 35 | pub max_tokens: u32 |
| 36 | /// The model's input context window in tokens (pi's `model.contextWindow`). |
| 37 | /// Drives proactive threshold auto-compaction: when the estimated context |
| 38 | /// exceeds `context_window - reserve`, older turns are folded into a |
| 39 | /// summary before the request goes out. Overridable via `CONTEXT_WINDOW`. |
| 40 | pub context_window: u32 |
| 41 | pub requires_key: bool |
| 42 | pub url_override: Option |
| 43 | pub azure_auth: bool |
| 44 | pub key_in_url: bool |
| 45 | pub aws_region: String |
| 46 | pub aws_secret_key: Option |
| 47 | pub aws_session_token: Option |
| 48 | /// Thinking effort level (`off | minimal | low | medium | high | xhigh`). |
| 49 | /// `None` = provider default. Mimics pi's thinking levels: sent as |
| 50 | /// `reasoning_effort` on OpenAI-compatible requests (the zen proxy maps |
| 51 | /// low/medium→low-ish / high / max per the DeepSeek V4 model). |
| 52 | pub effort: Option |
| 53 | } |
| 54 | |
| 55 | /// Map a pi-style effort level to the wire `reasoning_effort` value. DeepSeek |
| 56 | /// V4 accepts `low | high | max`; `off` returns `None` so the param is omitted. |
| 57 | pub fn effort_wire(level |
| 58 | match level { |
| 59 | "off" => None |
| 60 | "minimal" | "low" |
| 61 | "medium" | "high" |
| 62 | "xhigh" => Some |
| 63 | _ => None |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | impl ProviderConfig { |
| 68 | /// Resolve this config's configured effort level to the wire value. |
| 69 | fn effort_wire(&self |
| 70 | self.effort.as_deref() |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl ProviderConfig { |
| 75 | fn with_format(mut |
| 76 | self.api_format = f |
| 77 | self |
| 78 | } |
| 79 | fn with_key_in_url(mut |
| 80 | self.key_in_url = true; |
| 81 | self |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | #[derive(Clone |
| 86 | pub struct ToolCall |
| 87 | pub id: String |
| 88 | pub name: String |
| 89 | #[serde(default |
| 90 | pub arguments: Value |
| 91 | } |
| 92 | |
| 93 | #[derive(Clone |
| 94 | pub struct LlmUsage |
| 95 | pub input: u64 |
| 96 | pub output: u64 |
| 97 | pub cache_read: u64 |
| 98 | pub cache_write: u64 |
| 99 | pub total: u64 |
| 100 | } |
| 101 | |
| 102 | impl LlmUsage { |
| 103 | /// Total context tokens (pi's `calculateContextTokens`): the provider's |
| 104 | /// native `total` when available, else the sum of the components. |
| 105 | pub fn total( |
| 106 | if self.total > |
| 107 | self.total |
| 108 | } else { |
| 109 | self.input + self |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | impl LlmUsage { |
| 115 | /// Parse provider usage into the canonical shape. Handles OpenAI-style |
| 116 | /// `prompt_tokens`/`completion_tokens`/`total_tokens` (and the z.ai-style |
| 117 | /// `input_tokens`/`output_tokens`/`cache_read_input_tokens`) plus |
| 118 | /// Anthropic's `input_tokens`/`output_tokens`/`cache_read_input_tokens` |
| 119 | /// and Gemini's `promptTokenCount`/`candidatesTokenCount`/`totalTokenCount`. |
| 120 | pub fn parse( |
| 121 | let mut u |
| 122 | let take = |
| 123 | u.input = take |
| 124 | + take(v. |
| 125 | + take(v. |
| 126 | u.output = take |
| 127 | + take(v. |
| 128 | + take(v. |
| 129 | u.cache_read = take |
| 130 | + take(v. |
| 131 | + take(v. |
| 132 | + take(v. |
| 133 | u.cache_write = take |
| 134 | + take(v. |
| 135 | u.total = take |
| 136 | + take(v. |
| 137 | + take(v. |
| 138 | if u.input == |
| 139 | u.input = take |
| 140 | } |
| 141 | if u.output == |
| 142 | u.output = take |
| 143 | } |
| 144 | if u.total() |
| 145 | Some(u) |
| 146 | } else { |
| 147 | None |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub struct LlmResponse |
| 153 | pub content: Option |
| 154 | pub tool_calls: Vec |
| 155 | /// Raw `reasoning_content` this assistant turn streamed (DeepSeek-style |
| 156 | /// thinking). Passed back verbatim on the next request. |
| 157 | pub reasoning: Option |
| 158 | /// Provider stop reason, normalized: `stop`, `length` (token budget hit), |
| 159 | /// `tool_use`, or `error`. Drives pi-style overflow / recoverable-length |
| 160 | /// recovery. `None` when the provider never reported it. |
| 161 | pub finish_reason: Option |
| 162 | /// Provider token usage for this assistant message. `None` when the |
| 163 | /// provider didn't report it (or reported all zeros). |
| 164 | pub usage: Option |
| 165 | } |
| 166 | |
| 167 | /// An image attached to a user message. `data_base64` holds the raw image |
| 168 | /// bytes (already base64-encoded) so every provider format can inline it. |
| 169 | #[derive(Clone |
| 170 | pub struct ImagePart |
| 171 | pub media_type: String |
| 172 | pub data_base64: String |
| 173 | } |
| 174 | |
| 175 | #[derive(Clone |
| 176 | pub struct LlmMessage |
| 177 | pub role: String |
| 178 | pub content: Option |
| 179 | pub tool_call_id: Option |
| 180 | pub name: Option |
| 181 | pub tool_calls: Vec |
| 182 | /// Prior-turn `reasoning_content` (thinking-mode models require it to be |
| 183 | /// sent back with the assistant message on the next request). |
| 184 | pub reasoning: Option |
| 185 | pub images: Vec |
| 186 | } |
| 187 | |
| 188 | impl From<StoredMessage |
| 189 | fn from(m: |
| 190 | let tool_calls = |
| 191 | .tool_calls |
| 192 | .as_deref() |
| 193 | .and_then(|s| |
| 194 | .unwrap_or_default(); |
| 195 | let images = |
| 196 | .images |
| 197 | .as_deref() |
| 198 | .and_then(|s| |
| 199 | .unwrap_or_default(); |
| 200 | LlmMessage { |
| 201 | role: m.role |
| 202 | content: m.content |
| 203 | tool_call_id: m.tool_call_id |
| 204 | name: m.name |
| 205 | tool_calls, |
| 206 | reasoning: m.reasoning |
| 207 | images, |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn image_openai_parts(images: |
| 213 | images |
| 214 | .iter() |
| 215 | .map(|img| |
| 216 | json!({ |
| 217 | "type": "image_url", |
| 218 | "image_url": { |
| 219 | "url": format! |
| 220 | } |
| 221 | }) |
| 222 | }) |
| 223 | .collect() |
| 224 | } |
| 225 | |
| 226 | fn image_anthropic_block(img: |
| 227 | json!({ |
| 228 | "type": "image", |
| 229 | "source": { |
| 230 | "type": "base64", |
| 231 | "media_type": img. |
| 232 | "data": img. |
| 233 | } |
| 234 | }) |
| 235 | } |
| 236 | |
| 237 | fn image_gemini_part(img: |
| 238 | json!({ |
| 239 | "inline_data": { |
| 240 | "mime_type": img. |
| 241 | "data": img. |
| 242 | } |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | fn image_bedrock_block(img: |
| 247 | json!({ |
| 248 | "image": { |
| 249 | "format": img. |
| 250 | "source": {"bytes" |
| 251 | } |
| 252 | }) |
| 253 | } |
| 254 | |
| 255 | fn push_image_blocks(blocks: |
| 256 | for img in & |
| 257 | blocks.push(f |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | pub struct ProviderMeta |
| 262 | pub name: & |
| 263 | pub env: & |
| 264 | pub default_model: & |
| 265 | } |
| 266 | |
| 267 | pub fn provider_metas() |
| 268 | let mut metas |
| 269 | .iter() |
| 270 | .map(|r| |
| 271 | name: r.name |
| 272 | env: r.env |
| 273 | default_model: r.default_model |
| 274 | }) |
| 275 | .collect(); |
| 276 | metas.extend(vec! |
| 277 | ProviderMeta { |
| 278 | name: "google-vertex", |
| 279 | env: "GOOGLE_VERTEX_TOKEN", |
| 280 | default_model: "gemini-2.5-flash", |
| 281 | }, |
| 282 | ProviderMeta { |
| 283 | name: "amazon-bedrock", |
| 284 | env: "AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY", |
| 285 | default_model: "anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 286 | }, |
| 287 | ProviderMeta { |
| 288 | name: "azure", |
| 289 | env: "AZURE_OPENAI_API_KEY", |
| 290 | default_model: "(deployment)", |
| 291 | }, |
| 292 | ProviderMeta { |
| 293 | name: "ollama", |
| 294 | env: "(none)", |
| 295 | default_model: "llama3.2", |
| 296 | }, |
| 297 | ProviderMeta { |
| 298 | name: "compatible", |
| 299 | env: "(optional)", |
| 300 | default_model: "gpt-4o-mini", |
| 301 | }, |
| 302 | ProviderMeta { |
| 303 | name: "qwen", |
| 304 | env: "DASHSCOPE_API_KEY", |
| 305 | default_model: "qwen-plus", |
| 306 | }, |
| 307 | ProviderMeta { |
| 308 | name: "cohere", |
| 309 | env: "COHERE_API_KEY", |
| 310 | default_model: "command-r-plus", |
| 311 | }, |
| 312 | ProviderMeta { |
| 313 | name: "fireworks", |
| 314 | env: "FIREWORKS_API_KEY", |
| 315 | default_model: "accounts/fireworks/models/llama-v3p3-70b-instruct", |
| 316 | }, |
| 317 | ProviderMeta { |
| 318 | name: "together", |
| 319 | env: "TOGETHER_API_KEY", |
| 320 | default_model: "MiniMaxAI/MiniMax-M2.5", |
| 321 | }, |
| 322 | ProviderMeta { |
| 323 | name: "sambanova", |
| 324 | env: "SAMBANOVA_API_KEY", |
| 325 | default_model: "Meta-Llama-3.3-70B-Instruct", |
| 326 | }, |
| 327 | ProviderMeta { |
| 328 | name: "replicate", |
| 329 | env: "REPLICATE_API_TOKEN", |
| 330 | default_model: "meta/meta-llama-3-70b-instruct", |
| 331 | }, |
| 332 | ProviderMeta { |
| 333 | name: "cloudflare", |
| 334 | env: "CLOUDFLARE_API_TOKEN", |
| 335 | default_model: "@cf/meta/llama-3.1-8b-instruct", |
| 336 | }, |
| 337 | ]); |
| 338 | metas.sort_by(|a |
| 339 | metas |
| 340 | } |
| 341 | |
| 342 | fn env(key: |
| 343 | std::env::var |
| 344 | .ok() |
| 345 | .map(|s| |
| 346 | .filter(|s| |
| 347 | } |
| 348 | |
| 349 | fn env_default(key: |
| 350 | env(key).unwrap_or_else |
| 351 | } |
| 352 | |
| 353 | fn env_num<T |
| 354 | env(key).and_then |
| 355 | } |
| 356 | |
| 357 | #[allow(clippy:: |
| 358 | fn pcfg( |
| 359 | name: &str |
| 360 | key_env: &str |
| 361 | base_env: &str |
| 362 | default_base: &str |
| 363 | model_env: &str |
| 364 | default_model: &str |
| 365 | requires_key: bool |
| 366 | max_tokens: u32 |
| 367 | ) -> ProviderConfig { |
| 368 | ProviderConfig { |
| 369 | name: name.to_string |
| 370 | api_format: ApiFormat |
| 371 | base_url: env_default(base_env |
| 372 | api_key: env(key_env |
| 373 | default_model: env_default(model_env |
| 374 | max_tokens, |
| 375 | context_window: env_num(" |
| 376 | requires_key, |
| 377 | url_override: None |
| 378 | azure_auth: false, |
| 379 | key_in_url: false, |
| 380 | aws_region: "us-east-1". |
| 381 | aws_secret_key: None |
| 382 | aws_session_token: None |
| 383 | effort: None |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | pub fn resolve_provider(name |
| 388 | // Raised from 8192: reasoning-heavy models can burn the whole output |
| 389 | // budget on `reasoning_content` before producing a single answer byte |
| 390 | // (see the finish_reason=length guard in stream_compatible). |
| 391 | let max_tokens = |
| 392 | let cfg = |
| 393 | "openai" => pcfg |
| 394 | "openai", |
| 395 | "OPENAI_API_KEY", |
| 396 | "OPENAI_BASE_URL", |
| 397 | "https://api.openai.com/v1", |
| 398 | "OPENAI_MODEL", |
| 399 | "gpt-4o-mini", |
| 400 | true, |
| 401 | max_tokens, |
| 402 | ), |
| 403 | "anthropic" => pcfg |
| 404 | "anthropic", |
| 405 | "ANTHROPIC_API_KEY", |
| 406 | "ANTHROPIC_BASE_URL", |
| 407 | "https://api.anthropic.com", |
| 408 | "ANTHROPIC_MODEL", |
| 409 | "claude-sonnet-4-20250514", |
| 410 | true, |
| 411 | max_tokens, |
| 412 | ) |
| 413 | .with_format(ApiFormat::Anthropic |
| 414 | "google" | "gemini" |
| 415 | let mut c |
| 416 | "google", |
| 417 | "GOOGLE_API_KEY", |
| 418 | "GOOGLE_GENERATIVE_AI_BASE_URL", |
| 419 | "https://generativelanguage.googleapis.com/v1beta", |
| 420 | "GOOGLE_MODEL", |
| 421 | "gemini-2.0-flash", |
| 422 | true, |
| 423 | max_tokens, |
| 424 | ) |
| 425 | .with_format(ApiFormat::Gemini |
| 426 | .with_key_in_url(); |
| 427 | c.api_key = env |
| 428 | c |
| 429 | } |
| 430 | "google-vertex" | "vertex" |
| 431 | let project = |
| 432 | let location = |
| 433 | let base = |
| 434 | String::new() |
| 435 | } else { |
| 436 | format!( |
| 437 | "https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project |
| 438 | ) |
| 439 | }; |
| 440 | let mut c |
| 441 | "google-vertex", |
| 442 | "GOOGLE_VERTEX_TOKEN", |
| 443 | "GOOGLE_VERTEX_BASE_URL", |
| 444 | "", |
| 445 | "GOOGLE_VERTEX_MODEL", |
| 446 | "gemini-2.5-flash", |
| 447 | true, |
| 448 | max_tokens, |
| 449 | ) |
| 450 | .with_format(ApiFormat::Gemini |
| 451 | c.base_url = env |
| 452 | c.api_key = env |
| 453 | c |
| 454 | } |
| 455 | "amazon-bedrock" | "bedrock" |
| 456 | let region = |
| 457 | let mut c |
| 458 | "amazon-bedrock", |
| 459 | "AWS_ACCESS_KEY_ID", |
| 460 | "BEDROCK_BASE_URL", |
| 461 | &format!("https://bedrock-runtime.{ |
| 462 | "BEDROCK_MODEL", |
| 463 | "anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 464 | true, |
| 465 | max_tokens, |
| 466 | ) |
| 467 | .with_format(ApiFormat::Bedrock |
| 468 | c.aws_region = region |
| 469 | c.aws_secret_key = env |
| 470 | c.aws_session_token = env |
| 471 | c |
| 472 | } |
| 473 | "azure" => { |
| 474 | let endpoint = |
| 475 | .or_else(|| env |
| 476 | .unwrap_or_default(); |
| 477 | let deployment = |
| 478 | let version = |
| 479 | env("AZURE_OPENAI_API_VERSION"). |
| 480 | let url_override = |
| 481 | None |
| 482 | } else { |
| 483 | Some(format! |
| 484 | "{}/openai/deployments/{}/chat/completions?api-version={}", |
| 485 | endpoint.trim_end_matches('/ |
| 486 | deployment, |
| 487 | version |
| 488 | )) |
| 489 | }; |
| 490 | ProviderConfig { |
| 491 | name: "azure". |
| 492 | api_format: ApiFormat |
| 493 | base_url: endpoint, |
| 494 | api_key: env(" |
| 495 | default_model: if deployment |
| 496 | "deployment".into() |
| 497 | } else { |
| 498 | deployment.clone() |
| 499 | }, |
| 500 | max_tokens, |
| 501 | requires_key: true, |
| 502 | url_override, |
| 503 | azure_auth: true, |
| 504 | key_in_url: false, |
| 505 | aws_region: "us-east-1". |
| 506 | aws_secret_key: None |
| 507 | aws_session_token: None |
| 508 | effort: None |
| 509 | context_window: env_num(" |
| 510 | } |
| 511 | } |
| 512 | "groq" => pcfg |
| 513 | "groq", |
| 514 | "GROQ_API_KEY", |
| 515 | "GROQ_BASE_URL", |
| 516 | "https://api.groq.com/openai/v1", |
| 517 | "GROQ_MODEL", |
| 518 | "llama-3.3-70b-versatile", |
| 519 | true, |
| 520 | max_tokens, |
| 521 | ), |
| 522 | "mistral" => pcfg |
| 523 | "mistral", |
| 524 | "MISTRAL_API_KEY", |
| 525 | "MISTRAL_BASE_URL", |
| 526 | "https://api.mistral.ai/v1", |
| 527 | "MISTRAL_MODEL", |
| 528 | "mistral-large-latest", |
| 529 | true, |
| 530 | max_tokens, |
| 531 | ), |
| 532 | "cohere" => pcfg |
| 533 | "cohere", |
| 534 | "COHERE_API_KEY", |
| 535 | "COHERE_BASE_URL", |
| 536 | "https://api.cohere.com/v1", |
| 537 | "COHERE_MODEL", |
| 538 | "command-r-plus", |
| 539 | true, |
| 540 | max_tokens, |
| 541 | ), |
| 542 | "fireworks" => pcfg |
| 543 | "fireworks", |
| 544 | "FIREWORKS_API_KEY", |
| 545 | "FIREWORKS_BASE_URL", |
| 546 | "https://api.fireworks.ai/inference/v1", |
| 547 | "FIREWORKS_MODEL", |
| 548 | "accounts/fireworks/models/llama-v3p3-70b-instruct", |
| 549 | true, |
| 550 | max_tokens, |
| 551 | ), |
| 552 | "cerebras" => pcfg |
| 553 | "cerebras", |
| 554 | "CEREBRAS_API_KEY", |
| 555 | "CEREBRAS_BASE_URL", |
| 556 | "https://api.cerebras.ai/v1", |
| 557 | "CEREBRAS_MODEL", |
| 558 | "llama-3.3-70b", |
| 559 | true, |
| 560 | max_tokens, |
| 561 | ), |
| 562 | "xai" | "x-ai" |
| 563 | "xai", |
| 564 | "XAI_API_KEY", |
| 565 | "XAI_BASE_URL", |
| 566 | "https://api.x.ai/v1", |
| 567 | "XAI_MODEL", |
| 568 | "grok-2", |
| 569 | true, |
| 570 | max_tokens, |
| 571 | ), |
| 572 | "together" => pcfg |
| 573 | "together", |
| 574 | "TOGETHER_API_KEY", |
| 575 | "TOGETHER_BASE_URL", |
| 576 | "https://api.together.xyz/v1", |
| 577 | "TOGETHER_MODEL", |
| 578 | "meta-llama/Llama-3.3-70B-Instruct-Turbo", |
| 579 | true, |
| 580 | max_tokens, |
| 581 | ), |
| 582 | "perplexity" => pcfg |
| 583 | "perplexity", |
| 584 | "PERPLEXITY_API_KEY", |
| 585 | "PERPLEXITY_BASE_URL", |
| 586 | "https://api.perplexity.ai", |
| 587 | "PERPLEXITY_MODEL", |
| 588 | "sonar-pro", |
| 589 | true, |
| 590 | max_tokens, |
| 591 | ), |
| 592 | "deepseek" => pcfg |
| 593 | "deepseek", |
| 594 | "DEEPSEEK_API_KEY", |
| 595 | "DEEPSEEK_BASE_URL", |
| 596 | "https://api.deepseek.com/v1", |
| 597 | "DEEPSEEK_MODEL", |
| 598 | "deepseek-chat", |
| 599 | true, |
| 600 | max_tokens, |
| 601 | ), |
| 602 | "qwen" => { |
| 603 | let mut c |
| 604 | "qwen", |
| 605 | "DASHSCOPE_API_KEY", |
| 606 | "QWEN_BASE_URL", |
| 607 | "https://dashscope.aliyuncs.com/compatible-mode/v1", |
| 608 | "QWEN_MODEL", |
| 609 | "qwen-plus", |
| 610 | true, |
| 611 | max_tokens, |
| 612 | ); |
| 613 | c.api_key = env |
| 614 | c |
| 615 | } |
| 616 | "sambanova" => pcfg |
| 617 | "sambanova", |
| 618 | "SAMBANOVA_API_KEY", |
| 619 | "SAMBANOVA_BASE_URL", |
| 620 | "https://api.sambanova.ai/v1", |
| 621 | "SAMBANOVA_MODEL", |
| 622 | "Meta-Llama-3.3-70B-Instruct", |
| 623 | true, |
| 624 | max_tokens, |
| 625 | ), |
| 626 | "replicate" => pcfg |
| 627 | "replicate", |
| 628 | "REPLICATE_API_TOKEN", |
| 629 | "REPLICATE_BASE_URL", |
| 630 | "https://api.replicate.com/v1", |
| 631 | "REPLICATE_MODEL", |
| 632 | "meta/meta-llama-3-70b-instruct", |
| 633 | true, |
| 634 | max_tokens, |
| 635 | ), |
| 636 | "openrouter" => pcfg |
| 637 | "openrouter", |
| 638 | "OPENROUTER_API_KEY", |
| 639 | "OPENROUTER_BASE_URL", |
| 640 | "https://openrouter.ai/api/v1", |
| 641 | "OPENROUTER_MODEL", |
| 642 | "anthropic/claude-sonnet-4", |
| 643 | true, |
| 644 | max_tokens, |
| 645 | ), |
| 646 | "hf" | "huggingface" |
| 647 | let mut c |
| 648 | "huggingface", |
| 649 | "HF_API_TOKEN", |
| 650 | "HF_BASE_URL", |
| 651 | "https://api-inference.huggingface.co/v1", |
| 652 | "HF_MODEL", |
| 653 | "meta-llama/Llama-3.3-70B-Instruct", |
| 654 | true, |
| 655 | max_tokens, |
| 656 | ); |
| 657 | c.api_key = env |
| 658 | c |
| 659 | } |
| 660 | "cloudflare" => { |
| 661 | let account = |
| 662 | let default_base = |
| 663 | String::new() |
| 664 | } else { |
| 665 | format!("https://api.cloudflare.com/client/v4/accounts/{account |
| 666 | }; |
| 667 | let mut c |
| 668 | "cloudflare", |
| 669 | "CLOUDFLARE_API_TOKEN", |
| 670 | "CLOUDFLARE_BASE_URL", |
| 671 | "", |
| 672 | "CLOUDFLARE_MODEL", |
| 673 | "@cf/meta/llama-3.1-8b-instruct", |
| 674 | true, |
| 675 | max_tokens, |
| 676 | ); |
| 677 | c.base_url = env |
| 678 | c.api_key = env |
| 679 | c |
| 680 | } |
| 681 | "ollama" => pcfg |
| 682 | "ollama", |
| 683 | "OLLAMA_API_KEY", |
| 684 | "OLLAMA_BASE_URL", |
| 685 | "http://localhost:11434/v1", |
| 686 | "OLLAMA_MODEL", |
| 687 | "llama3.2", |
| 688 | false, |
| 689 | max_tokens, |
| 690 | ), |
| 691 | "lmstudio" => pcfg |
| 692 | "lmstudio", |
| 693 | "LMSTUDIO_API_KEY", |
| 694 | "LMSTUDIO_BASE_URL", |
| 695 | "http://localhost:1234/v1", |
| 696 | "LMSTUDIO_MODEL", |
| 697 | "", |
| 698 | false, |
| 699 | max_tokens, |
| 700 | ), |
| 701 | "compatible" => { |
| 702 | let mut c |
| 703 | "compatible", |
| 704 | "COMPATIBLE_API_KEY", |
| 705 | "COMPATIBLE_BASE_URL", |
| 706 | "https://api.openai.com/v1", |
| 707 | "COMPATIBLE_MODEL", |
| 708 | "gpt-4o-mini", |
| 709 | false, |
| 710 | max_tokens, |
| 711 | ); |
| 712 | c.base_url = env |
| 713 | .or_else(|| env |
| 714 | .unwrap_or_else(|| "https://api.openai.com/v1 |
| 715 | c.api_key = env |
| 716 | c.default_model = env |
| 717 | .or_else(|| env |
| 718 | .unwrap_or_else(|| "gpt-4o-mini |
| 719 | c |
| 720 | } |
| 721 | other => { |
| 722 | let Some( |
| 723 | bail!( |
| 724 | "Unknown provider '{other}'. Run `wynba providers` to list supported providers." |
| 725 | ) |
| 726 | }; |
| 727 | from_row(row, max_tokens |
| 728 | } |
| 729 | }; |
| 730 | Ok(cfg) |
| 731 | } |
| 732 | |
| 733 | fn from_row(row: |
| 734 | let key_env = |
| 735 | let tag = |
| 736 | let base_env = |
| 737 | let model_env = |
| 738 | if row.base_url.is_empty |
| 739 | bail!( |
| 740 | "No base URL for provider '{}'. Set {} or use `wynba connect`.", |
| 741 | row.name, |
| 742 | base_env |
| 743 | ); |
| 744 | } |
| 745 | let cfg = |
| 746 | row.name, |
| 747 | key_env, |
| 748 | &base_env, |
| 749 | row.base_url, |
| 750 | &model_env, |
| 751 | row.default_model, |
| 752 | row.requires_key, |
| 753 | max_tokens, |
| 754 | ) |
| 755 | .with_format(row.format |
| 756 | Ok(cfg) |
| 757 | } |
| 758 | |
| 759 | pub fn apply_stored(cfg |
| 760 | let Some( |
| 761 | if let Some |
| 762 | && !k.is_empty |
| 763 | { |
| 764 | cfg.api_key = Some |
| 765 | } |
| 766 | if let Some |
| 767 | && !b.is_empty |
| 768 | { |
| 769 | cfg.base_url = b |
| 770 | if cfg.name == |
| 771 | cfg.url_override = Some |
| 772 | } |
| 773 | } |
| 774 | if let Some |
| 775 | && !m.is_empty |
| 776 | { |
| 777 | cfg.default_model = m |
| 778 | } |
| 779 | if let Some |
| 780 | && !s.is_empty |
| 781 | { |
| 782 | cfg.aws_secret_key = Some |
| 783 | } |
| 784 | if let Some |
| 785 | && !r.is_empty |
| 786 | { |
| 787 | cfg.aws_region = r |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | /// Build a provider config from a stored `/connect` entry. This lets a |
| 792 | /// provider that is configured locally but not a built-in provider (or known |
| 793 | /// only by its stored name) still be resolved by name. |
| 794 | pub fn provider_from_stored(name |
| 795 | let get = |
| 796 | ProviderConfig { |
| 797 | name: name.to_string |
| 798 | api_format: ApiFormat |
| 799 | base_url: get(" |
| 800 | api_key: { |
| 801 | let k = |
| 802 | if k.is_empty() |
| 803 | }, |
| 804 | default_model: { |
| 805 | let m = |
| 806 | if m.is_empty() |
| 807 | "gpt-4o-mini".to_string() |
| 808 | } else { |
| 809 | m |
| 810 | } |
| 811 | }, |
| 812 | max_tokens: 2048, |
| 813 | requires_key: false, |
| 814 | url_override: None |
| 815 | azure_auth: false, |
| 816 | key_in_url: false, |
| 817 | aws_region: get(" |
| 818 | aws_secret_key: { |
| 819 | let k = |
| 820 | if k.is_empty() |
| 821 | }, |
| 822 | aws_session_token: None |
| 823 | effort: None |
| 824 | context_window: 131_072, |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | pub fn print_providers(conn |
| 829 | let stored = |
| 830 | .and_then(|c| |
| 831 | .unwrap_or_default(); |
| 832 | println!("{:<18} |
| 833 | println!("{}", |
| 834 | for m in provider_metas |
| 835 | let mark = |
| 836 | "✓" |
| 837 | } else { |
| 838 | " " |
| 839 | }; |
| 840 | println!("{mark} |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | fn get_json(cfg: |
| 845 | let mut req |
| 846 | if let Some |
| 847 | if cfg.api_format == |
| 848 | req = req |
| 849 | .set("x-api-key", |
| 850 | .set("anthropic-version", |
| 851 | } else if cfg |
| 852 | req = req. |
| 853 | } else { |
| 854 | req = req. |
| 855 | } |
| 856 | } |
| 857 | let resp = |
| 858 | Ok(r) |
| 859 | Err(ureq:: |
| 860 | let body = |
| 861 | bail!("HTTP {code |
| 862 | } |
| 863 | Err(e) |
| 864 | }; |
| 865 | resp.into_json().context |
| 866 | } |
| 867 | |
| 868 | /// List available models for a provider. Prefers the provider's live |
| 869 | /// `/models` endpoint; falls back to the embedded registry model list. |
| 870 | pub fn list_models(cfg |
| 871 | let base = |
| 872 | let live: Result |
| 873 | bail!("no credentials configured for provider '{}' |
| 874 | } else if cfg |
| 875 | let base = |
| 876 | let url = |
| 877 | let v = |
| 878 | Ok(v[ |
| 879 | .as_array() |
| 880 | .map(|arr| |
| 881 | arr.iter() |
| 882 | .filter_map(|m| |
| 883 | m["name"] |
| 884 | .as_str() |
| 885 | .map(|s| |
| 886 | }) |
| 887 | .collect() |
| 888 | }) |
| 889 | .unwrap_or_default()) |
| 890 | } else if cfg |
| 891 | let url = |
| 892 | let v = |
| 893 | Ok(v[ |
| 894 | .as_array() |
| 895 | .map(|arr| |
| 896 | arr.iter() |
| 897 | .filter_map(|m| |
| 898 | .collect() |
| 899 | }) |
| 900 | .unwrap_or_default()) |
| 901 | } else if cfg |
| 902 | let key = |
| 903 | let url = |
| 904 | let v = |
| 905 | Ok(v[ |
| 906 | .as_array() |
| 907 | .map(|arr| |
| 908 | arr.iter() |
| 909 | .filter_map(|m| |
| 910 | m["name"] |
| 911 | .as_str() |
| 912 | .map(|s| |
| 913 | }) |
| 914 | .collect() |
| 915 | }) |
| 916 | .unwrap_or_default()) |
| 917 | } else { |
| 918 | bail!("no model listing endpoint for {}" |
| 919 | }; |
| 920 | if let Ok |
| 921 | && !list.is_empty |
| 922 | { |
| 923 | return Ok(list |
| 924 | } |
| 925 | let embedded = |
| 926 | .iter() |
| 927 | .find(|(n |
| 928 | .map(|(_ |
| 929 | .unwrap_or_default(); |
| 930 | if !embedded.is_empty |
| 931 | return Ok(embedded |
| 932 | } |
| 933 | Ok(vec! |
| 934 | } |
| 935 | |
| 936 | pub fn embedded_models(name |
| 937 | providers_data::MODEL_LISTS |
| 938 | .iter() |
| 939 | .find(|(n |
| 940 | .map(|(_ |
| 941 | .unwrap_or_default() |
| 942 | } |
| 943 | |
| 944 | /// Latest live model list fetched for a provider (best-effort, refreshed in |
| 945 | /// the background so the picker never blocks on the network). |
| 946 | struct ModelCache { |
| 947 | provider: String |
| 948 | models: Vec |
| 949 | } |
| 950 | |
| 951 | static MODEL_CACHE: Mutex |
| 952 | |
| 953 | fn cached_models(provider: |
| 954 | MODEL_CACHE |
| 955 | .lock() |
| 956 | .unwrap() |
| 957 | .as_ref() |
| 958 | .filter(|c| |
| 959 | .map(|c| |
| 960 | } |
| 961 | |
| 962 | /// Model list for the interactive picker. Returns immediately (embedded |
| 963 | /// registry list, or the default model) and kicks off a background fetch of |
| 964 | /// the provider's live `/models` endpoint so later calls get the fresher |
| 965 | /// list. The dropdown never waits on the network. |
| 966 | pub fn picker_models(cfg |
| 967 | if let Some |
| 968 | return list; |
| 969 | } |
| 970 | let embedded = |
| 971 | let fallback = |
| 972 | vec![cfg.default_model |
| 973 | } else { |
| 974 | embedded |
| 975 | }; |
| 976 | let provider = |
| 977 | let cfg = |
| 978 | std::thread::spawn |
| 979 | match list_models(&cfg |
| 980 | Ok(list) |
| 981 | if let Ok |
| 982 | events::info( |
| 983 | "cache.model.fill", |
| 984 | &[ |
| 985 | ("provider", &provider |
| 986 | ("count", &list |
| 987 | ], |
| 988 | ); |
| 989 | *cache = Some |
| 990 | provider, |
| 991 | models: list, |
| 992 | }); |
| 993 | } |
| 994 | } |
| 995 | Ok(_) |
| 996 | "cache.model.empty", |
| 997 | &[("provider", &provider |
| 998 | ), |
| 999 | Err(e) |
| 1000 | "cache.model.refresh_failed", |
| 1001 | &[("provider", &provider |
| 1002 | ), |
| 1003 | } |
| 1004 | }); |
| 1005 | fallback |
| 1006 | } |
| 1007 | |
| 1008 | pub fn chat( |
| 1009 | cfg: &ProviderConfig |
| 1010 | model: &str |
| 1011 | system: &str |
| 1012 | messages: &[LlmMessage |
| 1013 | tools: &[ToolDef |
| 1014 | on_delta: Option |
| 1015 | ) -> Result<LlmResponse |
| 1016 | if cfg.requires_key && |
| 1017 | bail!( |
| 1018 | "Missing credentials for provider '{}'. Run `/connect` or set the matching env var (see `wynba providers`).", |
| 1019 | cfg.name |
| 1020 | ); |
| 1021 | } |
| 1022 | match cfg.api_format { |
| 1023 | ApiFormat::Compatible |
| 1024 | ApiFormat::Anthropic |
| 1025 | ApiFormat::Gemini |
| 1026 | ApiFormat::Bedrock |
| 1027 | } |
| 1028 | } |
| 1029 | |
| 1030 | const MAX_RETRIES: usize |
| 1031 | |
| 1032 | /// Per-socket read timeout for LLM HTTP requests. Applied per read operation, |
| 1033 | /// so a steadily-streaming response is unaffected, but a provider that stops |
| 1034 | /// sending data un-sticks the agent after this long instead of hanging forever. |
| 1035 | const LLM_TIMEOUT: Duration |
| 1036 | |
| 1037 | /// Pi-style retry of transient LLM failures: HTTP 429/5xx, "overloaded" / |
| 1038 | /// rate-limit responses, and network/timeout errors. Backoff doubles |
| 1039 | /// (2s, 4s, 8s). `on_retry` is called before each wait with |
| 1040 | /// (attempt, max, wait_ms); setting `cancel` during a wait aborts the retry. |
| 1041 | /// Calls that already streamed deltas are never retried (their output is |
| 1042 | /// already visible), and auth/validation/context errors never retry. |
| 1043 | #[allow(clippy:: |
| 1044 | pub fn chat_with_retries( |
| 1045 | cfg: &ProviderConfig |
| 1046 | model: &str |
| 1047 | system: &str |
| 1048 | messages: &[LlmMessage |
| 1049 | tools: &[ToolDef |
| 1050 | mut on_delta: Option |
| 1051 | mut on_retry: Option |
| 1052 | cancel: &AtomicBool |
| 1053 | ) -> Result<LlmResponse |
| 1054 | for attempt in 0 |
| 1055 | if cancel.load( |
| 1056 | bail!("cancelled"); |
| 1057 | } |
| 1058 | let mut streamed |
| 1059 | let call = |
| 1060 | let mut wrapped |
| 1061 | streamed = true; |
| 1062 | real(chunk); |
| 1063 | }; |
| 1064 | chat(cfg, model |
| 1065 | } else { |
| 1066 | chat(cfg, model |
| 1067 | }; |
| 1068 | let call = |
| 1069 | // Usage-aware guards (pi's `isContextOverflow` Case 2 and |
| 1070 | // `isRecoverableLength`): a provider that reports `stop` while the |
| 1071 | // input filled the window, or `length` with zero output tokens, has |
| 1072 | // exhausted the context. Surface this as an overflow/length error |
| 1073 | // so the agent auto-compacts and retries once — these are checked |
| 1074 | // before the generic empty-response error below. |
| 1075 | Ok(r) |
| 1076 | "Context overflow detected: input tokens ({}) filled the {}-token context window", |
| 1077 | r.usage |
| 1078 | .as_ref() |
| 1079 | .map(|u| |
| 1080 | .unwrap_or(0), |
| 1081 | cfg.context_window |
| 1082 | )), |
| 1083 | Ok(r) |
| 1084 | "finish_reason=length with zero output tokens; context exhausted" |
| 1085 | )), |
| 1086 | Ok(r) |
| 1087 | // A 200 with a stream that closed before any data (or a body |
| 1088 | // with no content and no tool calls) is not a model answer — |
| 1089 | // it's a silent network drop. Fail so the retry loop kicks in |
| 1090 | // instead of persisting an empty assistant message and ending |
| 1091 | // the turn with nothing. |
| 1092 | let e = |
| 1093 | "empty response from provider (no content, no tool calls)" |
| 1094 | ); |
| 1095 | if attempt == MAX_RETRIES |
| 1096 | events::error( |
| 1097 | "llm.empty_response", |
| 1098 | &[ |
| 1099 | ("provider", &cfg |
| 1100 | ("model", model |
| 1101 | ("attempt", &(attempt |
| 1102 | ], |
| 1103 | ); |
| 1104 | } |
| 1105 | Err(e) |
| 1106 | } |
| 1107 | other => other, |
| 1108 | }; |
| 1109 | match call { |
| 1110 | Ok(r) |
| 1111 | Err(e) |
| 1112 | events::error( |
| 1113 | "llm.stream_interrupted", |
| 1114 | &[ |
| 1115 | ("provider", &cfg |
| 1116 | ("model", model |
| 1117 | ("error", &format! |
| 1118 | ], |
| 1119 | ); |
| 1120 | return Err(e |
| 1121 | } |
| 1122 | Err(e) |
| 1123 | let wait_ms = |
| 1124 | events::warn( |
| 1125 | "llm.retry", |
| 1126 | &[ |
| 1127 | ("provider", &cfg |
| 1128 | ("model", model |
| 1129 | ("attempt", &(attempt |
| 1130 | ("max_attempts", &(MAX_RETRIES |
| 1131 | ("wait_ms", &wait_ms |
| 1132 | ("error", &format! |
| 1133 | ], |
| 1134 | ); |
| 1135 | if let Some |
| 1136 | f(attempt + |
| 1137 | } |
| 1138 | sleep_backoff(wait_ms, cancel |
| 1139 | } |
| 1140 | Err(e) |
| 1141 | events::error( |
| 1142 | "llm.failed", |
| 1143 | &[ |
| 1144 | ("provider", &cfg |
| 1145 | ("model", model |
| 1146 | ("attempt", &(attempt |
| 1147 | ("error", &format! |
| 1148 | ], |
| 1149 | ); |
| 1150 | return Err(e |
| 1151 | } |
| 1152 | } |
| 1153 | } |
| 1154 | unreachable!("retry loop always returns") |
| 1155 | } |
| 1156 | |
| 1157 | fn is_transient_err(err: |
| 1158 | let msg = |
| 1159 | if let Some |
| 1160 | && let Ok |
| 1161 | .chars() |
| 1162 | .take_while(|c| |
| 1163 | .collect::<String |
| 1164 | .parse::<u16 |
| 1165 | && (code == |
| 1166 | { |
| 1167 | return true; |
| 1168 | } |
| 1169 | if err.chain() |
| 1170 | matches!( |
| 1171 | c.downcast_ref::<ureq |
| 1172 | Some(ureq:: |
| 1173 | ) |
| 1174 | }) { |
| 1175 | return true; |
| 1176 | } |
| 1177 | let lower = |
| 1178 | [ |
| 1179 | "overloaded", |
| 1180 | "overloaded_error", |
| 1181 | "rate limit", |
| 1182 | "too many requests", |
| 1183 | "temporarily unavailable", |
| 1184 | "try again later", |
| 1185 | "server busy", |
| 1186 | "under maintenance", |
| 1187 | "upstream error", |
| 1188 | "connection reset", |
| 1189 | "empty response", |
| 1190 | ] |
| 1191 | .iter() |
| 1192 | .any(|pat| |
| 1193 | } |
| 1194 | |
| 1195 | /// True when a provider rejected the request because the context is too big |
| 1196 | /// for its window — the failure mode the agent recovers from by auto-compacting |
| 1197 | /// (mirrors pi's `isContextOverflow`). Message-pattern based because providers |
| 1198 | /// surface it as HTTP 400/429 bodies with wildly different shapes ("This |
| 1199 | /// model's maximum context length is …", Anthropic `request_too_large`, |
| 1200 | /// Gemini "The input token count … exceeds …"). Deliberately does NOT match |
| 1201 | /// the finish_reason=length guard below (an *output*-budget stop, not a |
| 1202 | /// context problem — that one needs a higher MAX_TOKENS instead). |
| 1203 | pub fn is_context_overflow(err |
| 1204 | let msg = |
| 1205 | let lower = |
| 1206 | [ |
| 1207 | "context length", |
| 1208 | "context window", |
| 1209 | "context overflow", |
| 1210 | "context_limit", |
| 1211 | "context_exceed", |
| 1212 | "exceeds the context", |
| 1213 | "exceeded the context", |
| 1214 | "maximum context", |
| 1215 | "max context", |
| 1216 | "model's maximum", |
| 1217 | "reduce the length", |
| 1218 | "prompt is too long", |
| 1219 | "request_too_large", |
| 1220 | "input is too long", |
| 1221 | "input token count", |
| 1222 | "token count exceeds", |
| 1223 | "too many tokens", |
| 1224 | "token_limit", |
| 1225 | "maximum number of tokens", |
| 1226 | "conversation is too long", |
| 1227 | "history is too long", |
| 1228 | "messages is too long", |
| 1229 | "total length of messages", |
| 1230 | ] |
| 1231 | .iter() |
| 1232 | .any(|pat| |
| 1233 | } |
| 1234 | |
| 1235 | /// A length stop is recoverable when the model was cut off below its intended |
| 1236 | /// output limit (pi's `isRecoverableLength`: `stopReason === "length"` with |
| 1237 | /// `usage.output < desiredMaxOutput`). Our provider-side guard bails with |
| 1238 | /// `finish_reason=length` when the model returned zero content — output 0 is |
| 1239 | /// always below the requested budget, so the agent compacts the context and |
| 1240 | /// retries once (MiMo-style: the input filled the window, leaving no room). |
| 1241 | pub fn is_recoverable_length(err |
| 1242 | format!("{err:#} |
| 1243 | } |
| 1244 | |
| 1245 | /// True when the provider stopped normally but usage shows the input filled |
| 1246 | /// the context window (pi's `isContextOverflow` Case 2: `usage.input + |
| 1247 | /// usage.cacheRead > contextWindow` on a `stop` response). The window check is |
| 1248 | /// scaled to 99% so rounded/sampled usage counts still trip it. |
| 1249 | fn context_overflowed(r: |
| 1250 | let Some( |
| 1251 | return false; |
| 1252 | }; |
| 1253 | let input_tokens = |
| 1254 | r.finish_reason.as_deref() |
| 1255 | && input_tokens >= context_window |
| 1256 | } |
| 1257 | |
| 1258 | /// True when the model hit its output cap with nothing to show for it — |
| 1259 | /// the request left no room for output (pi's `isRecoverableLength`). |
| 1260 | fn recovered_length(r: |
| 1261 | let Some( |
| 1262 | return false; |
| 1263 | }; |
| 1264 | r.finish_reason.as_deref() |
| 1265 | } |
| 1266 | |
| 1267 | fn sleep_backoff(wait_ms: |
| 1268 | let mut slept |
| 1269 | while slept < wait_ms |
| 1270 | if cancel.load( |
| 1271 | bail!("Retry cancelled"); |
| 1272 | } |
| 1273 | std::thread::sleep |
| 1274 | slept += 100; |
| 1275 | } |
| 1276 | Ok(()) |
| 1277 | } |
| 1278 | |
| 1279 | fn post_json(cfg: |
| 1280 | let mut req |
| 1281 | .timeout(LLM_TIMEOUT) |
| 1282 | .set("Content-Type", |
| 1283 | if let Some |
| 1284 | if cfg.api_format == |
| 1285 | req = req |
| 1286 | .set("x-api-key", |
| 1287 | .set("anthropic-version", |
| 1288 | } else if cfg |
| 1289 | req = req. |
| 1290 | } else { |
| 1291 | req = req. |
| 1292 | } |
| 1293 | } |
| 1294 | let resp = |
| 1295 | Ok(r) |
| 1296 | Err(ureq:: |
| 1297 | let body = |
| 1298 | bail!("HTTP {code |
| 1299 | } |
| 1300 | Err(e) |
| 1301 | }; |
| 1302 | let v: Value |
| 1303 | if let Some |
| 1304 | bail!("API error: {err |
| 1305 | } |
| 1306 | Ok(v) |
| 1307 | } |
| 1308 | |
| 1309 | fn extract_text(v: |
| 1310 | match v { |
| 1311 | Value::String( |
| 1312 | Value::Array( |
| 1313 | let mut out |
| 1314 | for item in arr |
| 1315 | if let Some |
| 1316 | out.push_str(t |
| 1317 | } else if let |
| 1318 | out.push_str(s |
| 1319 | } |
| 1320 | } |
| 1321 | Some(out) |
| 1322 | } |
| 1323 | Value::Null |
| 1324 | _ => None |
| 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | fn to_openai_messages(messages: |
| 1329 | let mut out |
| 1330 | for m in messages |
| 1331 | match m.role.as_str |
| 1332 | "system" => out |
| 1333 | .push(json! |
| 1334 | "user" => { |
| 1335 | if m.images.is_empty |
| 1336 | out.push( |
| 1337 | json!({"role": |
| 1338 | ); |
| 1339 | } else { |
| 1340 | let mut parts |
| 1341 | if let Some |
| 1342 | && !c.is_empty |
| 1343 | { |
| 1344 | parts.push(json! |
| 1345 | } |
| 1346 | parts.extend(image_openai_parts |
| 1347 | out.push(json! |
| 1348 | } |
| 1349 | } |
| 1350 | "assistant" => { |
| 1351 | let mut msg |
| 1352 | // DeepSeek-style thinking mode requires the previous turn's |
| 1353 | // `reasoning_content` to be echoed back; without it the proxy |
| 1354 | // rejects the request (HTTP 400 / empty stream). |
| 1355 | if let Some |
| 1356 | msg["reasoning_content"] |
| 1357 | } |
| 1358 | if !m.tool_calls. |
| 1359 | let tcs: Vec |
| 1360 | .tool_calls |
| 1361 | .iter() |
| 1362 | .map(|tc| |
| 1363 | json!({ |
| 1364 | "id": tc. |
| 1365 | "type": "function", |
| 1366 | "function": {"name" |
| 1367 | }) |
| 1368 | }) |
| 1369 | .collect(); |
| 1370 | msg["tool_calls"] |
| 1371 | } |
| 1372 | out.push(msg |
| 1373 | } |
| 1374 | "tool" => out |
| 1375 | "role": "tool", |
| 1376 | "tool_call_id": m. |
| 1377 | "content": m. |
| 1378 | })), |
| 1379 | _ => {} |
| 1380 | } |
| 1381 | } |
| 1382 | out |
| 1383 | } |
| 1384 | |
| 1385 | /// Build the OpenAI-compatible chat/completions request body. Extracted so |
| 1386 | /// tests can assert the payload (effort → `reasoning_effort`) without a server. |
| 1387 | fn compatible_request_body( |
| 1388 | cfg: &ProviderConfig |
| 1389 | model: &str |
| 1390 | messages: &[LlmMessage |
| 1391 | tools: &[ToolDef |
| 1392 | streaming: bool |
| 1393 | ) -> Value { |
| 1394 | let mut body |
| 1395 | "model": model, |
| 1396 | "messages": to_openai_messages( |
| 1397 | "max_tokens": cfg. |
| 1398 | "stream": streaming, |
| 1399 | }); |
| 1400 | if !tools.is_empty |
| 1401 | body["tools"] |
| 1402 | tools |
| 1403 | .iter() |
| 1404 | .map(|t| |
| 1405 | "type": "function", |
| 1406 | "function": {"name" |
| 1407 | })) |
| 1408 | .collect::<Vec |
| 1409 | ); |
| 1410 | } |
| 1411 | if let Some |
| 1412 | body["reasoning_effort"] |
| 1413 | } |
| 1414 | body |
| 1415 | } |
| 1416 | |
| 1417 | fn chat_compatible( |
| 1418 | cfg: &ProviderConfig |
| 1419 | model: &str |
| 1420 | _system: &str |
| 1421 | messages: &[LlmMessage |
| 1422 | tools: &[ToolDef |
| 1423 | on_delta: Option |
| 1424 | ) -> Result<LlmResponse |
| 1425 | let url = |
| 1426 | .url_override |
| 1427 | .clone() |
| 1428 | .unwrap_or_else(|| format! |
| 1429 | let streaming = |
| 1430 | let body = |
| 1431 | if streaming { |
| 1432 | let on_delta = |
| 1433 | return stream_compatible(cfg, |
| 1434 | } |
| 1435 | let resp = |
| 1436 | let msg = |
| 1437 | .pointer("/choices/0/message") |
| 1438 | .context("no choices[0].message in response") |
| 1439 | .clone(); |
| 1440 | let content = |
| 1441 | let reasoning = |
| 1442 | .get("reasoning_content") |
| 1443 | .and_then(|v| |
| 1444 | .map(|s| |
| 1445 | let mut tool_calls |
| 1446 | if let Some |
| 1447 | for tc in arr |
| 1448 | let id = |
| 1449 | .get("id") |
| 1450 | .and_then(|v| |
| 1451 | .unwrap_or("") |
| 1452 | .to_string(); |
| 1453 | let name = |
| 1454 | .pointer("/function/name") |
| 1455 | .and_then(|v| |
| 1456 | .unwrap_or("") |
| 1457 | .to_string(); |
| 1458 | let arguments = |
| 1459 | Some(Value |
| 1460 | Some(v) |
| 1461 | None => Value |
| 1462 | }; |
| 1463 | tool_calls.push(ToolCall |
| 1464 | id, |
| 1465 | name, |
| 1466 | arguments, |
| 1467 | }); |
| 1468 | } |
| 1469 | } |
| 1470 | let finish_reason = |
| 1471 | .pointer("/choices/0/finish_reason") |
| 1472 | .and_then(|v| |
| 1473 | .filter(|s| |
| 1474 | .map(|s| |
| 1475 | let usage = |
| 1476 | Ok(LlmResponse |
| 1477 | content, |
| 1478 | reasoning, |
| 1479 | tool_calls, |
| 1480 | finish_reason, |
| 1481 | usage, |
| 1482 | }) |
| 1483 | } |
| 1484 | |
| 1485 | fn stream_compatible( |
| 1486 | cfg: &ProviderConfig |
| 1487 | url: &str |
| 1488 | body: &Value |
| 1489 | on_delta: &mut |
| 1490 | ) -> Result<LlmResponse |
| 1491 | let mut req |
| 1492 | .timeout(LLM_TIMEOUT) |
| 1493 | .set("Content-Type", |
| 1494 | if let Some |
| 1495 | if cfg.api_format == |
| 1496 | req = req |
| 1497 | .set("x-api-key", |
| 1498 | .set("anthropic-version", |
| 1499 | } else if cfg |
| 1500 | req = req. |
| 1501 | } else { |
| 1502 | req = req. |
| 1503 | } |
| 1504 | } |
| 1505 | let resp = |
| 1506 | Ok(r) |
| 1507 | Err(ureq:: |
| 1508 | let body = |
| 1509 | bail!("HTTP {code |
| 1510 | } |
| 1511 | Err(e) |
| 1512 | }; |
| 1513 | let mut reader |
| 1514 | let mut buf |
| 1515 | let mut content |
| 1516 | let mut reasoning |
| 1517 | let mut finish_reason |
| 1518 | let mut usage |
| 1519 | let mut slots |
| 1520 | let mut order |
| 1521 | loop { |
| 1522 | buf.clear(); |
| 1523 | let n = |
| 1524 | if n == 0 |
| 1525 | break; |
| 1526 | } |
| 1527 | let line = |
| 1528 | let line = |
| 1529 | if line.is_empty() |
| 1530 | continue; |
| 1531 | } |
| 1532 | let data = |
| 1533 | if data.is_empty() |
| 1534 | continue; |
| 1535 | } |
| 1536 | let v: Value |
| 1537 | Ok(v) |
| 1538 | Err(_) |
| 1539 | }; |
| 1540 | if let Some |
| 1541 | .pointer("/choices/0/delta/content") |
| 1542 | .and_then(|x| |
| 1543 | { |
| 1544 | content.push_str(t |
| 1545 | on_delta(t); |
| 1546 | } |
| 1547 | // DeepSeek-style thinking mode streams the chain of thought here; |
| 1548 | // keep it verbatim so it can be passed back on the next request. |
| 1549 | if let Some |
| 1550 | .pointer("/choices/0/delta/reasoning_content") |
| 1551 | .and_then(|x| |
| 1552 | && !t.is_empty |
| 1553 | { |
| 1554 | reasoning.push_str(t |
| 1555 | } |
| 1556 | if let Some |
| 1557 | .pointer("/choices/0/finish_reason") |
| 1558 | .and_then(|x| |
| 1559 | && !fr.is_empty |
| 1560 | { |
| 1561 | finish_reason = Some |
| 1562 | } |
| 1563 | // OpenAI-compatible providers attach `usage` to the final chunk before |
| 1564 | // [DONE]; keep the last one seen (z.ai sends a middle chunk too). |
| 1565 | if let Some |
| 1566 | usage = Some |
| 1567 | } |
| 1568 | if let Some |
| 1569 | .pointer("/choices/0/delta/tool_calls") |
| 1570 | .and_then(|x| |
| 1571 | { |
| 1572 | for tc in arr |
| 1573 | let index = |
| 1574 | let slot = |
| 1575 | order.push(index |
| 1576 | (String::new(), |
| 1577 | }); |
| 1578 | if let Some |
| 1579 | && !id.is_empty |
| 1580 | { |
| 1581 | slot.0.push_str( |
| 1582 | } |
| 1583 | if let Some |
| 1584 | && !name.is_empty |
| 1585 | { |
| 1586 | slot.1.push_str( |
| 1587 | } |
| 1588 | if let Some |
| 1589 | slot.2.push_str( |
| 1590 | } |
| 1591 | } |
| 1592 | } |
| 1593 | } |
| 1594 | let mut tool_calls |
| 1595 | for index in order |
| 1596 | let (id, |
| 1597 | if name.is_empty() |
| 1598 | continue; |
| 1599 | } |
| 1600 | tool_calls.push(ToolCall |
| 1601 | id, |
| 1602 | name, |
| 1603 | arguments: serde_json::from_str |
| 1604 | }); |
| 1605 | } |
| 1606 | if content.is_empty() |
| 1607 | // The model burned its whole output budget on thinking and was cut off |
| 1608 | // before producing a single answer byte. Retrying can only repeat it, |
| 1609 | // so fail loudly with the fix. |
| 1610 | bail!( |
| 1611 | "provider hit its output token limit (finish_reason=length) with no content — \ |
| 1612 | the model used the entire {} output budget on reasoning. Raise MAX_TOKENS \ |
| 1613 | (default 16384) or lower thinking effort with /effort so the answer fits.", |
| 1614 | cfg.max_tokens |
| 1615 | ); |
| 1616 | } |
| 1617 | Ok(LlmResponse |
| 1618 | content: if content |
| 1619 | None |
| 1620 | } else { |
| 1621 | Some(content) |
| 1622 | }, |
| 1623 | reasoning: if reasoning |
| 1624 | None |
| 1625 | } else { |
| 1626 | Some(reasoning) |
| 1627 | }, |
| 1628 | tool_calls, |
| 1629 | finish_reason, |
| 1630 | usage, |
| 1631 | }) |
| 1632 | } |
| 1633 | |
| 1634 | fn push_blocks(out: |
| 1635 | if let Some |
| 1636 | && last["role" |
| 1637 | && let Some |
| 1638 | { |
| 1639 | for b in blocks |
| 1640 | arr.push(b |
| 1641 | } |
| 1642 | return; |
| 1643 | } |
| 1644 | out.push(json! |
| 1645 | } |
| 1646 | |
| 1647 | fn to_anthropic_messages(messages: |
| 1648 | let mut out |
| 1649 | let mut pending_results |
| 1650 | for m in messages |
| 1651 | match m.role.as_str |
| 1652 | "system" => continue, |
| 1653 | "assistant" => { |
| 1654 | if !pending_results.is_empty |
| 1655 | push_blocks(&mut out |
| 1656 | } |
| 1657 | let mut blocks |
| 1658 | if let Some |
| 1659 | && !c.is_empty |
| 1660 | { |
| 1661 | blocks.push(json! |
| 1662 | } |
| 1663 | for tc in & |
| 1664 | blocks.push(json! |
| 1665 | } |
| 1666 | if !blocks.is_empty |
| 1667 | push_blocks(&mut out |
| 1668 | } |
| 1669 | } |
| 1670 | "tool" => { |
| 1671 | pending_results.push(json! |
| 1672 | "type": "tool_result", |
| 1673 | "tool_use_id": m. |
| 1674 | "content": m. |
| 1675 | })); |
| 1676 | } |
| 1677 | "user" => { |
| 1678 | if !pending_results.is_empty |
| 1679 | let mut blocks |
| 1680 | if let Some |
| 1681 | && !c.is_empty |
| 1682 | { |
| 1683 | blocks.push(json! |
| 1684 | } |
| 1685 | push_image_blocks(&mut blocks |
| 1686 | push_blocks(&mut out |
| 1687 | } else { |
| 1688 | let mut blocks |
| 1689 | if let Some |
| 1690 | && !c.is_empty |
| 1691 | { |
| 1692 | blocks.push(json! |
| 1693 | } |
| 1694 | push_image_blocks(&mut blocks |
| 1695 | if blocks.is_empty() |
| 1696 | blocks.push(json! |
| 1697 | } |
| 1698 | push_blocks(&mut out |
| 1699 | } |
| 1700 | } |
| 1701 | _ => {} |
| 1702 | } |
| 1703 | } |
| 1704 | if !pending_results.is_empty |
| 1705 | push_blocks(&mut out |
| 1706 | } |
| 1707 | if let Some |
| 1708 | && first["role" |
| 1709 | { |
| 1710 | out.insert( |
| 1711 | 0, |
| 1712 | json!({"role": |
| 1713 | ); |
| 1714 | } |
| 1715 | out |
| 1716 | } |
| 1717 | |
| 1718 | fn chat_anthropic( |
| 1719 | cfg: &ProviderConfig |
| 1720 | model: &str |
| 1721 | system: &str |
| 1722 | messages: &[LlmMessage |
| 1723 | tools: &[ToolDef |
| 1724 | on_delta: Option |
| 1725 | ) -> Result<LlmResponse |
| 1726 | let url = |
| 1727 | let streaming = |
| 1728 | let mut body |
| 1729 | "model": model, |
| 1730 | "max_tokens": cfg. |
| 1731 | "system": system, |
| 1732 | "messages": to_anthropic_messages( |
| 1733 | "stream": streaming, |
| 1734 | }); |
| 1735 | if !tools.is_empty |
| 1736 | body["tools"] |
| 1737 | tools |
| 1738 | .iter() |
| 1739 | .map(|t| |
| 1740 | .collect::<Vec |
| 1741 | ); |
| 1742 | } |
| 1743 | if streaming { |
| 1744 | let on_delta = |
| 1745 | return stream_anthropic(cfg, |
| 1746 | } |
| 1747 | let resp = |
| 1748 | let blocks = |
| 1749 | .get("content") |
| 1750 | .and_then(|v| |
| 1751 | .context("no content in response") |
| 1752 | let mut content |
| 1753 | let mut tool_calls |
| 1754 | for block in blocks |
| 1755 | match block.get( |
| 1756 | Some("text") |
| 1757 | if let Some |
| 1758 | content.push_str(t |
| 1759 | } |
| 1760 | } |
| 1761 | Some("tool_use") |
| 1762 | let id = |
| 1763 | .get("id") |
| 1764 | .and_then(|v| |
| 1765 | .unwrap_or("") |
| 1766 | .to_string(); |
| 1767 | let name = |
| 1768 | .get("name") |
| 1769 | .and_then(|v| |
| 1770 | .unwrap_or("") |
| 1771 | .to_string(); |
| 1772 | let input = |
| 1773 | tool_calls.push(ToolCall |
| 1774 | id, |
| 1775 | name, |
| 1776 | arguments: input, |
| 1777 | }); |
| 1778 | } |
| 1779 | _ => {} |
| 1780 | } |
| 1781 | } |
| 1782 | Ok(LlmResponse |
| 1783 | content: if content |
| 1784 | None |
| 1785 | } else { |
| 1786 | Some(content) |
| 1787 | }, |
| 1788 | reasoning: None |
| 1789 | tool_calls, |
| 1790 | finish_reason: resp |
| 1791 | .get("stop_reason") |
| 1792 | .and_then(|v| |
| 1793 | .map(|fr| |
| 1794 | if fr == " |
| 1795 | "length".to_string() |
| 1796 | } else { |
| 1797 | fr.to_string() |
| 1798 | } |
| 1799 | }), |
| 1800 | usage: resp.get |
| 1801 | }) |
| 1802 | } |
| 1803 | |
| 1804 | fn stream_anthropic( |
| 1805 | cfg: &ProviderConfig |
| 1806 | url: &str |
| 1807 | body: &Value |
| 1808 | on_delta: &mut |
| 1809 | ) -> Result<LlmResponse |
| 1810 | let mut req |
| 1811 | .timeout(LLM_TIMEOUT) |
| 1812 | .set("Content-Type", |
| 1813 | if let Some |
| 1814 | req = req |
| 1815 | .set("x-api-key", |
| 1816 | .set("anthropic-version", |
| 1817 | } |
| 1818 | let resp = |
| 1819 | Ok(r) |
| 1820 | Err(ureq:: |
| 1821 | let body = |
| 1822 | bail!("HTTP {code |
| 1823 | } |
| 1824 | Err(e) |
| 1825 | }; |
| 1826 | let mut reader |
| 1827 | let mut buf |
| 1828 | let mut content |
| 1829 | let mut tool_blocks |
| 1830 | // Anthropic splits usage across events: `message_start` carries the input |
| 1831 | // side (input/cache tokens), `message_delta` the output side + stop_reason. |
| 1832 | let mut usage |
| 1833 | let mut saw_usage |
| 1834 | let mut finish_reason |
| 1835 | loop { |
| 1836 | buf.clear(); |
| 1837 | let n = |
| 1838 | if n == 0 |
| 1839 | break; |
| 1840 | } |
| 1841 | let line = |
| 1842 | let line = |
| 1843 | if line.is_empty() |
| 1844 | continue; |
| 1845 | } |
| 1846 | let data = |
| 1847 | if data.is_empty() |
| 1848 | continue; |
| 1849 | } |
| 1850 | let v: Value |
| 1851 | Ok(v) |
| 1852 | Err(_) |
| 1853 | }; |
| 1854 | let event_type = |
| 1855 | match event_type { |
| 1856 | "message_start" => { |
| 1857 | if let Some |
| 1858 | usage.input = u |
| 1859 | usage.cache_read = u |
| 1860 | .get("cache_read_input_tokens") |
| 1861 | .and_then(|x| |
| 1862 | .unwrap_or(0); |
| 1863 | usage.cache_write = u |
| 1864 | .get("cache_creation_input_tokens") |
| 1865 | .and_then(|x| |
| 1866 | .unwrap_or(0); |
| 1867 | saw_usage = true; |
| 1868 | } |
| 1869 | } |
| 1870 | "message_delta" => { |
| 1871 | if let Some |
| 1872 | usage.output = u |
| 1873 | saw_usage = true; |
| 1874 | } |
| 1875 | // `end_turn` (a full answer), `max_tokens` (output budget hit — |
| 1876 | // pi's "length"), `stop_sequence`, `tool_use`. |
| 1877 | if let Some |
| 1878 | finish_reason = Some |
| 1879 | "max_tokens" => "length" |
| 1880 | "tool_use" => "tool_use" |
| 1881 | other => other. |
| 1882 | }); |
| 1883 | } |
| 1884 | } |
| 1885 | "content_block_start" => { |
| 1886 | let block = |
| 1887 | if block.get( |
| 1888 | let id = |
| 1889 | .get("id") |
| 1890 | .and_then(|x| |
| 1891 | .unwrap_or("") |
| 1892 | .to_string(); |
| 1893 | let name = |
| 1894 | .get("name") |
| 1895 | .and_then(|x| |
| 1896 | .unwrap_or("") |
| 1897 | .to_string(); |
| 1898 | tool_blocks.push((id |
| 1899 | } |
| 1900 | } |
| 1901 | "content_block_delta" => { |
| 1902 | let delta = |
| 1903 | match delta.get( |
| 1904 | Some("text_delta") |
| 1905 | if let Some |
| 1906 | content.push_str(t |
| 1907 | on_delta(t); |
| 1908 | } |
| 1909 | } |
| 1910 | Some("input_json_delta") |
| 1911 | if let Some |
| 1912 | && let Some |
| 1913 | { |
| 1914 | last.2.push_str( |
| 1915 | } |
| 1916 | } |
| 1917 | _ => {} |
| 1918 | } |
| 1919 | } |
| 1920 | _ => {} |
| 1921 | } |
| 1922 | } |
| 1923 | let mut tool_calls |
| 1924 | for (id, name |
| 1925 | tool_calls.push(ToolCall |
| 1926 | id, |
| 1927 | name, |
| 1928 | arguments: serde_json::from_str |
| 1929 | }); |
| 1930 | } |
| 1931 | Ok(LlmResponse |
| 1932 | content: if content |
| 1933 | None |
| 1934 | } else { |
| 1935 | Some(content) |
| 1936 | }, |
| 1937 | reasoning: None |
| 1938 | tool_calls, |
| 1939 | finish_reason, |
| 1940 | usage: if saw_usage |
| 1941 | }) |
| 1942 | } |
| 1943 | |
| 1944 | fn gpush(out: |
| 1945 | if let Some |
| 1946 | && last["role" |
| 1947 | && let Some |
| 1948 | { |
| 1949 | for p in parts |
| 1950 | arr.push(p |
| 1951 | } |
| 1952 | return; |
| 1953 | } |
| 1954 | out.push(json! |
| 1955 | } |
| 1956 | |
| 1957 | fn parse_tool_content(c: |
| 1958 | match c { |
| 1959 | None => json! |
| 1960 | Some(s) |
| 1961 | } |
| 1962 | } |
| 1963 | |
| 1964 | fn to_gemini_contents(messages: |
| 1965 | let mut out |
| 1966 | let mut pending_fn |
| 1967 | for m in messages |
| 1968 | match m.role.as_str |
| 1969 | "system" => continue, |
| 1970 | "assistant" => { |
| 1971 | if !pending_fn.is_empty |
| 1972 | gpush(&mut out |
| 1973 | } |
| 1974 | let mut parts |
| 1975 | if let Some |
| 1976 | && !c.is_empty |
| 1977 | { |
| 1978 | parts.push(json! |
| 1979 | } |
| 1980 | for tc in & |
| 1981 | parts.push(json! |
| 1982 | } |
| 1983 | if !parts.is_empty |
| 1984 | gpush(&mut out |
| 1985 | } |
| 1986 | } |
| 1987 | "tool" => { |
| 1988 | let name = |
| 1989 | pending_fn.push(json! |
| 1990 | } |
| 1991 | "user" => { |
| 1992 | let mut parts |
| 1993 | if let Some |
| 1994 | && !c.is_empty |
| 1995 | { |
| 1996 | parts.push(json! |
| 1997 | } |
| 1998 | for img in & |
| 1999 | parts.push(image_gemini_part |
| 2000 | } |
| 2001 | if !parts.is_empty |
| 2002 | gpush(&mut out |
| 2003 | } |
| 2004 | } |
| 2005 | _ => {} |
| 2006 | } |
| 2007 | } |
| 2008 | if !pending_fn.is_empty |
| 2009 | gpush(&mut out |
| 2010 | } |
| 2011 | out |
| 2012 | } |
| 2013 | |
| 2014 | fn chat_gemini( |
| 2015 | cfg: &ProviderConfig |
| 2016 | model: &str |
| 2017 | system: &str |
| 2018 | messages: &[LlmMessage |
| 2019 | tools: &[ToolDef |
| 2020 | on_delta: Option |
| 2021 | ) -> Result<LlmResponse |
| 2022 | let base = |
| 2023 | if base.is_empty() |
| 2024 | bail!( |
| 2025 | "No base URL configured for '{}'. Run `/connect google-vertex` or set GOOGLE_VERTEX_BASE_URL.", |
| 2026 | cfg.name |
| 2027 | ); |
| 2028 | } |
| 2029 | let streaming = |
| 2030 | let url = |
| 2031 | let key = |
| 2032 | .api_key |
| 2033 | .as_deref() |
| 2034 | .context("missing Gemini API key (GOOGLE_API_KEY or GEMINI_API_KEY)") |
| 2035 | if streaming { |
| 2036 | format!("{base} |
| 2037 | } else { |
| 2038 | format!("{base} |
| 2039 | } |
| 2040 | } else if streaming |
| 2041 | format!("{base} |
| 2042 | } else { |
| 2043 | format!("{base} |
| 2044 | }; |
| 2045 | let mut body |
| 2046 | "contents": to_gemini_contents( |
| 2047 | "systemInstruction": {"parts" |
| 2048 | "generationConfig": {"maxOutputTokens" |
| 2049 | }); |
| 2050 | if !tools.is_empty |
| 2051 | body["tools"] |
| 2052 | "functionDeclarations": tools |
| 2053 | .iter() |
| 2054 | .map(|t| |
| 2055 | .collect::<Vec |
| 2056 | }]); |
| 2057 | } |
| 2058 | if streaming { |
| 2059 | let on_delta = |
| 2060 | return stream_gemini(cfg, |
| 2061 | } |
| 2062 | let resp = |
| 2063 | let parts = |
| 2064 | .pointer("/candidates/0/content/parts") |
| 2065 | .and_then(|v| |
| 2066 | .context("no candidates[0].content.parts in response") |
| 2067 | let mut content |
| 2068 | let mut tool_calls |
| 2069 | for (i, part |
| 2070 | if let Some |
| 2071 | content.push_str(t |
| 2072 | } |
| 2073 | if let Some |
| 2074 | let name = |
| 2075 | .get("name") |
| 2076 | .and_then(|v| |
| 2077 | .unwrap_or("") |
| 2078 | .to_string(); |
| 2079 | let args = |
| 2080 | tool_calls.push(ToolCall |
| 2081 | id: format! |
| 2082 | name, |
| 2083 | arguments: args, |
| 2084 | }); |
| 2085 | } |
| 2086 | } |
| 2087 | Ok(LlmResponse |
| 2088 | content: if content |
| 2089 | None |
| 2090 | } else { |
| 2091 | Some(content) |
| 2092 | }, |
| 2093 | reasoning: None |
| 2094 | tool_calls, |
| 2095 | finish_reason: resp |
| 2096 | .pointer("/candidates/0/finishReason") |
| 2097 | .and_then(|v| |
| 2098 | .map(|fr| |
| 2099 | if fr == " |
| 2100 | "length".to_string() |
| 2101 | } else { |
| 2102 | fr.to_string() |
| 2103 | } |
| 2104 | }), |
| 2105 | usage: resp.get |
| 2106 | }) |
| 2107 | } |
| 2108 | |
| 2109 | fn stream_gemini( |
| 2110 | cfg: &ProviderConfig |
| 2111 | url: &str |
| 2112 | body: &Value |
| 2113 | on_delta: &mut |
| 2114 | ) -> Result<LlmResponse |
| 2115 | let mut req |
| 2116 | .timeout(LLM_TIMEOUT) |
| 2117 | .set("Content-Type", |
| 2118 | if !cfg.key_in_url |
| 2119 | && let Some |
| 2120 | { |
| 2121 | req = req. |
| 2122 | } |
| 2123 | let resp = |
| 2124 | Ok(r) |
| 2125 | Err(ureq:: |
| 2126 | let body = |
| 2127 | bail!("HTTP {code |
| 2128 | } |
| 2129 | Err(e) |
| 2130 | }; |
| 2131 | let mut reader |
| 2132 | let mut buf |
| 2133 | let mut content |
| 2134 | let mut fcs |
| 2135 | let mut finish_reason |
| 2136 | let mut usage |
| 2137 | loop { |
| 2138 | buf.clear(); |
| 2139 | let n = |
| 2140 | if n == 0 |
| 2141 | break; |
| 2142 | } |
| 2143 | let line = |
| 2144 | let line = |
| 2145 | if line.is_empty() |
| 2146 | continue; |
| 2147 | } |
| 2148 | let data = |
| 2149 | if data.is_empty() |
| 2150 | continue; |
| 2151 | } |
| 2152 | let v: Value |
| 2153 | Ok(v) |
| 2154 | Err(_) |
| 2155 | }; |
| 2156 | if let Some |
| 2157 | finish_reason = Some |
| 2158 | "MAX_TOKENS" => "length" |
| 2159 | "STOP" => "stop" |
| 2160 | other => other. |
| 2161 | }); |
| 2162 | } |
| 2163 | if let Some |
| 2164 | usage = Some |
| 2165 | } |
| 2166 | let Some( |
| 2167 | .pointer("/candidates/0/content/parts") |
| 2168 | .and_then(|x| |
| 2169 | else { |
| 2170 | continue; |
| 2171 | }; |
| 2172 | for (i, part |
| 2173 | if let Some |
| 2174 | content.push_str(t |
| 2175 | on_delta(t); |
| 2176 | } |
| 2177 | if let Some |
| 2178 | let name = |
| 2179 | .get("name") |
| 2180 | .and_then(|x| |
| 2181 | .unwrap_or("") |
| 2182 | .to_string(); |
| 2183 | let args = |
| 2184 | fcs.insert(i |
| 2185 | } |
| 2186 | } |
| 2187 | } |
| 2188 | let mut tool_calls |
| 2189 | let mut indices |
| 2190 | indices.sort_unstable(); |
| 2191 | for i in indices |
| 2192 | let (name, |
| 2193 | tool_calls.push(ToolCall |
| 2194 | id: format! |
| 2195 | name, |
| 2196 | arguments, |
| 2197 | }); |
| 2198 | } |
| 2199 | Ok(LlmResponse |
| 2200 | content: if content |
| 2201 | None |
| 2202 | } else { |
| 2203 | Some(content) |
| 2204 | }, |
| 2205 | reasoning: None |
| 2206 | tool_calls, |
| 2207 | finish_reason, |
| 2208 | usage, |
| 2209 | }) |
| 2210 | } |
| 2211 | |
| 2212 | // ---- Amazon Bedrock (AWS SigV4 + Converse API) ---- |
| 2213 | |
| 2214 | fn sha256_hex(data: |
| 2215 | let mut h |
| 2216 | h.update(data |
| 2217 | h.finalize().iter |
| 2218 | } |
| 2219 | |
| 2220 | fn hmac_bytes(key: |
| 2221 | let mut mac |
| 2222 | mac.update(data |
| 2223 | mac.finalize().into_bytes |
| 2224 | } |
| 2225 | |
| 2226 | fn to_bedrock_messages(messages: |
| 2227 | let mut out |
| 2228 | let mut pending |
| 2229 | for m in messages |
| 2230 | match m.role.as_str |
| 2231 | "system" => continue, |
| 2232 | "assistant" => { |
| 2233 | if !pending.is_empty |
| 2234 | push_blocks(&mut out |
| 2235 | } |
| 2236 | let mut blocks |
| 2237 | if let Some |
| 2238 | && !c.is_empty |
| 2239 | { |
| 2240 | blocks.push(json! |
| 2241 | } |
| 2242 | for tc in & |
| 2243 | blocks.push(json! |
| 2244 | } |
| 2245 | if !blocks.is_empty |
| 2246 | push_blocks(&mut out |
| 2247 | } |
| 2248 | } |
| 2249 | "tool" => { |
| 2250 | pending.push(json! |
| 2251 | "toolResult": { |
| 2252 | "toolUseId": m. |
| 2253 | "content": [{"text" |
| 2254 | } |
| 2255 | })); |
| 2256 | } |
| 2257 | "user" => { |
| 2258 | if !pending.is_empty |
| 2259 | let mut blocks |
| 2260 | if let Some |
| 2261 | && !c.is_empty |
| 2262 | { |
| 2263 | blocks.push(json! |
| 2264 | } |
| 2265 | push_image_blocks(&mut blocks |
| 2266 | push_blocks(&mut out |
| 2267 | } else { |
| 2268 | let mut blocks |
| 2269 | if let Some |
| 2270 | && !c.is_empty |
| 2271 | { |
| 2272 | blocks.push(json! |
| 2273 | } |
| 2274 | push_image_blocks(&mut blocks |
| 2275 | if blocks.is_empty() |
| 2276 | blocks.push(json! |
| 2277 | } |
| 2278 | push_blocks(&mut out |
| 2279 | } |
| 2280 | } |
| 2281 | _ => {} |
| 2282 | } |
| 2283 | } |
| 2284 | if !pending.is_empty |
| 2285 | push_blocks(&mut out |
| 2286 | } |
| 2287 | out |
| 2288 | } |
| 2289 | |
| 2290 | fn post_bedrock(cfg: |
| 2291 | let access_key = |
| 2292 | .api_key |
| 2293 | .as_deref() |
| 2294 | .context("missing AWS_ACCESS_KEY_ID") |
| 2295 | let secret_key = |
| 2296 | .aws_secret_key |
| 2297 | .as_deref() |
| 2298 | .context("missing AWS_SECRET_ACCESS_KEY") |
| 2299 | let region = |
| 2300 | let body_str = |
| 2301 | let payload_hash = |
| 2302 | |
| 2303 | let now = |
| 2304 | let amz_date = |
| 2305 | let date_stamp = |
| 2306 | |
| 2307 | let parsed = |
| 2308 | let host = |
| 2309 | let path = |
| 2310 | |
| 2311 | let canonical_headers = |
| 2312 | "content-type:application/json\nhost:{host}\ |
| 2313 | ); |
| 2314 | let signed_headers = |
| 2315 | let canonical_request = |
| 2316 | format!("POST\n |
| 2317 | let scope = |
| 2318 | let string_to_sign = |
| 2319 | "AWS4-HMAC-SHA256\n{amz_date}\n |
| 2320 | sha256_hex(canonical_request.as_bytes |
| 2321 | ); |
| 2322 | |
| 2323 | let mut key |
| 2324 | key.extend_from_slice(secret_key |
| 2325 | let k_date = |
| 2326 | let k_region = |
| 2327 | let k_service = |
| 2328 | let k_signing = |
| 2329 | let signature = |
| 2330 | .iter() |
| 2331 | .map(|b| |
| 2332 | .collect::<String |
| 2333 | let authorization = |
| 2334 | "AWS4-HMAC-SHA256 Credential={access_key}/{scope} |
| 2335 | ); |
| 2336 | |
| 2337 | let mut req |
| 2338 | .timeout(LLM_TIMEOUT) |
| 2339 | .set("Content-Type", |
| 2340 | .set("X-Amz-Date", |
| 2341 | .set("X-Amz-Content-Sha256", |
| 2342 | .set("Authorization", |
| 2343 | if let Some |
| 2344 | req = req. |
| 2345 | } |
| 2346 | let resp = |
| 2347 | Ok(r) |
| 2348 | Err(ureq:: |
| 2349 | let txt = |
| 2350 | bail!("HTTP {code |
| 2351 | } |
| 2352 | Err(e) |
| 2353 | }; |
| 2354 | let v: Value |
| 2355 | .into_json() |
| 2356 | .context("invalid JSON response from Bedrock") |
| 2357 | if let Some |
| 2358 | bail!("Bedrock error: {err |
| 2359 | } |
| 2360 | Ok(v) |
| 2361 | } |
| 2362 | |
| 2363 | fn chat_bedrock( |
| 2364 | cfg: &ProviderConfig |
| 2365 | model: &str |
| 2366 | system: &str |
| 2367 | messages: &[LlmMessage |
| 2368 | tools: &[ToolDef |
| 2369 | _on_delta: Option |
| 2370 | ) -> Result<LlmResponse |
| 2371 | let url = |
| 2372 | "{}/model/{model}/converse", |
| 2373 | cfg.base_url.trim_end_matches( |
| 2374 | ); |
| 2375 | let mut body |
| 2376 | "modelId": model, |
| 2377 | "system": [{"text" |
| 2378 | "messages": to_bedrock_messages( |
| 2379 | "inferenceConfig": {"maxTokens" |
| 2380 | }); |
| 2381 | if !tools.is_empty |
| 2382 | body["toolConfig"] |
| 2383 | "tools": tools |
| 2384 | .iter() |
| 2385 | .map(|t| |
| 2386 | .collect::<Vec |
| 2387 | }); |
| 2388 | } |
| 2389 | let resp = |
| 2390 | let message = |
| 2391 | .pointer("/output/message") |
| 2392 | .context("no output.message in response") |
| 2393 | .clone(); |
| 2394 | let mut content |
| 2395 | let mut tool_calls |
| 2396 | if let Some |
| 2397 | for block in arr |
| 2398 | if let Some |
| 2399 | content.push_str(t |
| 2400 | } |
| 2401 | if let Some |
| 2402 | let id = |
| 2403 | .get("toolUseId") |
| 2404 | .and_then(|v| |
| 2405 | .unwrap_or("") |
| 2406 | .to_string(); |
| 2407 | let name = |
| 2408 | .get("name") |
| 2409 | .and_then(|v| |
| 2410 | .unwrap_or("") |
| 2411 | .to_string(); |
| 2412 | let input = |
| 2413 | tool_calls.push(ToolCall |
| 2414 | id, |
| 2415 | name, |
| 2416 | arguments: input, |
| 2417 | }); |
| 2418 | } |
| 2419 | } |
| 2420 | } |
| 2421 | Ok(LlmResponse |
| 2422 | content: if content |
| 2423 | None |
| 2424 | } else { |
| 2425 | Some(content) |
| 2426 | }, |
| 2427 | reasoning: None |
| 2428 | tool_calls, |
| 2429 | finish_reason: resp |
| 2430 | .pointer("/output/stopReason") |
| 2431 | .and_then(|v| |
| 2432 | .map(|fr| |
| 2433 | if fr == " |
| 2434 | "length".to_string() |
| 2435 | } else { |
| 2436 | fr.to_string() |
| 2437 | } |
| 2438 | }), |
| 2439 | usage: resp.pointer |
| 2440 | }) |
| 2441 | } |
| 2442 | |
| 2443 | #[cfg(test)] |
| 2444 | mod tests { |
| 2445 | use super::*; |
| 2446 | use anyhow::anyhow; |
| 2447 | |
| 2448 | fn err(s: |
| 2449 | anyhow!(s.into |
| 2450 | } |
| 2451 | |
| 2452 | #[test] |
| 2453 | fn transient_http_status_codes() { |
| 2454 | assert!(is_transient_err( |
| 2455 | "HTTP 429 from https://api.example.com: rate limited" |
| 2456 | ))); |
| 2457 | assert!(is_transient_err( |
| 2458 | "HTTP 500 from https://api.example.com: boom" |
| 2459 | ))); |
| 2460 | assert!(is_transient_err( |
| 2461 | "HTTP 503 from https://api.example.com: unavailable" |
| 2462 | ))); |
| 2463 | // A 200 with an empty body is a silent network drop, not a model |
| 2464 | // answer — it must retry, never persist an empty assistant message. |
| 2465 | assert!(is_transient_err( |
| 2466 | "empty response from provider (no content, no tool calls)" |
| 2467 | ))); |
| 2468 | } |
| 2469 | |
| 2470 | #[test] |
| 2471 | fn reasoning_content_round_trips_through_openai_messages() { |
| 2472 | let mut m |
| 2473 | role: "assistant". |
| 2474 | content: None |
| 2475 | tool_call_id: None |
| 2476 | name: None |
| 2477 | tool_calls: vec! |
| 2478 | reasoning: Some |
| 2479 | images: vec! |
| 2480 | }; |
| 2481 | let mut out |
| 2482 | assert_eq!( |
| 2483 | out[0]["reasoning_content" |
| 2484 | json!("I should check the file first."), |
| 2485 | "thinking-mode providers demand reasoning_content echoed back" |
| 2486 | ); |
| 2487 | // No reasoning → the field stays out of the payload entirely. |
| 2488 | m.reasoning = None |
| 2489 | out = to_openai_messages( |
| 2490 | assert!( |
| 2491 | out[0].get |
| 2492 | "payload must not carry an empty reasoning field" |
| 2493 | ); |
| 2494 | } |
| 2495 | |
| 2496 | #[test] |
| 2497 | fn non_transient_http_status_codes() { |
| 2498 | assert!(!is_transient_err |
| 2499 | "HTTP 400 from https://api.example.com: bad request" |
| 2500 | ))); |
| 2501 | assert!(!is_transient_err |
| 2502 | "HTTP 401 from https://api.example.com: unauthorized" |
| 2503 | ))); |
| 2504 | assert!(!is_transient_err |
| 2505 | "HTTP 404 from https://api.example.com: not found" |
| 2506 | ))); |
| 2507 | } |
| 2508 | |
| 2509 | #[test] |
| 2510 | fn overloaded_message_patterns() { |
| 2511 | assert!(is_transient_err( |
| 2512 | "API error: {\"error\":{\ |
| 2513 | ))); |
| 2514 | assert!(is_transient_err( |
| 2515 | assert!(is_transient_err( |
| 2516 | } |
| 2517 | |
| 2518 | #[test] |
| 2519 | fn never_retries_auth_and_validation() { |
| 2520 | assert!(!is_transient_err |
| 2521 | "Missing credentials for provider 'openai'" |
| 2522 | ))); |
| 2523 | assert!(!is_transient_err |
| 2524 | "API error: {\"error\":{\ |
| 2525 | ))); |
| 2526 | assert!(!is_transient_err |
| 2527 | } |
| 2528 | |
| 2529 | #[test] |
| 2530 | fn context_overflow_patterns_across_providers() { |
| 2531 | // OpenAI-compatible: "This model's maximum context length is 200000 |
| 2532 | // tokens. However, you requested about 230000 tokens…" |
| 2533 | assert!(is_context_overflow( |
| 2534 | "HTTP 400 from https://api.example.com: {\"error\":{\ |
| 2535 | model's maximum context length is 200000 tokens. However, you requested \ |
| 2536 | about 230000 tokens. Reduce the length of the messages before your \ |
| 2537 | request.\"}}" |
| 2538 | ))); |
| 2539 | // Anthropic: request_too_large |
| 2540 | assert!(is_context_overflow( |
| 2541 | "HTTP 400 from https://api.anthropic.com: {\"type\":\ |
| 2542 | {\"type\":\"request_too_large |
| 2543 | tokens > 200000 maximum\"}}" |
| 2544 | ))); |
| 2545 | // Gemini: input token count exceeds the maximum |
| 2546 | assert!(is_context_overflow( |
| 2547 | "API error: {\"error\":{\ |
| 2548 | (180000 tokens) exceeds the maximum number of tokens allowed (128000 \ |
| 2549 | tokens)\"}}" |
| 2550 | ))); |
| 2551 | // context window overflow style |
| 2552 | assert!(is_context_overflow( |
| 2553 | assert!(is_context_overflow( |
| 2554 | assert!(is_context_overflow( |
| 2555 | "Error: history is too long for the model's context window" |
| 2556 | ))); |
| 2557 | } |
| 2558 | |
| 2559 | #[test] |
| 2560 | fn output_budget_stop_is_not_context_overflow() { |
| 2561 | // The finish_reason=length guard is an *output*-budget problem (thinking |
| 2562 | // ate the whole max_tokens), not a context problem: it must not trip the |
| 2563 | // context-overflow detector. pi's `isRecoverableLength` handles it |
| 2564 | // separately — compact once and retry, then the original error surfaces |
| 2565 | // with the raise-MAX_TOKENS fix. |
| 2566 | assert!(!is_context_overflow |
| 2567 | "provider hit its output token limit (finish_reason=length) with no content — \ |
| 2568 | the model used the entire 16384 output budget on reasoning. Raise MAX_TOKENS \ |
| 2569 | (default 16384) or lower thinking effort with /effort so the answer fits." |
| 2570 | ))); |
| 2571 | // And unrelated failures stay untouched. |
| 2572 | assert!(!is_context_overflow |
| 2573 | assert!(!is_context_overflow |
| 2574 | assert!(!is_context_overflow |
| 2575 | } |
| 2576 | |
| 2577 | #[test] |
| 2578 | fn recoverable_length_matches_zero_output_guards() { |
| 2579 | assert!(is_recoverable_length( |
| 2580 | "finish_reason=length with zero output tokens; context exhausted" |
| 2581 | ))); |
| 2582 | // The provider-side output-budget guard reports the same stop reason, so |
| 2583 | // it also gets one compact-and-retry (pi's isRecoverableLength). |
| 2584 | assert!(is_recoverable_length( |
| 2585 | "provider hit its output token limit (finish_reason=length) with no content" |
| 2586 | ))); |
| 2587 | assert!(!is_recoverable_length |
| 2588 | assert!(!is_recoverable_length |
| 2589 | } |
| 2590 | |
| 2591 | #[test] |
| 2592 | fn usage_overflow_and_length_detection() { |
| 2593 | let resp = |
| 2594 | content: Some |
| 2595 | reasoning: None |
| 2596 | tool_calls: vec! |
| 2597 | finish_reason: finish.map |
| 2598 | usage, |
| 2599 | }; |
| 2600 | // stop + input filled 99% of the window => silent overflow (pi Case 2). |
| 2601 | assert!(context_overflowed( |
| 2602 | &resp( |
| 2603 | Some("stop"), |
| 2604 | Some(LlmUsage |
| 2605 | input: 130_000, |
| 2606 | cache_read: 0, |
| 2607 | ..Default::default() |
| 2608 | }) |
| 2609 | ), |
| 2610 | 131_072 |
| 2611 | )); |
| 2612 | // stop with plenty of room => fine. |
| 2613 | assert!(!context_overflowed |
| 2614 | &resp( |
| 2615 | Some("stop"), |
| 2616 | Some(LlmUsage |
| 2617 | input: 50_000, |
| 2618 | ..Default::default() |
| 2619 | }) |
| 2620 | ), |
| 2621 | 131_072 |
| 2622 | )); |
| 2623 | // length + zero output => recoverable. |
| 2624 | assert!(recovered_length( |
| 2625 | Some("length"), |
| 2626 | Some(LlmUsage |
| 2627 | output: 0, |
| 2628 | input: 130_000, |
| 2629 | ..Default::default() |
| 2630 | }) |
| 2631 | ))); |
| 2632 | // length with real output => a partial answer, not recoverable. |
| 2633 | assert!(!recovered_length |
| 2634 | Some("length"), |
| 2635 | Some(LlmUsage |
| 2636 | output: 4096, |
| 2637 | ..Default::default() |
| 2638 | }) |
| 2639 | ))); |
| 2640 | // No usage reported => neither detector fires. |
| 2641 | assert!(!context_overflowed |
| 2642 | assert!(!recovered_length |
| 2643 | } |
| 2644 | |
| 2645 | #[test] |
| 2646 | fn usage_parses_provider_shapes() { |
| 2647 | // OpenAI-compatible: prompt_tokens/completion_tokens. |
| 2648 | let u = |
| 2649 | "prompt_tokens": 100, " |
| 2650 | })) |
| 2651 | .unwrap(); |
| 2652 | assert_eq!(u.input |
| 2653 | assert_eq!(u.output |
| 2654 | // Anthropic: input_tokens/output_tokens + cache reads. |
| 2655 | let u = |
| 2656 | "input_tokens": 500, " |
| 2657 | "cache_read_input_tokens": 12_000, " |
| 2658 | })) |
| 2659 | .unwrap(); |
| 2660 | assert_eq!(u.input |
| 2661 | assert_eq!(u.cache_read |
| 2662 | assert_eq!(u.cache_write |
| 2663 | // Gemini: camelCase usageMetadata. |
| 2664 | let u = |
| 2665 | "promptTokenCount": 700, " |
| 2666 | "cachedContentTokenCount": 900, " |
| 2667 | })) |
| 2668 | .unwrap(); |
| 2669 | assert_eq!(u.input |
| 2670 | assert_eq!(u.output |
| 2671 | assert_eq!(u.cache_read |
| 2672 | assert_eq!(u.total |
| 2673 | // Bedrock Converse: camelCase totals. |
| 2674 | let u = |
| 2675 | "inputTokens": 200, " |
| 2676 | "cacheWriteInputTokens": 1, " |
| 2677 | })) |
| 2678 | .unwrap(); |
| 2679 | assert_eq!(u.input |
| 2680 | assert_eq!(u.output |
| 2681 | assert_eq!(u.cache_read |
| 2682 | assert_eq!(u.cache_write |
| 2683 | assert_eq!(u.total |
| 2684 | // Unknown shapes yield None (no real usage reported), never panic. |
| 2685 | assert!(LlmUsage |
| 2686 | } |
| 2687 | |
| 2688 | #[test] |
| 2689 | fn backoff_sequence_doubles() { |
| 2690 | assert_eq!(MAX_RETRIES, |
| 2691 | assert_eq!(2000u64 |
| 2692 | assert_eq!(2000u64 |
| 2693 | assert_eq!(2000u64 |
| 2694 | } |
| 2695 | |
| 2696 | #[test] |
| 2697 | fn effort_wire_maps_pi_levels_to_deepseek_values() { |
| 2698 | assert_eq!(effort_wire( |
| 2699 | assert_eq!(effort_wire( |
| 2700 | assert_eq!(effort_wire( |
| 2701 | assert_eq!(effort_wire( |
| 2702 | assert_eq!(effort_wire( |
| 2703 | assert_eq!(effort_wire( |
| 2704 | assert_eq!(effort_wire( |
| 2705 | } |
| 2706 | |
| 2707 | #[test] |
| 2708 | fn provider_config_effort_defaults_to_none() { |
| 2709 | let cfg = |
| 2710 | assert_eq!(cfg.effort |
| 2711 | assert_eq!(cfg.effort_wire |
| 2712 | } |
| 2713 | |
| 2714 | #[test] |
| 2715 | fn chat_compatible_body_omits_or_injects_reasoning_effort() { |
| 2716 | // Dark-build the request body helper path: effort Some("high") adds |
| 2717 | // reasoning_effort="high"; None and "off" omit it. |
| 2718 | let mut cfg |
| 2719 | let body_with = |
| 2720 | assert!(body_with. |
| 2721 | |
| 2722 | cfg.effort = Some |
| 2723 | let body_high = |
| 2724 | assert_eq!(body_high[ |
| 2725 | |
| 2726 | cfg.effort = Some |
| 2727 | let body_off = |
| 2728 | assert!(body_off. |
| 2729 | } |
| 2730 | } |