| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use anyhow::{Context, Result}; |
| 4 | use serde_json::{Map, Value, json}; |
| 5 | |
| 6 | use codewhale_models::{ |
| 7 | ContentBlock, ContentBlockStart, Delta, MessageDelta, MessageRequest, MessageResponse, Role, |
| 8 | StreamEvent, SystemPrompt, Usage, |
| 9 | }; |
| 10 | use codewhale_runtime::logging; |
| 11 | |
| 12 | use super::CodewhaleClient; |
| 13 | use super::wire::{ |
| 14 | extract_sse_data_value, from_api_tool_name, next_sse_line, push_sse_event_data, |
| 15 | to_api_tool_name, |
| 16 | }; |
| 17 | use crate::llm_client::{LlmError, StreamEventBox}; |
| 18 | |
| 19 | const GEMINI_REJECTED_SCHEMA_KEYS: &[&str] = &["$schema", "additionalProperties"]; |
| 20 | |
| 21 | pub fn build_generate_content_body(request: &MessageRequest) -> Value { |
| 22 | let mut body = Map::new(); |
| 23 | |
| 24 | if let Some(system) = system_instruction(request.system.as_ref()) { |
| 25 | body.insert("systemInstruction".into(), system); |
| 26 | } |
| 27 | |
| 28 | body.insert("contents".into(), Value::Array(contents(request))); |
| 29 | |
| 30 | let declarations = function_declarations(request); |
| 31 | if !declarations.is_empty() { |
| 32 | body.insert( |
| 33 | "tools".into(), |
| 34 | json!([{ "functionDeclarations": declarations }]), |
| 35 | ); |
| 36 | if let Some(config) = request.tool_choice.as_ref().and_then(tool_config) { |
| 37 | body.insert("toolConfig".into(), config); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | let mut generation = Map::new(); |
| 42 | if request.max_tokens > 0 { |
| 43 | generation.insert("maxOutputTokens".into(), json!(request.max_tokens)); |
| 44 | } |
| 45 | if let Some(temperature) = request.temperature { |
| 46 | generation.insert("temperature".into(), json!(temperature)); |
| 47 | } |
| 48 | if let Some(top_p) = request.top_p { |
| 49 | generation.insert("topP".into(), json!(top_p)); |
| 50 | } |
| 51 | if !generation.is_empty() { |
| 52 | body.insert("generationConfig".into(), Value::Object(generation)); |
| 53 | } |
| 54 | |
| 55 | Value::Object(body) |
| 56 | } |
| 57 | |
| 58 | fn system_instruction(system: Option<&SystemPrompt>) -> Option<Value> { |
| 59 | let parts: Vec<Value> = match system? { |
| 60 | SystemPrompt::Text(text) => vec![text.clone()], |
| 61 | SystemPrompt::Blocks(blocks) => blocks.iter().map(|block| block.text.clone()).collect(), |
| 62 | } |
| 63 | .into_iter() |
| 64 | .filter(|text| !text.is_empty()) |
| 65 | .map(|text| json!({ "text": text })) |
| 66 | .collect(); |
| 67 | (!parts.is_empty()).then(|| json!({ "parts": parts })) |
| 68 | } |
| 69 | |
| 70 | fn gemini_role(role: &Role) -> &'static str { |
| 71 | match role { |
| 72 | Role::Assistant | Role::InterruptedAssistant => "model", |
| 73 | Role::User |
| 74 | | Role::System |
| 75 | | Role::Developer |
| 76 | | Role::LatestReminder |
| 77 | | Role::Unrecognized(_) => "user", |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn contents(request: &MessageRequest) -> Vec<Value> { |
| 82 | let tool_names: HashMap<&str, &str> = request |
| 83 | .messages |
| 84 | .iter() |
| 85 | .flat_map(|message| message.content.iter()) |
| 86 | .filter_map(|block| match block { |
| 87 | ContentBlock::ToolUse { id, name, .. } => Some((id.as_str(), name.as_str())), |
| 88 | _ => None, |
| 89 | }) |
| 90 | .collect(); |
| 91 | |
| 92 | let mut turns: Vec<(&'static str, Vec<Value>)> = Vec::new(); |
| 93 | for message in &request.messages { |
| 94 | let role = gemini_role(&message.role); |
| 95 | let mut parts: Vec<Value> = message |
| 96 | .content |
| 97 | .iter() |
| 98 | .flat_map(|block| block_parts(block, &tool_names)) |
| 99 | .collect(); |
| 100 | if message.role == Role::InterruptedAssistant |
| 101 | && let Some(text) = parts.iter_mut().find_map(|part| part.get_mut("text")) |
| 102 | { |
| 103 | let existing = text.as_str().unwrap_or_default(); |
| 104 | *text = json!(format!( |
| 105 | "{}{existing}", |
| 106 | codewhale_models::INTERRUPTED_ASSISTANT_CONTEXT_PREFIX |
| 107 | )); |
| 108 | } |
| 109 | if parts.is_empty() { |
| 110 | continue; |
| 111 | } |
| 112 | match turns.last_mut() { |
| 113 | Some((last_role, last_parts)) if *last_role == role => last_parts.append(&mut parts), |
| 114 | _ => turns.push((role, parts)), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | turns |
| 119 | .into_iter() |
| 120 | .map(|(role, parts)| json!({ "role": role, "parts": parts })) |
| 121 | .collect() |
| 122 | } |
| 123 | |
| 124 | fn block_parts(block: &ContentBlock, tool_names: &HashMap<&str, &str>) -> Vec<Value> { |
| 125 | match block { |
| 126 | ContentBlock::Text { text, .. } if !text.is_empty() => vec![json!({ "text": text })], |
| 127 | ContentBlock::ImageUrl { image_url } => vec![image_part(&image_url.url)], |
| 128 | ContentBlock::ToolUse { |
| 129 | name, |
| 130 | input, |
| 131 | thought_signature, |
| 132 | .. |
| 133 | } => { |
| 134 | let mut part = json!({ |
| 135 | "functionCall": { "name": to_api_tool_name(name), "args": function_args(input) } |
| 136 | }); |
| 137 | if let Some(signature) = thought_signature.as_deref().filter(|s| !s.is_empty()) { |
| 138 | part["thoughtSignature"] = json!(signature); |
| 139 | } |
| 140 | vec![part] |
| 141 | } |
| 142 | ContentBlock::ToolResult { |
| 143 | tool_use_id, |
| 144 | content, |
| 145 | is_error, |
| 146 | content_blocks, |
| 147 | .. |
| 148 | } => { |
| 149 | let name = tool_names |
| 150 | .get(tool_use_id.as_str()) |
| 151 | .copied() |
| 152 | .unwrap_or(tool_use_id.as_str()); |
| 153 | let (image, omitted) = |
| 154 | crate::image_attach::provider_tool_result_image_refs(content_blocks.as_deref()); |
| 155 | let content = |
| 156 | codewhale_models::image_window::tool_result_text_with_omission(content, omitted); |
| 157 | let mut response = json!({ "content": content }); |
| 158 | if *is_error == Some(true) { |
| 159 | response["is_error"] = json!(true); |
| 160 | } |
| 161 | let mut parts = vec![json!({ |
| 162 | "functionResponse": { "name": to_api_tool_name(name), "response": response } |
| 163 | })]; |
| 164 | if let Some((mime_type, data)) = image { |
| 165 | parts.push(json!({ "inlineData": { "mimeType": mime_type, "data": data } })); |
| 166 | } |
| 167 | parts |
| 168 | } |
| 169 | _ => Vec::new(), |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | fn function_args(input: &Value) -> Value { |
| 174 | if input.is_object() { |
| 175 | input.clone() |
| 176 | } else { |
| 177 | json!({}) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | fn image_part(url: &str) -> Value { |
| 182 | if let Some((mime_type, data)) = codewhale_models::image_window::parse_data_url(url) { |
| 183 | return json!({ "inlineData": { "mimeType": mime_type, "data": data } }); |
| 184 | } |
| 185 | json!({ "text": format!("[unsupported image reference: {url}]") }) |
| 186 | } |
| 187 | |
| 188 | fn function_declarations(request: &MessageRequest) -> Vec<Value> { |
| 189 | request |
| 190 | .tools |
| 191 | .iter() |
| 192 | .flatten() |
| 193 | .filter(|tool| { |
| 194 | tool.tool_type |
| 195 | .as_deref() |
| 196 | .is_none_or(|kind| kind == "function") |
| 197 | }) |
| 198 | .map(|tool| { |
| 199 | let mut parameters = tool.input_schema.clone(); |
| 200 | strip_rejected_schema_keys(&mut parameters); |
| 201 | let mut declaration = json!({ |
| 202 | "name": to_api_tool_name(&tool.name), |
| 203 | "description": tool.description, |
| 204 | }); |
| 205 | if parameters |
| 206 | .as_object() |
| 207 | .is_some_and(|object| !object.is_empty()) |
| 208 | { |
| 209 | declaration["parameters"] = parameters; |
| 210 | } |
| 211 | declaration |
| 212 | }) |
| 213 | .collect() |
| 214 | } |
| 215 | |
| 216 | fn strip_rejected_schema_keys(schema: &mut Value) { |
| 217 | match schema { |
| 218 | Value::Object(object) => { |
| 219 | for key in GEMINI_REJECTED_SCHEMA_KEYS { |
| 220 | object.remove(*key); |
| 221 | } |
| 222 | for (key, child) in object.iter_mut() { |
| 223 | if key == "properties" |
| 224 | && let Some(properties) = child.as_object_mut() |
| 225 | { |
| 226 | properties.values_mut().for_each(strip_rejected_schema_keys); |
| 227 | } else { |
| 228 | strip_rejected_schema_keys(child); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | Value::Array(items) => items.iter_mut().for_each(strip_rejected_schema_keys), |
| 233 | _ => {} |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn tool_config(tool_choice: &Value) -> Option<Value> { |
| 238 | if let Some(name) = codewhale_models::tool_projection::forced_tool_name(tool_choice) { |
| 239 | return Some(json!({ |
| 240 | "functionCallingConfig": { |
| 241 | "mode": "ANY", |
| 242 | "allowedFunctionNames": [to_api_tool_name(name)], |
| 243 | } |
| 244 | })); |
| 245 | } |
| 246 | let choice = tool_choice |
| 247 | .as_str() |
| 248 | .or_else(|| tool_choice.get("type").and_then(Value::as_str))?; |
| 249 | let mode = match choice { |
| 250 | "auto" => "AUTO", |
| 251 | "none" => "NONE", |
| 252 | "any" | "required" => "ANY", |
| 253 | _ => return None, |
| 254 | }; |
| 255 | Some(json!({ "functionCallingConfig": { "mode": mode } })) |
| 256 | } |
| 257 | |
| 258 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 259 | enum OpenBlock { |
| 260 | Text(u32), |
| 261 | Thinking(u32), |
| 262 | } |
| 263 | |
| 264 | #[derive(Debug)] |
| 265 | pub struct GeminiStreamDecoder { |
| 266 | model: String, |
| 267 | started: bool, |
| 268 | next_index: u32, |
| 269 | open: Option<OpenBlock>, |
| 270 | response_id: Option<String>, |
| 271 | stream_nonce: String, |
| 272 | tool_calls: u32, |
| 273 | finished: bool, |
| 274 | stopped: bool, |
| 275 | } |
| 276 | |
| 277 | impl GeminiStreamDecoder { |
| 278 | pub fn new(model: impl Into<String>) -> Self { |
| 279 | Self { |
| 280 | model: model.into(), |
| 281 | started: false, |
| 282 | next_index: 0, |
| 283 | open: None, |
| 284 | response_id: None, |
| 285 | stream_nonce: uuid::Uuid::new_v4().simple().to_string(), |
| 286 | tool_calls: 0, |
| 287 | finished: false, |
| 288 | stopped: false, |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | pub fn decode(&mut self, chunk: &Value) -> Vec<StreamEvent> { |
| 293 | let mut events = Vec::new(); |
| 294 | if self.stopped { |
| 295 | return events; |
| 296 | } |
| 297 | if !self.started { |
| 298 | self.started = true; |
| 299 | self.response_id = chunk |
| 300 | .get("responseId") |
| 301 | .and_then(Value::as_str) |
| 302 | .map(str::to_string); |
| 303 | let model = chunk |
| 304 | .get("modelVersion") |
| 305 | .and_then(Value::as_str) |
| 306 | .unwrap_or(&self.model) |
| 307 | .to_string(); |
| 308 | events.push(StreamEvent::MessageStart { |
| 309 | message: MessageResponse { |
| 310 | tool_projection_warning: None, |
| 311 | id: self.response_id.clone().unwrap_or_default(), |
| 312 | r#type: "message".to_string(), |
| 313 | role: "assistant".to_string(), |
| 314 | content: Vec::new(), |
| 315 | model, |
| 316 | stop_reason: None, |
| 317 | stop_sequence: None, |
| 318 | container: None, |
| 319 | usage: Usage::default(), |
| 320 | title: None, |
| 321 | stop_details: None, |
| 322 | refusal: None, |
| 323 | }, |
| 324 | }); |
| 325 | } |
| 326 | |
| 327 | let candidate = chunk |
| 328 | .get("candidates") |
| 329 | .and_then(Value::as_array) |
| 330 | .and_then(|candidates| candidates.first()); |
| 331 | |
| 332 | if let Some(parts) = candidate |
| 333 | .and_then(|candidate| candidate.pointer("/content/parts")) |
| 334 | .and_then(Value::as_array) |
| 335 | { |
| 336 | for part in parts { |
| 337 | self.decode_part(part, &mut events); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | let usage = chunk.get("usageMetadata").map(gemini_usage); |
| 342 | let finish = candidate |
| 343 | .and_then(|candidate| candidate.get("finishReason")) |
| 344 | .and_then(Value::as_str) |
| 345 | .filter(|reason| !reason.is_empty()); |
| 346 | let blocked = chunk |
| 347 | .pointer("/promptFeedback/blockReason") |
| 348 | .and_then(Value::as_str) |
| 349 | .filter(|reason| !reason.is_empty()); |
| 350 | |
| 351 | if let Some(reason) = finish.or(blocked) { |
| 352 | self.close_open(&mut events); |
| 353 | let stop_reason = map_finish_reason(reason, self.tool_calls > 0); |
| 354 | let refusal = codewhale_models::is_refusal_stop_reason(Some(&stop_reason)).then(|| { |
| 355 | candidate |
| 356 | .and_then(|candidate| candidate.get("finishMessage")) |
| 357 | .and_then(Value::as_str) |
| 358 | .map_or_else(|| format!("Gemini stopped: {reason}"), str::to_string) |
| 359 | }); |
| 360 | self.finished = true; |
| 361 | events.push(StreamEvent::MessageDelta { |
| 362 | delta: MessageDelta { |
| 363 | stop_reason: Some(stop_reason), |
| 364 | stop_sequence: None, |
| 365 | title: None, |
| 366 | stop_details: None, |
| 367 | refusal, |
| 368 | }, |
| 369 | usage, |
| 370 | }); |
| 371 | } else if let Some(usage) = usage { |
| 372 | events.push(StreamEvent::MessageDelta { |
| 373 | delta: MessageDelta::default(), |
| 374 | usage: Some(usage), |
| 375 | }); |
| 376 | } |
| 377 | |
| 378 | events |
| 379 | } |
| 380 | |
| 381 | pub fn finish(&mut self) -> Vec<StreamEvent> { |
| 382 | let mut events = Vec::new(); |
| 383 | if self.stopped { |
| 384 | return events; |
| 385 | } |
| 386 | self.stopped = true; |
| 387 | self.close_open(&mut events); |
| 388 | events.push(StreamEvent::MessageStop); |
| 389 | events |
| 390 | } |
| 391 | |
| 392 | pub fn saw_finish_reason(&self) -> bool { |
| 393 | self.finished |
| 394 | } |
| 395 | |
| 396 | fn decode_part(&mut self, part: &Value, events: &mut Vec<StreamEvent>) { |
| 397 | if let Some(call) = part.get("functionCall") { |
| 398 | self.close_open(events); |
| 399 | let index = self.next_index; |
| 400 | self.next_index += 1; |
| 401 | self.tool_calls += 1; |
| 402 | let id = call |
| 403 | .get("id") |
| 404 | .and_then(Value::as_str) |
| 405 | .filter(|id| !id.is_empty()) |
| 406 | .map_or_else(|| self.generated_call_id(), str::to_string); |
| 407 | let name = from_api_tool_name(call.get("name").and_then(Value::as_str).unwrap_or("")); |
| 408 | let args = call |
| 409 | .get("args") |
| 410 | .filter(|args| args.is_object()) |
| 411 | .cloned() |
| 412 | .unwrap_or_else(|| json!({})); |
| 413 | let thought_signature = part |
| 414 | .get("thoughtSignature") |
| 415 | .and_then(Value::as_str) |
| 416 | .filter(|signature| !signature.is_empty()) |
| 417 | .map(str::to_string); |
| 418 | events.push(StreamEvent::ContentBlockStart { |
| 419 | index, |
| 420 | content_block: ContentBlockStart::ToolUse { |
| 421 | id, |
| 422 | name, |
| 423 | input: json!({}), |
| 424 | caller: None, |
| 425 | thought_signature, |
| 426 | }, |
| 427 | }); |
| 428 | events.push(StreamEvent::ContentBlockDelta { |
| 429 | index, |
| 430 | delta: Delta::InputJsonDelta { |
| 431 | partial_json: args.to_string(), |
| 432 | }, |
| 433 | }); |
| 434 | events.push(StreamEvent::ContentBlockStop { index }); |
| 435 | return; |
| 436 | } |
| 437 | |
| 438 | let Some(text) = part.get("text").and_then(Value::as_str) else { |
| 439 | return; |
| 440 | }; |
| 441 | if text.is_empty() { |
| 442 | return; |
| 443 | } |
| 444 | let thought = part.get("thought").and_then(Value::as_bool) == Some(true); |
| 445 | let index = match (self.open, thought) { |
| 446 | (Some(OpenBlock::Thinking(index)), true) | (Some(OpenBlock::Text(index)), false) => { |
| 447 | index |
| 448 | } |
| 449 | _ => { |
| 450 | self.close_open(events); |
| 451 | let index = self.next_index; |
| 452 | self.next_index += 1; |
| 453 | let (open, content_block) = if thought { |
| 454 | ( |
| 455 | OpenBlock::Thinking(index), |
| 456 | ContentBlockStart::Thinking { |
| 457 | thinking: String::new(), |
| 458 | }, |
| 459 | ) |
| 460 | } else { |
| 461 | ( |
| 462 | OpenBlock::Text(index), |
| 463 | ContentBlockStart::Text { |
| 464 | text: String::new(), |
| 465 | }, |
| 466 | ) |
| 467 | }; |
| 468 | self.open = Some(open); |
| 469 | events.push(StreamEvent::ContentBlockStart { |
| 470 | index, |
| 471 | content_block, |
| 472 | }); |
| 473 | index |
| 474 | } |
| 475 | }; |
| 476 | let delta = if thought { |
| 477 | Delta::ThinkingDelta { |
| 478 | thinking: text.to_string(), |
| 479 | } |
| 480 | } else { |
| 481 | Delta::TextDelta { |
| 482 | text: text.to_string(), |
| 483 | } |
| 484 | }; |
| 485 | events.push(StreamEvent::ContentBlockDelta { index, delta }); |
| 486 | } |
| 487 | |
| 488 | fn generated_call_id(&self) -> String { |
| 489 | match self.response_id.as_deref() { |
| 490 | Some(response_id) => format!("gemini_{response_id}_{}", self.tool_calls), |
| 491 | None => format!("gemini_{}_{}", self.stream_nonce, self.tool_calls), |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | fn close_open(&mut self, events: &mut Vec<StreamEvent>) { |
| 496 | if let Some(OpenBlock::Text(index) | OpenBlock::Thinking(index)) = self.open.take() { |
| 497 | events.push(StreamEvent::ContentBlockStop { index }); |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | fn gemini_usage(metadata: &Value) -> Usage { |
| 503 | let count = |key: &str| { |
| 504 | metadata |
| 505 | .get(key) |
| 506 | .and_then(Value::as_u64) |
| 507 | .map(|value| u32::try_from(value).unwrap_or(u32::MAX)) |
| 508 | }; |
| 509 | let prompt = count("promptTokenCount").unwrap_or(0); |
| 510 | let candidates = count("candidatesTokenCount").unwrap_or(0); |
| 511 | let thoughts = count("thoughtsTokenCount"); |
| 512 | let cached = count("cachedContentTokenCount"); |
| 513 | Usage { |
| 514 | input_tokens: prompt, |
| 515 | output_tokens: candidates.saturating_add(thoughts.unwrap_or(0)), |
| 516 | prompt_cache_hit_tokens: cached, |
| 517 | prompt_cache_miss_tokens: cached.map(|cached| prompt.saturating_sub(cached)), |
| 518 | reasoning_tokens: thoughts, |
| 519 | ..Usage::default() |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | fn map_finish_reason(reason: &str, saw_tool_call: bool) -> String { |
| 524 | match reason { |
| 525 | "STOP" if saw_tool_call => "tool_calls".to_string(), |
| 526 | "STOP" => "stop".to_string(), |
| 527 | "MAX_TOKENS" => "length".to_string(), |
| 528 | "SAFETY" |
| 529 | | "RECITATION" |
| 530 | | "BLOCKLIST" |
| 531 | | "PROHIBITED_CONTENT" |
| 532 | | "SPII" |
| 533 | | "IMAGE_SAFETY" |
| 534 | | "IMAGE_PROHIBITED_CONTENT" |
| 535 | | "IMAGE_RECITATION" => "content_filter".to_string(), |
| 536 | other => format!("incomplete:{}", other.to_ascii_lowercase()), |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | pub fn map_gemini_error(status: u16, body: &str) -> LlmError { |
| 541 | let error = serde_json::from_str::<Value>(body) |
| 542 | .ok() |
| 543 | .and_then(|value| value.get("error").cloned()); |
| 544 | let google_status = error |
| 545 | .as_ref() |
| 546 | .and_then(|error| error.get("status")) |
| 547 | .and_then(Value::as_str) |
| 548 | .unwrap_or_default(); |
| 549 | let message = error |
| 550 | .as_ref() |
| 551 | .and_then(|error| error.get("message")) |
| 552 | .and_then(Value::as_str) |
| 553 | .unwrap_or(body); |
| 554 | let invalid_key = body.contains("API_KEY_INVALID") |
| 555 | || message.to_ascii_lowercase().contains("api key not valid"); |
| 556 | if invalid_key || google_status == "UNAUTHENTICATED" { |
| 557 | return LlmError::authentication_error(message); |
| 558 | } |
| 559 | if google_status == "RESOURCE_EXHAUSTED" && status != 429 { |
| 560 | return LlmError::from_http_response(429, body); |
| 561 | } |
| 562 | LlmError::from_http_response(status, body) |
| 563 | } |
| 564 | |
| 565 | pub fn gemini_generate_content_url(base_url: &str, model: &str) -> String { |
| 566 | let base = base_url.trim().trim_end_matches('/'); |
| 567 | let base = base.strip_suffix("/models").unwrap_or(base); |
| 568 | let model = model.trim(); |
| 569 | let model = model.strip_prefix("models/").unwrap_or(model); |
| 570 | format!("{base}/models/{model}:streamGenerateContent?alt=sse") |
| 571 | } |
| 572 | |
| 573 | impl CodewhaleClient { |
| 574 | async fn open_gemini_stream_response( |
| 575 | &self, |
| 576 | url: &str, |
| 577 | body: &Value, |
| 578 | ) -> Result<reqwest::Response> { |
| 579 | let request_body = serde_json::to_vec(body) |
| 580 | .context("Failed to serialize Gemini Generate Content request")?; |
| 581 | self.send_stream_open_with_retry(|policy| { |
| 582 | super::stream_entry::client_for_policy( |
| 583 | &self.http_client, |
| 584 | self.http1_fallback_client(), |
| 585 | policy, |
| 586 | ) |
| 587 | .post(url) |
| 588 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 589 | .header("Accept", "text/event-stream") |
| 590 | .body(request_body.clone()) |
| 591 | }) |
| 592 | .await |
| 593 | .context("Gemini Generate Content API request failed") |
| 594 | } |
| 595 | |
| 596 | pub(super) async fn handle_gemini_stream( |
| 597 | &self, |
| 598 | prepared: &super::PreparedOutboundRequest, |
| 599 | ) -> Result<StreamEventBox> { |
| 600 | let response = self |
| 601 | .open_gemini_stream_response(&prepared.endpoint.url, &prepared.body) |
| 602 | .await?; |
| 603 | |
| 604 | let stream_idle_timeout = self.stream_idle_timeout; |
| 605 | let first_byte = super::stream_entry::first_byte_timeout(stream_idle_timeout); |
| 606 | let provider_label = self.api_provider.provider().display_name(); |
| 607 | let wire_model = prepared.wire_model.clone(); |
| 608 | let byte_stream = response.bytes_stream(); |
| 609 | |
| 610 | let stream = async_stream::stream! { |
| 611 | use futures_util::StreamExt; |
| 612 | |
| 613 | let mut decoder = GeminiStreamDecoder::new(wire_model); |
| 614 | let mut buffer: Vec<u8> = Vec::new(); |
| 615 | let mut event_data = String::new(); |
| 616 | let stream_start = std::time::Instant::now(); |
| 617 | let mut last_chunk_at = std::time::Instant::now(); |
| 618 | let mut bytes_received: usize = 0; |
| 619 | let mut ended = false; |
| 620 | tokio::pin!(byte_stream); |
| 621 | |
| 622 | loop { |
| 623 | if !ended { |
| 624 | let wait = super::stream_entry::next_chunk_timeout( |
| 625 | stream_idle_timeout, |
| 626 | first_byte, |
| 627 | bytes_received, |
| 628 | ); |
| 629 | match tokio::time::timeout(wait, byte_stream.next()).await { |
| 630 | Ok(Some(Ok(chunk))) => { |
| 631 | bytes_received += chunk.len(); |
| 632 | last_chunk_at = std::time::Instant::now(); |
| 633 | buffer.extend_from_slice(&chunk); |
| 634 | } |
| 635 | Ok(Some(Err(e))) => { |
| 636 | yield Err(anyhow::anyhow!("Stream read error: {e}")); |
| 637 | return; |
| 638 | } |
| 639 | Ok(None) => ended = true, |
| 640 | Err(_) => { |
| 641 | yield Err(anyhow::anyhow!(super::stream_entry::body_timeout_message( |
| 642 | wait, |
| 643 | bytes_received, |
| 644 | stream_start.elapsed(), |
| 645 | last_chunk_at.elapsed(), |
| 646 | provider_label, |
| 647 | ))); |
| 648 | return; |
| 649 | } |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | loop { |
| 654 | let data = match next_sse_line(&mut buffer, ended) { |
| 655 | Ok(Some(line)) if line.is_empty() => std::mem::take(&mut event_data), |
| 656 | Ok(Some(line)) => { |
| 657 | if let Some(value) = extract_sse_data_value(&line) |
| 658 | && let Err(err) = push_sse_event_data(&mut event_data, value) |
| 659 | { |
| 660 | yield Err(anyhow::anyhow!("{err}")); |
| 661 | return; |
| 662 | } |
| 663 | continue; |
| 664 | } |
| 665 | Ok(None) if ended && !event_data.is_empty() => { |
| 666 | std::mem::take(&mut event_data) |
| 667 | } |
| 668 | Ok(None) => break, |
| 669 | Err(err) => { |
| 670 | yield Err(anyhow::anyhow!("{err}")); |
| 671 | return; |
| 672 | } |
| 673 | }; |
| 674 | let trimmed = data.trim(); |
| 675 | if trimmed.is_empty() || trimmed == "[DONE]" { |
| 676 | continue; |
| 677 | } |
| 678 | |
| 679 | match serde_json::from_str::<Value>(trimmed) { |
| 680 | Ok(chunk) => { |
| 681 | if chunk.get("error").is_some() { |
| 682 | let status = chunk |
| 683 | .pointer("/error/code") |
| 684 | .and_then(Value::as_u64) |
| 685 | .and_then(|code| u16::try_from(code).ok()) |
| 686 | .unwrap_or(500); |
| 687 | yield Err(anyhow::Error::new(map_gemini_error(status, trimmed))); |
| 688 | return; |
| 689 | } |
| 690 | for event in decoder.decode(&chunk) { |
| 691 | yield Ok(event); |
| 692 | } |
| 693 | } |
| 694 | Err(e) => { |
| 695 | logging::warn(format!("Failed to parse Gemini SSE chunk: {e}")); |
| 696 | } |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | if ended { |
| 701 | break; |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | if !decoder.saw_finish_reason() { |
| 706 | yield Err(anyhow::anyhow!( |
| 707 | "Gemini Generate Content stream closed before finishReason" |
| 708 | )); |
| 709 | return; |
| 710 | } |
| 711 | for event in decoder.finish() { |
| 712 | yield Ok(event); |
| 713 | } |
| 714 | }; |
| 715 | |
| 716 | Ok(Box::pin(stream)) |
| 717 | } |
| 718 | |
| 719 | pub(super) async fn handle_gemini_message( |
| 720 | &self, |
| 721 | prepared: &super::PreparedOutboundRequest, |
| 722 | ) -> Result<MessageResponse> { |
| 723 | use futures_util::StreamExt; |
| 724 | |
| 725 | let mut stream = self.handle_gemini_stream(prepared).await?; |
| 726 | let mut response = MessageResponse { |
| 727 | tool_projection_warning: None, |
| 728 | id: String::new(), |
| 729 | r#type: "message".to_string(), |
| 730 | role: "assistant".to_string(), |
| 731 | content: Vec::new(), |
| 732 | model: prepared.wire_model.clone(), |
| 733 | stop_reason: None, |
| 734 | stop_sequence: None, |
| 735 | container: None, |
| 736 | usage: Usage::default(), |
| 737 | title: None, |
| 738 | stop_details: None, |
| 739 | refusal: None, |
| 740 | }; |
| 741 | let mut tool_args: Vec<String> = Vec::new(); |
| 742 | |
| 743 | while let Some(event) = stream.next().await { |
| 744 | match event? { |
| 745 | StreamEvent::MessageStart { message } => { |
| 746 | response.id = message.id; |
| 747 | response.model = message.model; |
| 748 | response.usage = message.usage; |
| 749 | } |
| 750 | StreamEvent::ContentBlockStart { content_block, .. } => { |
| 751 | let block = match content_block { |
| 752 | ContentBlockStart::Text { text } => ContentBlock::Text { |
| 753 | text, |
| 754 | cache_control: None, |
| 755 | }, |
| 756 | ContentBlockStart::Thinking { thinking } => ContentBlock::Thinking { |
| 757 | thinking, |
| 758 | signature: None, |
| 759 | state: None, |
| 760 | redacted_data: None, |
| 761 | }, |
| 762 | ContentBlockStart::RedactedThinking { .. } |
| 763 | | ContentBlockStart::ServerToolUse { .. } |
| 764 | | ContentBlockStart::WebSearchToolResult { .. } |
| 765 | | ContentBlockStart::WebFetchToolResult { .. } |
| 766 | | ContentBlockStart::WebSearchCall { .. } |
| 767 | | ContentBlockStart::ServerToolCalls { .. } => continue, |
| 768 | ContentBlockStart::ToolUse { |
| 769 | id, |
| 770 | name, |
| 771 | input, |
| 772 | caller, |
| 773 | thought_signature, |
| 774 | } => ContentBlock::ToolUse { |
| 775 | id, |
| 776 | name, |
| 777 | input, |
| 778 | caller, |
| 779 | thought_signature, |
| 780 | execution_id: None, |
| 781 | }, |
| 782 | }; |
| 783 | response.content.push(block); |
| 784 | tool_args.push(String::new()); |
| 785 | } |
| 786 | StreamEvent::ContentBlockDelta { delta, .. } => match delta { |
| 787 | Delta::TextDelta { text } => { |
| 788 | if let Some(ContentBlock::Text { text: existing, .. }) = |
| 789 | response.content.last_mut() |
| 790 | { |
| 791 | existing.push_str(&text); |
| 792 | } |
| 793 | } |
| 794 | Delta::ThinkingDelta { thinking } => { |
| 795 | if let Some(ContentBlock::Thinking { |
| 796 | thinking: existing, .. |
| 797 | }) = response.content.last_mut() |
| 798 | { |
| 799 | existing.push_str(&thinking); |
| 800 | } |
| 801 | } |
| 802 | Delta::InputJsonDelta { partial_json } => { |
| 803 | if let Some(buf) = tool_args.last_mut() { |
| 804 | buf.push_str(&partial_json); |
| 805 | } |
| 806 | } |
| 807 | _ => {} |
| 808 | }, |
| 809 | StreamEvent::ContentBlockStop { .. } => { |
| 810 | if let (Some(ContentBlock::ToolUse { input, .. }), Some(raw_json)) = |
| 811 | (response.content.last_mut(), tool_args.last()) |
| 812 | && !raw_json.is_empty() |
| 813 | && let Ok(parsed) = serde_json::from_str::<Value>(raw_json) |
| 814 | { |
| 815 | *input = parsed; |
| 816 | } |
| 817 | } |
| 818 | StreamEvent::MessageDelta { delta, usage } => { |
| 819 | if delta.stop_reason.is_some() { |
| 820 | response.stop_reason = delta.stop_reason; |
| 821 | } |
| 822 | if delta.refusal.is_some() { |
| 823 | response.refusal = delta.refusal; |
| 824 | } |
| 825 | if let Some(usage) = usage { |
| 826 | response.usage = usage; |
| 827 | } |
| 828 | } |
| 829 | StreamEvent::MessageStop |
| 830 | | StreamEvent::Ping |
| 831 | | StreamEvent::Error { .. } |
| 832 | | StreamEvent::ToolProjectionWarning { .. } => {} |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | Ok(response) |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | #[cfg(test)] |
| 841 | #[path = "gemini_tests.rs"] |
| 842 | mod tests; |
| 843 |