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