| 1 | use super::*; |
| 2 | use codewhale_models::{ImageUrlContent, Message, SystemBlock, Tool}; |
| 3 | |
| 4 | fn request(messages: Vec<Message>) -> MessageRequest { |
| 5 | MessageRequest { |
| 6 | model: "gemini-4-argon".to_string(), |
| 7 | messages, |
| 8 | max_tokens: 4096, |
| 9 | system: None, |
| 10 | tools: None, |
| 11 | tool_choice: None, |
| 12 | metadata: None, |
| 13 | thinking: None, |
| 14 | reasoning_effort: None, |
| 15 | stream: Some(true), |
| 16 | temperature: None, |
| 17 | top_p: None, |
| 18 | safety_check: None, |
| 19 | title: None, |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | fn text(role: Role, text: &str) -> Message { |
| 24 | Message { |
| 25 | role, |
| 26 | content: vec![ContentBlock::Text { |
| 27 | text: text.to_string(), |
| 28 | cache_control: None, |
| 29 | }], |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn tool_use(id: &str, name: &str, input: Value, signature: Option<&str>) -> ContentBlock { |
| 34 | ContentBlock::ToolUse { |
| 35 | id: id.to_string(), |
| 36 | name: name.to_string(), |
| 37 | input, |
| 38 | execution_id: None, |
| 39 | caller: None, |
| 40 | thought_signature: signature.map(str::to_string), |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn tool_result(tool_use_id: &str, content: &str) -> ContentBlock { |
| 45 | ContentBlock::ToolResult { |
| 46 | tool_use_id: tool_use_id.to_string(), |
| 47 | content: content.to_string(), |
| 48 | execution_id: None, |
| 49 | is_error: None, |
| 50 | content_blocks: None, |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn tool_loop_request() -> MessageRequest { |
| 55 | request(vec![ |
| 56 | text(Role::User, "list files"), |
| 57 | Message { |
| 58 | role: Role::Assistant, |
| 59 | content: vec![ |
| 60 | tool_use( |
| 61 | "call_a", |
| 62 | "list_dir", |
| 63 | json!({ "path": "." }), |
| 64 | Some("sig-list-dir"), |
| 65 | ), |
| 66 | tool_use("call_b", "read_file", json!({ "path": "README.md" }), None), |
| 67 | ], |
| 68 | }, |
| 69 | Message { |
| 70 | role: Role::User, |
| 71 | content: vec![ |
| 72 | tool_result("call_b", "readme body"), |
| 73 | tool_result("call_a", "a.rs\nb.rs"), |
| 74 | ], |
| 75 | }, |
| 76 | ]) |
| 77 | } |
| 78 | |
| 79 | fn decode_all(chunks: &[Value]) -> Vec<StreamEvent> { |
| 80 | let mut decoder = GeminiStreamDecoder::new("gemini-4-argon"); |
| 81 | let mut events: Vec<StreamEvent> = chunks |
| 82 | .iter() |
| 83 | .flat_map(|chunk| decoder.decode(chunk)) |
| 84 | .collect(); |
| 85 | events.extend(decoder.finish()); |
| 86 | events |
| 87 | } |
| 88 | |
| 89 | fn text_deltas(events: &[StreamEvent]) -> String { |
| 90 | events |
| 91 | .iter() |
| 92 | .filter_map(|event| match event { |
| 93 | StreamEvent::ContentBlockDelta { |
| 94 | delta: Delta::TextDelta { text }, |
| 95 | .. |
| 96 | } => Some(text.as_str()), |
| 97 | _ => None, |
| 98 | }) |
| 99 | .collect() |
| 100 | } |
| 101 | |
| 102 | fn stop_reason(events: &[StreamEvent]) -> Option<String> { |
| 103 | events.iter().find_map(|event| match event { |
| 104 | StreamEvent::MessageDelta { delta, .. } => delta.stop_reason.clone(), |
| 105 | _ => None, |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | #[test] |
| 110 | fn gemini_body_maps_system_and_text_turns() { |
| 111 | let mut req = request(vec![ |
| 112 | text(Role::User, "hello"), |
| 113 | text(Role::Assistant, "hi there"), |
| 114 | text(Role::User, "again"), |
| 115 | ]); |
| 116 | req.system = Some(SystemPrompt::Blocks(vec![ |
| 117 | SystemBlock { |
| 118 | block_type: "text".to_string(), |
| 119 | text: "be brief".to_string(), |
| 120 | cache_control: None, |
| 121 | }, |
| 122 | SystemBlock { |
| 123 | block_type: "text".to_string(), |
| 124 | text: "be kind".to_string(), |
| 125 | cache_control: None, |
| 126 | }, |
| 127 | ])); |
| 128 | req.temperature = Some(0.5); |
| 129 | |
| 130 | let body = build_generate_content_body(&req); |
| 131 | |
| 132 | assert_eq!( |
| 133 | body["systemInstruction"], |
| 134 | json!({ "parts": [{ "text": "be brief" }, { "text": "be kind" }] }) |
| 135 | ); |
| 136 | assert_eq!( |
| 137 | body["contents"], |
| 138 | json!([ |
| 139 | { "role": "user", "parts": [{ "text": "hello" }] }, |
| 140 | { "role": "model", "parts": [{ "text": "hi there" }] }, |
| 141 | { "role": "user", "parts": [{ "text": "again" }] }, |
| 142 | ]) |
| 143 | ); |
| 144 | assert_eq!(body["generationConfig"]["maxOutputTokens"], json!(4096)); |
| 145 | assert_eq!(body["generationConfig"]["temperature"], json!(0.5)); |
| 146 | assert!(body.get("tools").is_none()); |
| 147 | assert!(body.get("system").is_none()); |
| 148 | assert!(body.get("messages").is_none()); |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn gemini_body_text_system_prompt_and_no_temperature() { |
| 153 | let mut req = request(vec![text(Role::User, "hello")]); |
| 154 | req.system = Some(SystemPrompt::Text("sys".to_string())); |
| 155 | let body = build_generate_content_body(&req); |
| 156 | assert_eq!( |
| 157 | body["systemInstruction"], |
| 158 | json!({ "parts": [{ "text": "sys" }] }) |
| 159 | ); |
| 160 | assert!(body["generationConfig"].get("temperature").is_none()); |
| 161 | } |
| 162 | |
| 163 | #[test] |
| 164 | fn gemini_body_declares_tools_with_rejected_schema_keys_stripped() { |
| 165 | let mut req = request(vec![text(Role::User, "go")]); |
| 166 | req.tools = Some(vec![Tool { |
| 167 | tool_type: None, |
| 168 | name: "read_file".to_string(), |
| 169 | description: "Read a file".to_string(), |
| 170 | input_schema: json!({ |
| 171 | "$schema": "http://json-schema.org/draft-07/schema#", |
| 172 | "type": "object", |
| 173 | "additionalProperties": false, |
| 174 | "properties": { |
| 175 | "path": { "type": "string", "description": "file path" }, |
| 176 | "additionalProperties": { "type": "string" }, |
| 177 | "opts": { |
| 178 | "type": "object", |
| 179 | "additionalProperties": false, |
| 180 | "properties": { "limit": { "type": "integer" } } |
| 181 | }, |
| 182 | "tags": { |
| 183 | "type": "array", |
| 184 | "items": { "type": "object", "additionalProperties": true } |
| 185 | } |
| 186 | }, |
| 187 | "required": ["path"] |
| 188 | }), |
| 189 | allowed_callers: None, |
| 190 | defer_loading: None, |
| 191 | input_examples: None, |
| 192 | strict: None, |
| 193 | cache_control: None, |
| 194 | }]); |
| 195 | req.tool_choice = Some(json!({ "type": "tool", "name": "read_file" })); |
| 196 | |
| 197 | let body = build_generate_content_body(&req); |
| 198 | |
| 199 | assert_eq!( |
| 200 | body["tools"], |
| 201 | json!([{ |
| 202 | "functionDeclarations": [{ |
| 203 | "name": "read_file", |
| 204 | "description": "Read a file", |
| 205 | "parameters": { |
| 206 | "type": "object", |
| 207 | "properties": { |
| 208 | "path": { "type": "string", "description": "file path" }, |
| 209 | "additionalProperties": { "type": "string" }, |
| 210 | "opts": { |
| 211 | "type": "object", |
| 212 | "properties": { "limit": { "type": "integer" } } |
| 213 | }, |
| 214 | "tags": { "type": "array", "items": { "type": "object" } } |
| 215 | }, |
| 216 | "required": ["path"] |
| 217 | } |
| 218 | }] |
| 219 | }]) |
| 220 | ); |
| 221 | assert_eq!( |
| 222 | body["toolConfig"], |
| 223 | json!({ |
| 224 | "functionCallingConfig": { "mode": "ANY", "allowedFunctionNames": ["read_file"] } |
| 225 | }) |
| 226 | ); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn gemini_body_replays_tool_call_thought_signature() { |
| 231 | let body = build_generate_content_body(&tool_loop_request()); |
| 232 | let model_turn = &body["contents"][1]; |
| 233 | assert_eq!(model_turn["role"], "model"); |
| 234 | assert_eq!( |
| 235 | model_turn["parts"], |
| 236 | json!([ |
| 237 | { |
| 238 | "functionCall": { "name": "list_dir", "args": { "path": "." } }, |
| 239 | "thoughtSignature": "sig-list-dir" |
| 240 | }, |
| 241 | { "functionCall": { "name": "read_file", "args": { "path": "README.md" } } } |
| 242 | ]) |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn gemini_body_maps_tool_result_to_function_response_by_tool_use_name() { |
| 248 | let body = build_generate_content_body(&tool_loop_request()); |
| 249 | let result_turn = &body["contents"][2]; |
| 250 | assert_eq!(result_turn["role"], "user"); |
| 251 | assert_eq!( |
| 252 | result_turn["parts"], |
| 253 | json!([ |
| 254 | { |
| 255 | "functionResponse": { |
| 256 | "name": "read_file", |
| 257 | "response": { "content": "readme body" } |
| 258 | } |
| 259 | }, |
| 260 | { |
| 261 | "functionResponse": { |
| 262 | "name": "list_dir", |
| 263 | "response": { "content": "a.rs\nb.rs" } |
| 264 | } |
| 265 | } |
| 266 | ]) |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn gemini_body_maps_data_url_images_to_inline_data_and_merges_same_role_turns() { |
| 272 | let body = build_generate_content_body(&request(vec![ |
| 273 | text(Role::User, "what is this"), |
| 274 | Message { |
| 275 | role: Role::User, |
| 276 | content: vec![ContentBlock::ImageUrl { |
| 277 | image_url: ImageUrlContent { |
| 278 | url: "data:image/png;base64,iVBORw0KGgo=".to_string(), |
| 279 | }, |
| 280 | }], |
| 281 | }, |
| 282 | ])); |
| 283 | assert_eq!( |
| 284 | body["contents"], |
| 285 | json!([{ |
| 286 | "role": "user", |
| 287 | "parts": [ |
| 288 | { "text": "what is this" }, |
| 289 | { "inlineData": { "mimeType": "image/png", "data": "iVBORw0KGgo=" } } |
| 290 | ] |
| 291 | }]) |
| 292 | ); |
| 293 | } |
| 294 | |
| 295 | #[test] |
| 296 | fn gemini_stream_joins_text_across_three_chunks() { |
| 297 | let events = decode_all(&[ |
| 298 | json!({ "responseId": "r1", "candidates": [{ "content": { "role": "model", "parts": [{ "text": "Hel" }] } }] }), |
| 299 | json!({ "candidates": [{ "content": { "role": "model", "parts": [{ "text": "lo, " }] } }] }), |
| 300 | json!({ "candidates": [{ "content": { "role": "model", "parts": [{ "text": "world" }] }, "finishReason": "STOP" }] }), |
| 301 | ]); |
| 302 | |
| 303 | assert!( |
| 304 | matches!(events.first(), Some(StreamEvent::MessageStart { message }) if message.id == "r1") |
| 305 | ); |
| 306 | assert_eq!(text_deltas(&events), "Hello, world"); |
| 307 | let starts = events |
| 308 | .iter() |
| 309 | .filter(|event| { |
| 310 | matches!( |
| 311 | event, |
| 312 | StreamEvent::ContentBlockStart { |
| 313 | index: 0, |
| 314 | content_block: ContentBlockStart::Text { .. } |
| 315 | } |
| 316 | ) |
| 317 | }) |
| 318 | .count(); |
| 319 | assert_eq!(starts, 1); |
| 320 | let stops = events |
| 321 | .iter() |
| 322 | .filter(|event| matches!(event, StreamEvent::ContentBlockStop { index: 0 })) |
| 323 | .count(); |
| 324 | assert_eq!(stops, 1); |
| 325 | assert_eq!(stop_reason(&events).as_deref(), Some("stop")); |
| 326 | assert!(matches!(events.last(), Some(StreamEvent::MessageStop))); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn gemini_stream_routes_thought_parts_to_a_thinking_block() { |
| 331 | let events = decode_all(&[ |
| 332 | json!({ "candidates": [{ "content": { "parts": [{ "text": "pondering", "thought": true }] } }] }), |
| 333 | json!({ "candidates": [{ "content": { "parts": [{ "text": "answer" }] }, "finishReason": "STOP" }] }), |
| 334 | ]); |
| 335 | assert!(events.iter().any(|event| matches!( |
| 336 | event, |
| 337 | StreamEvent::ContentBlockStart { |
| 338 | index: 0, |
| 339 | content_block: ContentBlockStart::Thinking { .. } |
| 340 | } |
| 341 | ))); |
| 342 | assert!(events.iter().any(|event| matches!( |
| 343 | event, |
| 344 | StreamEvent::ContentBlockDelta { index: 0, delta: Delta::ThinkingDelta { thinking } } |
| 345 | if thinking == "pondering" |
| 346 | ))); |
| 347 | assert!(events.iter().any(|event| matches!( |
| 348 | event, |
| 349 | StreamEvent::ContentBlockStart { |
| 350 | index: 1, |
| 351 | content_block: ContentBlockStart::Text { .. } |
| 352 | } |
| 353 | ))); |
| 354 | assert_eq!(text_deltas(&events), "answer"); |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn gemini_stream_function_call_becomes_tool_use_with_args_and_stable_id() { |
| 359 | let chunk = json!({ |
| 360 | "responseId": "resp-9", |
| 361 | "candidates": [{ |
| 362 | "content": { "role": "model", "parts": [ |
| 363 | { "text": "Checking." }, |
| 364 | { "functionCall": { "name": "list_dir", "args": { "path": "src" } } }, |
| 365 | { "functionCall": { "name": "read_file", "args": { "path": "a.rs" } } } |
| 366 | ] }, |
| 367 | "finishReason": "STOP" |
| 368 | }] |
| 369 | }); |
| 370 | let events = decode_all(std::slice::from_ref(&chunk)); |
| 371 | let tool_starts: Vec<(u32, String, String)> = events |
| 372 | .iter() |
| 373 | .filter_map(|event| match event { |
| 374 | StreamEvent::ContentBlockStart { |
| 375 | index, |
| 376 | content_block: ContentBlockStart::ToolUse { id, name, .. }, |
| 377 | } => Some((*index, id.clone(), name.clone())), |
| 378 | _ => None, |
| 379 | }) |
| 380 | .collect(); |
| 381 | assert_eq!( |
| 382 | tool_starts, |
| 383 | vec![ |
| 384 | (1, "gemini_resp-9_1".to_string(), "list_dir".to_string()), |
| 385 | (2, "gemini_resp-9_2".to_string(), "read_file".to_string()), |
| 386 | ] |
| 387 | ); |
| 388 | let args: Vec<Value> = events |
| 389 | .iter() |
| 390 | .filter_map(|event| match event { |
| 391 | StreamEvent::ContentBlockDelta { |
| 392 | delta: Delta::InputJsonDelta { partial_json }, |
| 393 | .. |
| 394 | } => serde_json::from_str(partial_json).ok(), |
| 395 | _ => None, |
| 396 | }) |
| 397 | .collect(); |
| 398 | assert_eq!( |
| 399 | args, |
| 400 | vec![json!({ "path": "src" }), json!({ "path": "a.rs" })] |
| 401 | ); |
| 402 | assert!( |
| 403 | events |
| 404 | .iter() |
| 405 | .any(|event| matches!(event, StreamEvent::ContentBlockStop { index: 0 })) |
| 406 | ); |
| 407 | assert_eq!(stop_reason(&events).as_deref(), Some("tool_calls")); |
| 408 | |
| 409 | let again = decode_all(&[chunk]); |
| 410 | let again_ids: Vec<String> = again |
| 411 | .iter() |
| 412 | .filter_map(|event| match event { |
| 413 | StreamEvent::ContentBlockStart { |
| 414 | content_block: ContentBlockStart::ToolUse { id, .. }, |
| 415 | .. |
| 416 | } => Some(id.clone()), |
| 417 | _ => None, |
| 418 | }) |
| 419 | .collect(); |
| 420 | assert_eq!(again_ids, vec!["gemini_resp-9_1", "gemini_resp-9_2"]); |
| 421 | } |
| 422 | |
| 423 | #[test] |
| 424 | fn gemini_stream_preserves_function_call_thought_signature() { |
| 425 | let events = decode_all(&[json!({ |
| 426 | "candidates": [{ |
| 427 | "content": { "parts": [{ |
| 428 | "functionCall": { "name": "list_dir", "args": {} }, |
| 429 | "thoughtSignature": "c2lnbmF0dXJl" |
| 430 | }] }, |
| 431 | "finishReason": "STOP" |
| 432 | }] |
| 433 | })]); |
| 434 | let signature = events.iter().find_map(|event| match event { |
| 435 | StreamEvent::ContentBlockStart { |
| 436 | content_block: |
| 437 | ContentBlockStart::ToolUse { |
| 438 | thought_signature, .. |
| 439 | }, |
| 440 | .. |
| 441 | } => Some(thought_signature.clone()), |
| 442 | _ => None, |
| 443 | }); |
| 444 | assert_eq!(signature, Some(Some("c2lnbmF0dXJl".to_string()))); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn gemini_stream_maps_usage_metadata() { |
| 449 | let events = decode_all(&[json!({ |
| 450 | "candidates": [{ "content": { "parts": [{ "text": "ok" }] }, "finishReason": "STOP" }], |
| 451 | "usageMetadata": { |
| 452 | "promptTokenCount": 1200, |
| 453 | "candidatesTokenCount": 40, |
| 454 | "thoughtsTokenCount": 60, |
| 455 | "cachedContentTokenCount": 1000, |
| 456 | "totalTokenCount": 1300 |
| 457 | } |
| 458 | })]); |
| 459 | let usage = events |
| 460 | .iter() |
| 461 | .find_map(|event| match event { |
| 462 | StreamEvent::MessageDelta { usage, .. } => usage.clone(), |
| 463 | _ => None, |
| 464 | }) |
| 465 | .expect("usage"); |
| 466 | assert_eq!(usage.input_tokens, 1200); |
| 467 | assert_eq!(usage.output_tokens, 100); |
| 468 | assert_eq!(usage.reasoning_tokens, Some(60)); |
| 469 | assert_eq!(usage.prompt_cache_hit_tokens, Some(1000)); |
| 470 | assert_eq!(usage.prompt_cache_miss_tokens, Some(200)); |
| 471 | } |
| 472 | |
| 473 | #[test] |
| 474 | fn gemini_stream_usage_without_finish_reason_is_a_usage_only_delta() { |
| 475 | let events = decode_all(&[json!({ |
| 476 | "candidates": [{ "content": { "parts": [{ "text": "ok" }] } }], |
| 477 | "usageMetadata": { "promptTokenCount": 5, "candidatesTokenCount": 1 } |
| 478 | })]); |
| 479 | let delta = events.iter().find_map(|event| match event { |
| 480 | StreamEvent::MessageDelta { delta, usage } => { |
| 481 | Some((delta.stop_reason.clone(), usage.clone())) |
| 482 | } |
| 483 | _ => None, |
| 484 | }); |
| 485 | let (stop, usage) = delta.expect("usage delta"); |
| 486 | assert_eq!(stop, None); |
| 487 | let usage = usage.expect("usage"); |
| 488 | assert_eq!(usage.input_tokens, 5); |
| 489 | assert_eq!(usage.output_tokens, 1); |
| 490 | assert_eq!(usage.prompt_cache_hit_tokens, None); |
| 491 | assert_eq!(usage.reasoning_tokens, None); |
| 492 | } |
| 493 | |
| 494 | #[test] |
| 495 | fn gemini_stream_maps_each_finish_reason() { |
| 496 | for (reason, expected) in [ |
| 497 | ("STOP", "stop"), |
| 498 | ("MAX_TOKENS", "length"), |
| 499 | ("SAFETY", "content_filter"), |
| 500 | ("RECITATION", "content_filter"), |
| 501 | ("BLOCKLIST", "content_filter"), |
| 502 | ("PROHIBITED_CONTENT", "content_filter"), |
| 503 | ("SPII", "content_filter"), |
| 504 | ("IMAGE_SAFETY", "content_filter"), |
| 505 | ("LANGUAGE", "incomplete:language"), |
| 506 | ( |
| 507 | "MALFORMED_FUNCTION_CALL", |
| 508 | "incomplete:malformed_function_call", |
| 509 | ), |
| 510 | ("OTHER", "incomplete:other"), |
| 511 | ( |
| 512 | "FINISH_REASON_UNSPECIFIED", |
| 513 | "incomplete:finish_reason_unspecified", |
| 514 | ), |
| 515 | ] { |
| 516 | let events = decode_all(&[json!({ |
| 517 | "candidates": [{ "content": { "parts": [{ "text": "x" }] }, "finishReason": reason }] |
| 518 | })]); |
| 519 | let stop = stop_reason(&events); |
| 520 | assert_eq!(stop.as_deref(), Some(expected), "{reason}"); |
| 521 | if expected == "length" { |
| 522 | assert!(codewhale_models::is_output_limit_stop_reason( |
| 523 | stop.as_deref() |
| 524 | )); |
| 525 | } |
| 526 | if expected != "stop" { |
| 527 | assert!( |
| 528 | codewhale_models::is_incomplete_stop_reason(stop.as_deref()), |
| 529 | "{reason}" |
| 530 | ); |
| 531 | } |
| 532 | let refusal = events.iter().find_map(|event| match event { |
| 533 | StreamEvent::MessageDelta { delta, .. } => delta.refusal.clone(), |
| 534 | _ => None, |
| 535 | }); |
| 536 | assert_eq!(refusal.is_some(), expected == "content_filter", "{reason}"); |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | #[test] |
| 541 | fn gemini_stream_prompt_block_reason_is_a_refusal_stop() { |
| 542 | let events = decode_all(&[json!({ |
| 543 | "promptFeedback": { "blockReason": "SAFETY" }, |
| 544 | "usageMetadata": { "promptTokenCount": 9 } |
| 545 | })]); |
| 546 | assert_eq!(stop_reason(&events).as_deref(), Some("content_filter")); |
| 547 | } |
| 548 | |
| 549 | #[test] |
| 550 | fn gemini_stream_finish_closes_open_block_and_stops_once() { |
| 551 | let mut decoder = GeminiStreamDecoder::new("gemini-4-argon"); |
| 552 | let first = decoder.decode(&json!({ |
| 553 | "candidates": [{ "content": { "parts": [{ "text": "partial" }] } }] |
| 554 | })); |
| 555 | assert!(!decoder.saw_finish_reason()); |
| 556 | assert!( |
| 557 | !first |
| 558 | .iter() |
| 559 | .any(|event| matches!(event, StreamEvent::ContentBlockStop { .. })) |
| 560 | ); |
| 561 | let finished = decoder.finish(); |
| 562 | assert!(matches!( |
| 563 | finished.as_slice(), |
| 564 | [ |
| 565 | StreamEvent::ContentBlockStop { index: 0 }, |
| 566 | StreamEvent::MessageStop |
| 567 | ] |
| 568 | )); |
| 569 | assert!(decoder.finish().is_empty()); |
| 570 | } |
| 571 | |
| 572 | #[test] |
| 573 | fn gemini_error_maps_google_status_onto_llm_errors() { |
| 574 | let body = |code: u16, status: &str, message: &str| { |
| 575 | json!({ "error": { "code": code, "status": status, "message": message } }).to_string() |
| 576 | }; |
| 577 | |
| 578 | assert!(matches!( |
| 579 | map_gemini_error( |
| 580 | 400, |
| 581 | &json!({ "error": { |
| 582 | "code": 400, |
| 583 | "status": "INVALID_ARGUMENT", |
| 584 | "message": "API key not valid. Please pass a valid API key.", |
| 585 | "details": [{ "reason": "API_KEY_INVALID" }] |
| 586 | } }) |
| 587 | .to_string() |
| 588 | ), |
| 589 | LlmError::AuthenticationError(_) |
| 590 | )); |
| 591 | assert!(matches!( |
| 592 | map_gemini_error( |
| 593 | 401, |
| 594 | &body(401, "UNAUTHENTICATED", "Request had invalid credentials.") |
| 595 | ), |
| 596 | LlmError::AuthenticationError(_) |
| 597 | )); |
| 598 | assert!(matches!( |
| 599 | map_gemini_error( |
| 600 | 403, |
| 601 | &body( |
| 602 | 403, |
| 603 | "PERMISSION_DENIED", |
| 604 | "Generative Language API has not been used in project" |
| 605 | ) |
| 606 | ), |
| 607 | LlmError::AuthorizationError(_) |
| 608 | )); |
| 609 | assert!(matches!( |
| 610 | map_gemini_error( |
| 611 | 429, |
| 612 | &body( |
| 613 | 429, |
| 614 | "RESOURCE_EXHAUSTED", |
| 615 | "Resource has been exhausted (e.g. check quota)." |
| 616 | ) |
| 617 | ), |
| 618 | LlmError::RateLimited { .. } |
| 619 | )); |
| 620 | assert!(matches!( |
| 621 | map_gemini_error( |
| 622 | 400, |
| 623 | &body( |
| 624 | 400, |
| 625 | "INVALID_ARGUMENT", |
| 626 | "The input token count (1200000) exceeds the maximum number of tokens allowed (1048576)." |
| 627 | ) |
| 628 | ), |
| 629 | LlmError::ContextLengthError(_) |
| 630 | )); |
| 631 | assert!(matches!( |
| 632 | map_gemini_error( |
| 633 | 400, |
| 634 | &body(400, "INVALID_ARGUMENT", "Invalid JSON payload received.") |
| 635 | ), |
| 636 | LlmError::InvalidRequest { status: 400, .. } |
| 637 | )); |
| 638 | assert!(matches!( |
| 639 | map_gemini_error( |
| 640 | 404, |
| 641 | &body( |
| 642 | 404, |
| 643 | "NOT_FOUND", |
| 644 | "models/gemini-nope is not found for API version v1beta" |
| 645 | ) |
| 646 | ), |
| 647 | LlmError::ModelError(_) |
| 648 | )); |
| 649 | assert!(matches!( |
| 650 | map_gemini_error( |
| 651 | 500, |
| 652 | &body(500, "INTERNAL", "An internal error has occurred.") |
| 653 | ), |
| 654 | LlmError::ServerError { status: 500, .. } |
| 655 | )); |
| 656 | assert!(matches!( |
| 657 | map_gemini_error(503, &body(503, "UNAVAILABLE", "The model is overloaded.")), |
| 658 | LlmError::ServerError { status: 503, .. } |
| 659 | )); |
| 660 | assert!(matches!( |
| 661 | map_gemini_error( |
| 662 | 429, |
| 663 | &body( |
| 664 | 429, |
| 665 | "RESOURCE_EXHAUSTED", |
| 666 | "You exceeded your current quota, please check your plan and billing details." |
| 667 | ) |
| 668 | ), |
| 669 | LlmError::QuotaExhausted(_) |
| 670 | )); |
| 671 | } |
| 672 | |
| 673 | #[test] |
| 674 | fn gemini_error_rate_limit_keeps_google_retry_delay() { |
| 675 | let body = json!({ "error": { |
| 676 | "code": 429, |
| 677 | "status": "RESOURCE_EXHAUSTED", |
| 678 | "message": "Resource has been exhausted.", |
| 679 | "details": [{ |
| 680 | "@type": "type.googleapis.com/google.rpc.RetryInfo", |
| 681 | "retryDelay": "17s" |
| 682 | }] |
| 683 | } }) |
| 684 | .to_string(); |
| 685 | match map_gemini_error(429, &body) { |
| 686 | LlmError::RateLimited { retry_after, .. } => { |
| 687 | assert_eq!(retry_after, Some(std::time::Duration::from_secs(17))); |
| 688 | } |
| 689 | other => panic!("expected rate limit, got {other:?}"), |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | fn sse_body(chunks: &[Value]) -> String { |
| 694 | chunks |
| 695 | .iter() |
| 696 | .map(|chunk| format!("data: {chunk}\n\n")) |
| 697 | .collect::<Vec<_>>() |
| 698 | .join("") |
| 699 | } |
| 700 | |
| 701 | fn google_test_config(base_url: &str, model: &str) -> codewhale_runtime::config::Config { |
| 702 | let mut config = codewhale_runtime::config::Config::default(); |
| 703 | config.provider = Some("google".to_string()); |
| 704 | config.default_text_model = Some(model.to_string()); |
| 705 | config.providers = Some(codewhale_runtime::config::ProvidersConfig { |
| 706 | google: codewhale_runtime::config::ProviderConfig { |
| 707 | api_key: Some("AIzaTestKey123".to_string()), |
| 708 | base_url: Some(base_url.to_string()), |
| 709 | model: Some(model.to_string()), |
| 710 | ..codewhale_runtime::config::ProviderConfig::default() |
| 711 | }, |
| 712 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 713 | }); |
| 714 | config |
| 715 | } |
| 716 | |
| 717 | #[tokio::test] |
| 718 | async fn wiremock_direct_google_streams_text_thinking_and_uses_x_goog_api_key() { |
| 719 | use crate::llm_client::LlmClient; |
| 720 | use futures_util::StreamExt; |
| 721 | use wiremock::matchers::{header, header_exists, method, path, query_param}; |
| 722 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 723 | |
| 724 | let server = MockServer::start().await; |
| 725 | let sse = sse_body(&[ |
| 726 | json!({ |
| 727 | "responseId": "resp_g1", |
| 728 | "modelVersion": "gemini-3.1-pro-preview", |
| 729 | "candidates": [{ |
| 730 | "content": { |
| 731 | "role": "model", |
| 732 | "parts": [ |
| 733 | { "text": "thinking step", "thought": true }, |
| 734 | { "text": "hello " } |
| 735 | ] |
| 736 | } |
| 737 | }] |
| 738 | }), |
| 739 | json!({ |
| 740 | "responseId": "resp_g1", |
| 741 | "modelVersion": "gemini-3.1-pro-preview", |
| 742 | "candidates": [{ |
| 743 | "content": { "role": "model", "parts": [{ "text": "world" }] }, |
| 744 | "finishReason": "STOP" |
| 745 | }], |
| 746 | "usageMetadata": { |
| 747 | "promptTokenCount": 42, |
| 748 | "candidatesTokenCount": 10, |
| 749 | "thoughtsTokenCount": 5, |
| 750 | "cachedContentTokenCount": 12 |
| 751 | } |
| 752 | }), |
| 753 | ]); |
| 754 | |
| 755 | Mock::given(method("POST")) |
| 756 | .and(path( |
| 757 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 758 | )) |
| 759 | .and(query_param("alt", "sse")) |
| 760 | .and(header("x-goog-api-key", "AIzaTestKey123")) |
| 761 | .respond_with( |
| 762 | ResponseTemplate::new(200) |
| 763 | .insert_header("content-type", "text/event-stream") |
| 764 | .set_body_string(sse), |
| 765 | ) |
| 766 | .expect(1) |
| 767 | .mount(&server) |
| 768 | .await; |
| 769 | |
| 770 | Mock::given(header_exists("authorization")) |
| 771 | .respond_with(ResponseTemplate::new(401)) |
| 772 | .expect(0) |
| 773 | .mount(&server) |
| 774 | .await; |
| 775 | |
| 776 | let config = google_test_config( |
| 777 | &format!("{}/v1beta", server.uri()), |
| 778 | "gemini-3.1-pro-preview", |
| 779 | ); |
| 780 | let client = CodewhaleClient::new(&config).expect("google client"); |
| 781 | assert_eq!( |
| 782 | client.wire_format, |
| 783 | codewhale_config::provider::WireFormat::GenerateContent |
| 784 | ); |
| 785 | |
| 786 | let mut req = request(vec![text(Role::User, "say hi")]); |
| 787 | req.model = "gemini-3.1-pro-preview".to_string(); |
| 788 | req.system = Some(SystemPrompt::Text("be concise".to_string())); |
| 789 | let mut stream = client.create_message_stream(req).await.expect("stream"); |
| 790 | let mut events = Vec::new(); |
| 791 | while let Some(item) = stream.next().await { |
| 792 | events.push(item.expect("event")); |
| 793 | } |
| 794 | |
| 795 | assert!(events.iter().any(|e| matches!( |
| 796 | e, |
| 797 | StreamEvent::ContentBlockDelta { delta: Delta::ThinkingDelta { thinking }, .. } |
| 798 | if thinking == "thinking step" |
| 799 | ))); |
| 800 | let collected_text: String = events |
| 801 | .iter() |
| 802 | .filter_map(|e| match e { |
| 803 | StreamEvent::ContentBlockDelta { |
| 804 | delta: Delta::TextDelta { text }, |
| 805 | .. |
| 806 | } => Some(text.as_str()), |
| 807 | _ => None, |
| 808 | }) |
| 809 | .collect(); |
| 810 | assert_eq!(collected_text, "hello world"); |
| 811 | assert!(events.iter().any(|e| matches!( |
| 812 | e, |
| 813 | StreamEvent::MessageDelta { delta, usage: Some(u) } |
| 814 | if delta.stop_reason.as_deref() == Some("stop") |
| 815 | && u.input_tokens == 42 |
| 816 | && u.output_tokens == 15 |
| 817 | && u.reasoning_tokens == Some(5) |
| 818 | && u.prompt_cache_hit_tokens == Some(12) |
| 819 | ))); |
| 820 | assert!(matches!(events.last(), Some(StreamEvent::MessageStop))); |
| 821 | |
| 822 | let received = server.received_requests().await.expect("requests"); |
| 823 | assert_eq!(received.len(), 1); |
| 824 | let sent_body: Value = serde_json::from_slice(&received[0].body).expect("json body"); |
| 825 | assert_eq!( |
| 826 | sent_body["systemInstruction"]["parts"][0]["text"], |
| 827 | "be concise" |
| 828 | ); |
| 829 | assert_eq!(sent_body["contents"][0]["role"], "user"); |
| 830 | assert_eq!(sent_body["contents"][0]["parts"][0]["text"], "say hi"); |
| 831 | } |
| 832 | |
| 833 | #[tokio::test] |
| 834 | async fn wiremock_tool_round_trip_replays_thought_signature_and_function_name() { |
| 835 | use crate::llm_client::LlmClient; |
| 836 | use wiremock::matchers::{method, path, query_param}; |
| 837 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 838 | |
| 839 | let server = MockServer::start().await; |
| 840 | let turn1_sse = sse_body(&[json!({ |
| 841 | "responseId": "resp_tool_1", |
| 842 | "modelVersion": "gemini-3.1-pro-preview", |
| 843 | "candidates": [{ |
| 844 | "content": { |
| 845 | "role": "model", |
| 846 | "parts": [{ |
| 847 | "functionCall": { "name": "read_file", "args": { "path": "Cargo.toml" } }, |
| 848 | "thoughtSignature": "sig_opaque_roundtrip" |
| 849 | }] |
| 850 | }, |
| 851 | "finishReason": "STOP" |
| 852 | }] |
| 853 | })]); |
| 854 | let turn2_sse = sse_body(&[json!({ |
| 855 | "responseId": "resp_tool_2", |
| 856 | "modelVersion": "gemini-3.1-pro-preview", |
| 857 | "candidates": [{ |
| 858 | "content": { |
| 859 | "role": "model", |
| 860 | "parts": [{ "text": "version is 0.10.5" }] |
| 861 | }, |
| 862 | "finishReason": "STOP" |
| 863 | }] |
| 864 | })]); |
| 865 | |
| 866 | Mock::given(method("POST")) |
| 867 | .and(path( |
| 868 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 869 | )) |
| 870 | .and(query_param("alt", "sse")) |
| 871 | .respond_with( |
| 872 | ResponseTemplate::new(200) |
| 873 | .insert_header("content-type", "text/event-stream") |
| 874 | .set_body_string(turn1_sse), |
| 875 | ) |
| 876 | .up_to_n_times(1) |
| 877 | .mount(&server) |
| 878 | .await; |
| 879 | |
| 880 | Mock::given(method("POST")) |
| 881 | .and(path( |
| 882 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 883 | )) |
| 884 | .and(query_param("alt", "sse")) |
| 885 | .respond_with( |
| 886 | ResponseTemplate::new(200) |
| 887 | .insert_header("content-type", "text/event-stream") |
| 888 | .set_body_string(turn2_sse), |
| 889 | ) |
| 890 | .up_to_n_times(1) |
| 891 | .mount(&server) |
| 892 | .await; |
| 893 | |
| 894 | let config = google_test_config( |
| 895 | &format!("{}/v1beta", server.uri()), |
| 896 | "gemini-3.1-pro-preview", |
| 897 | ); |
| 898 | let client = CodewhaleClient::new(&config).expect("google client"); |
| 899 | |
| 900 | let mut req1 = request(vec![text(Role::User, "read Cargo.toml")]); |
| 901 | req1.model = "gemini-3.1-pro-preview".to_string(); |
| 902 | req1.tools = Some(vec![Tool { |
| 903 | name: "read_file".to_string(), |
| 904 | description: "Read a file".to_string(), |
| 905 | input_schema: json!({ |
| 906 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 907 | "type": "object", |
| 908 | "additionalProperties": false, |
| 909 | "properties": { "path": { "type": "string" } }, |
| 910 | "required": ["path"] |
| 911 | }), |
| 912 | strict: None, |
| 913 | cache_control: None, |
| 914 | tool_type: None, |
| 915 | allowed_callers: None, |
| 916 | defer_loading: None, |
| 917 | input_examples: None, |
| 918 | }]); |
| 919 | |
| 920 | let resp1 = client.create_message(req1).await.expect("turn 1"); |
| 921 | assert_eq!(resp1.stop_reason.as_deref(), Some("tool_calls")); |
| 922 | let (call_id, call_name, call_sig) = match resp1.content.first() { |
| 923 | Some(ContentBlock::ToolUse { |
| 924 | id, |
| 925 | name, |
| 926 | input, |
| 927 | thought_signature, |
| 928 | .. |
| 929 | }) => { |
| 930 | assert_eq!(input, &json!({ "path": "Cargo.toml" })); |
| 931 | (id.clone(), name.clone(), thought_signature.clone()) |
| 932 | } |
| 933 | other => panic!("expected tool_use, got {other:?}"), |
| 934 | }; |
| 935 | assert_eq!(call_name, "read_file"); |
| 936 | assert_eq!(call_sig.as_deref(), Some("sig_opaque_roundtrip")); |
| 937 | |
| 938 | let mut req2 = request(vec![ |
| 939 | text(Role::User, "read Cargo.toml"), |
| 940 | Message { |
| 941 | role: Role::Assistant, |
| 942 | content: resp1.content, |
| 943 | }, |
| 944 | Message { |
| 945 | role: Role::User, |
| 946 | content: vec![tool_result(&call_id, "version = \"0.10.5\"")], |
| 947 | }, |
| 948 | ]); |
| 949 | req2.model = "gemini-3.1-pro-preview".to_string(); |
| 950 | let resp2 = client.create_message(req2).await.expect("turn 2"); |
| 951 | assert_eq!(resp2.stop_reason.as_deref(), Some("stop")); |
| 952 | assert!(matches!( |
| 953 | resp2.content.first(), |
| 954 | Some(ContentBlock::Text { text, .. }) if text == "version is 0.10.5" |
| 955 | )); |
| 956 | |
| 957 | let received = server.received_requests().await.expect("requests"); |
| 958 | assert_eq!(received.len(), 2); |
| 959 | let body2: Value = serde_json::from_slice(&received[1].body).expect("turn 2 json"); |
| 960 | assert_eq!( |
| 961 | body2["contents"][1]["parts"][0]["thoughtSignature"], |
| 962 | "sig_opaque_roundtrip" |
| 963 | ); |
| 964 | assert_eq!( |
| 965 | body2["contents"][2]["parts"][0]["functionResponse"]["name"], |
| 966 | "read_file" |
| 967 | ); |
| 968 | } |
| 969 | |
| 970 | #[tokio::test] |
| 971 | async fn wiremock_maps_api_key_invalid_safety_refusal_and_truncated_stream() { |
| 972 | use crate::llm_client::LlmClient; |
| 973 | use wiremock::matchers::{method, path}; |
| 974 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 975 | |
| 976 | let server = MockServer::start().await; |
| 977 | Mock::given(method("POST")) |
| 978 | .and(path( |
| 979 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 980 | )) |
| 981 | .respond_with(ResponseTemplate::new(400).set_body_json(json!({ |
| 982 | "error": { |
| 983 | "code": 400, |
| 984 | "status": "INVALID_ARGUMENT", |
| 985 | "message": "API key not valid. Please pass a valid API key.", |
| 986 | "details": [{ "reason": "API_KEY_INVALID" }] |
| 987 | } |
| 988 | }))) |
| 989 | .up_to_n_times(1) |
| 990 | .mount(&server) |
| 991 | .await; |
| 992 | |
| 993 | let config = google_test_config( |
| 994 | &format!("{}/v1beta", server.uri()), |
| 995 | "gemini-3.1-pro-preview", |
| 996 | ); |
| 997 | let client = CodewhaleClient::new(&config).expect("google client"); |
| 998 | let mut req = request(vec![text(Role::User, "hello")]); |
| 999 | req.model = "gemini-3.1-pro-preview".to_string(); |
| 1000 | |
| 1001 | let err = client |
| 1002 | .create_message(req.clone()) |
| 1003 | .await |
| 1004 | .expect_err("invalid api key must fail"); |
| 1005 | let llm_err = err |
| 1006 | .downcast_ref::<LlmError>() |
| 1007 | .expect("downcastable LlmError"); |
| 1008 | assert!(matches!(llm_err, LlmError::AuthenticationError(_))); |
| 1009 | |
| 1010 | let safety_sse = sse_body(&[json!({ |
| 1011 | "responseId": "resp_safety", |
| 1012 | "candidates": [{ |
| 1013 | "finishReason": "SAFETY", |
| 1014 | "finishMessage": "Blocked by safety filter" |
| 1015 | }] |
| 1016 | })]); |
| 1017 | Mock::given(method("POST")) |
| 1018 | .and(path( |
| 1019 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 1020 | )) |
| 1021 | .respond_with( |
| 1022 | ResponseTemplate::new(200) |
| 1023 | .insert_header("content-type", "text/event-stream") |
| 1024 | .set_body_string(safety_sse), |
| 1025 | ) |
| 1026 | .up_to_n_times(1) |
| 1027 | .mount(&server) |
| 1028 | .await; |
| 1029 | |
| 1030 | let safety_resp = client.create_message(req.clone()).await.expect("safety"); |
| 1031 | assert_eq!(safety_resp.stop_reason.as_deref(), Some("content_filter")); |
| 1032 | assert_eq!( |
| 1033 | safety_resp.refusal.as_deref(), |
| 1034 | Some("Blocked by safety filter") |
| 1035 | ); |
| 1036 | |
| 1037 | let truncated_sse = sse_body(&[json!({ |
| 1038 | "responseId": "resp_trunc", |
| 1039 | "candidates": [{ |
| 1040 | "content": { "role": "model", "parts": [{ "text": "partial" }] } |
| 1041 | }] |
| 1042 | })]); |
| 1043 | Mock::given(method("POST")) |
| 1044 | .and(path( |
| 1045 | "/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent", |
| 1046 | )) |
| 1047 | .respond_with( |
| 1048 | ResponseTemplate::new(200) |
| 1049 | .insert_header("content-type", "text/event-stream") |
| 1050 | .set_body_string(truncated_sse), |
| 1051 | ) |
| 1052 | .up_to_n_times(1) |
| 1053 | .mount(&server) |
| 1054 | .await; |
| 1055 | |
| 1056 | let trunc_err = client |
| 1057 | .create_message(req) |
| 1058 | .await |
| 1059 | .expect_err("truncated stream must fail closed"); |
| 1060 | assert!( |
| 1061 | trunc_err.to_string().contains("closed before finishReason"), |
| 1062 | "unexpected error: {trunc_err:#}" |
| 1063 | ); |
| 1064 | } |
| 1065 | |
| 1066 | #[tokio::test] |
| 1067 | async fn wiremock_opencode_go_catalog_generate_content_resolves_and_dispatches_with_bearer() { |
| 1068 | use crate::llm_client::LlmClient; |
| 1069 | use codewhale_config::ProviderKind; |
| 1070 | use codewhale_config::route::{LogicalModelRef, RequestProtocol, RouteRequest, RouteResolver}; |
| 1071 | use wiremock::matchers::{header, header_exists, method, path, query_param}; |
| 1072 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 1073 | |
| 1074 | let server = MockServer::start().await; |
| 1075 | let base = format!("{}/inference/go/v1", server.uri()); |
| 1076 | let catalog_json = json!({ |
| 1077 | "data": [{ |
| 1078 | "id": "gemini-4-argon", |
| 1079 | "type": "chat", |
| 1080 | "name": "Gemini 4 Argon", |
| 1081 | "api": { |
| 1082 | "generate-content": { "base_url": base } |
| 1083 | }, |
| 1084 | "capabilities": { "reasoning": true, "tools": true }, |
| 1085 | "limit": { "context": 1048576, "output": 65536 } |
| 1086 | }] |
| 1087 | }) |
| 1088 | .to_string(); |
| 1089 | |
| 1090 | let offerings = super::super::opencode_catalog::parse( |
| 1091 | &catalog_json, |
| 1092 | "opencode-go", |
| 1093 | &base, |
| 1094 | "fp_go", |
| 1095 | 100, |
| 1096 | &[], |
| 1097 | ) |
| 1098 | .expect("catalog parses") |
| 1099 | .expect("typed offerings"); |
| 1100 | assert_eq!(offerings.len(), 1); |
| 1101 | assert_eq!(offerings[0].endpoint_key, "generate-content"); |
| 1102 | assert_eq!(offerings[0].provider_api.as_deref(), Some(base.as_str())); |
| 1103 | |
| 1104 | let mut models = std::collections::BTreeMap::new(); |
| 1105 | models.insert( |
| 1106 | "gemini-4-argon".to_string(), |
| 1107 | ("generate-content".to_string(), base.clone()), |
| 1108 | ); |
| 1109 | let resolver = RouteResolver::from_offerings( |
| 1110 | offerings |
| 1111 | .iter() |
| 1112 | .map(super::super::CatalogOffering::to_offering) |
| 1113 | .collect(), |
| 1114 | ) |
| 1115 | .with_go_catalog_routes("opencode-go", "test".to_string(), &base, models); |
| 1116 | let candidate = resolver |
| 1117 | .resolve_with_endpoint_catalog_authority(&RouteRequest { |
| 1118 | explicit_provider: Some(ProviderKind::OpencodeGo), |
| 1119 | model_selector: Some(LogicalModelRef::from("gemini-4-argon")), |
| 1120 | base_url_override: Some(base.clone()), |
| 1121 | ..RouteRequest::default() |
| 1122 | }) |
| 1123 | .expect("go generate-content route resolves"); |
| 1124 | assert_eq!(candidate.protocol(), RequestProtocol::GenerateContent); |
| 1125 | |
| 1126 | let sse = sse_body(&[json!({ |
| 1127 | "responseId": "resp_go_1", |
| 1128 | "modelVersion": "gemini-4-argon", |
| 1129 | "candidates": [{ |
| 1130 | "content": { "role": "model", "parts": [{ "text": "go native ok" }] }, |
| 1131 | "finishReason": "STOP" |
| 1132 | }] |
| 1133 | })]); |
| 1134 | |
| 1135 | Mock::given(method("POST")) |
| 1136 | .and(path( |
| 1137 | "/inference/go/v1/models/gemini-4-argon:streamGenerateContent", |
| 1138 | )) |
| 1139 | .and(query_param("alt", "sse")) |
| 1140 | .and(header("authorization", "Bearer go_test_token")) |
| 1141 | .respond_with( |
| 1142 | ResponseTemplate::new(200) |
| 1143 | .insert_header("content-type", "text/event-stream") |
| 1144 | .set_body_string(sse), |
| 1145 | ) |
| 1146 | .expect(1) |
| 1147 | .mount(&server) |
| 1148 | .await; |
| 1149 | |
| 1150 | Mock::given(header_exists("x-goog-api-key")) |
| 1151 | .respond_with(ResponseTemplate::new(400)) |
| 1152 | .expect(0) |
| 1153 | .mount(&server) |
| 1154 | .await; |
| 1155 | |
| 1156 | let mut config = codewhale_runtime::config::Config::default(); |
| 1157 | config.provider = Some("opencode-go".to_string()); |
| 1158 | config.default_text_model = Some("gemini-4-argon".to_string()); |
| 1159 | config.providers = Some(codewhale_runtime::config::ProvidersConfig { |
| 1160 | opencode_go: codewhale_runtime::config::ProviderConfig { |
| 1161 | api_key: Some("go_test_token".to_string()), |
| 1162 | base_url: Some(base.clone()), |
| 1163 | model: Some("gemini-4-argon".to_string()), |
| 1164 | ..codewhale_runtime::config::ProviderConfig::default() |
| 1165 | }, |
| 1166 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 1167 | }); |
| 1168 | let admitted = CodewhaleClient::admit_client_route(&config, base.clone()).expect("admit"); |
| 1169 | let captured = CodewhaleClient::capture_route_preflight_inputs( |
| 1170 | &config, |
| 1171 | &admitted.identity, |
| 1172 | &admitted.base_url, |
| 1173 | ) |
| 1174 | .expect("preflight"); |
| 1175 | let mut client = CodewhaleClient::from_admitted( |
| 1176 | &config, |
| 1177 | admitted, |
| 1178 | captured, |
| 1179 | "gemini-4-argon".to_string(), |
| 1180 | codewhale_config::provider::WireFormat::GenerateContent, |
| 1181 | None, |
| 1182 | None, |
| 1183 | false, |
| 1184 | ) |
| 1185 | .expect("opencode go client"); |
| 1186 | client.go_route = None; |
| 1187 | let resp = client |
| 1188 | .create_message(request(vec![text(Role::User, "ping")])) |
| 1189 | .await |
| 1190 | .expect("opencode go generate-content dispatch"); |
| 1191 | assert!(matches!( |
| 1192 | resp.content.first(), |
| 1193 | Some(ContentBlock::Text { text, .. }) if text == "go native ok" |
| 1194 | )); |
| 1195 | } |
| 1196 |