Skip to main content

aither_gemini/
llm.rs

1use aither_core::{
2    LanguageModel,
3    llm::{
4        Attachment, Event, GenerateError, LLMRequest, Message, ReasoningState, RetryPolicy, Role,
5        TokenCounting, Usage,
6        model::{Ability, Parameters, Profile, ToolChoice},
7        tool::ToolDefinition,
8    },
9};
10use futures_core::Stream;
11use futures_lite::StreamExt;
12use schemars::JsonSchema;
13use serde::de::DeserializeOwned;
14use std::collections::HashMap;
15use tracing::debug;
16
17use crate::PROVIDER_NAME;
18use crate::{
19    client::{RETRY_POLICY, stream_generate},
20    config::Gemini,
21    error::GeminiError,
22    types::{
23        FunctionCallingConfig, FunctionCallingMode, FunctionDeclaration, GeminiContent, GeminiTool,
24        GenerateContentRequest, GenerationConfig, GoogleSearch, Part, PromptFeedback, SafetyRating,
25        ThinkingConfig, ThinkingLevel, ToolConfig, UsageMetadata,
26    },
27};
28use schemars::schema_for;
29
30impl LanguageModel for Gemini {
31    type Error = GeminiError;
32
33    fn token_counting(&self) -> TokenCounting {
34        TokenCounting::Endpoint
35    }
36
37    /// `POST /v1beta/models/{model}:countTokens` carrying the same
38    /// `generateContent` body the request would send, so the count covers
39    /// tools and system instructions the way the call does.
40    async fn count_tokens(
41        &self,
42        request: &LLMRequest,
43    ) -> Result<Option<u32>, GenerateError<Self::Error>> {
44        let cfg = self.config().clone();
45        let generate = build_generate_request(&cfg, request.clone())
46            .await
47            .map_err(GenerateError::Provider)?;
48        let body = serde_json::json!({ "generateContentRequest": generate });
49        let endpoint = cfg.model_endpoint(&cfg.text_model, "countTokens");
50        let response: crate::types::CountTokensResponse =
51            crate::client::post_json(&cfg, endpoint, &body)
52                .await
53                .map_err(GenerateError::Provider)?;
54        Ok(Some(response.total_tokens))
55    }
56
57    fn respond(
58        &self,
59        request: LLMRequest,
60    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
61        let cfg = self.config();
62        respond_stream(cfg.clone(), request)
63    }
64
65    fn generate<T: JsonSchema + DeserializeOwned + 'static>(
66        &self,
67        mut request: LLMRequest,
68    ) -> impl core::future::Future<Output = Result<T, GenerateError<Self::Error>>> + Send {
69        let schema = schema_for!(T);
70        let mut params = request.parameters().clone();
71        params.structured_outputs = true;
72        params.response_format = Some(schema);
73        request = request.with_parameters(params);
74
75        let stream = self.respond(request);
76        async move {
77            let text = aither_core::llm::collect_text(stream)
78                .await
79                .map_err(GenerateError::Provider)?;
80            serde_json::from_str::<T>(&text).map_err(|source| GenerateError::Parse {
81                source,
82                response: text.chars().take(500).collect(),
83            })
84        }
85    }
86
87    fn retry_policy(&self) -> RetryPolicy {
88        RETRY_POLICY
89    }
90
91    fn profile(&self) -> impl core::future::Future<Output = Result<Profile, Self::Error>> + Send {
92        let cfg = self.config().clone();
93        async move {
94            let model_name = cfg.text_model.trim_start_matches("models/").to_string();
95
96            // Fetch actual context window from API, fallback to models database
97            let context_length = match crate::client::get_model_info(&cfg, &cfg.text_model).await {
98                Ok(info) => info.input_token_limit,
99                Err(e) => {
100                    tracing::debug!("API did not return context_length: {e}");
101                    // Fallback to models database
102                    aither_models::lookup(&model_name)
103                        .and_then(aither_models::ModelEntry::max_input_tokens)
104                        .ok_or_else(|| {
105                            GeminiError::Api(format!(
106                                "cannot determine context length for model '{model_name}': \
107                                 model info request failed ({e}) and aither-models has no entry"
108                            ))
109                        })?
110                }
111            };
112
113            let mut profile = Profile::new(
114                model_name.clone(),
115                "google",
116                model_name,
117                "Gemini Developer API model",
118                context_length,
119            )
120            .with_abilities([Ability::ToolUse, Ability::Vision, Ability::Audio]);
121            for ability in &cfg.native_abilities {
122                if !profile.abilities.contains(ability) {
123                    profile.abilities.push(*ability);
124                }
125            }
126            Ok(profile)
127        }
128    }
129}
130
131fn respond_stream(
132    cfg: crate::config::GeminiConfig,
133    request: LLMRequest,
134) -> impl Stream<Item = Result<Event, GeminiError>> + Send {
135    Box::pin(respond_stream_inner(cfg, request))
136}
137
138/// Assembles the Gemini request for a provider-agnostic one.
139///
140/// Async because file attachments are uploaded before the request is sent.
141///
142/// # Errors
143///
144/// Returns [`GeminiError`] if the request names an exact tool that was not
145/// supplied, or an attachment cannot be resolved. Cache settings of other
146/// providers are ignored.
147async fn build_generate_request(
148    cfg: &crate::config::GeminiConfig,
149    request: LLMRequest,
150) -> Result<GenerateContentRequest, GeminiError> {
151    let (messages, parameters, tool_defs) = request.into_parts();
152
153    #[cfg(not(target_arch = "wasm32"))]
154    let messages = crate::attachments::resolve_messages(cfg, messages).await?;
155    // wasm32 has no filesystem, so there is nothing to upload and no use for
156    // the config here.
157    #[cfg(target_arch = "wasm32")]
158    let _ = cfg;
159
160    let (system_instruction, contents) = messages_to_gemini(&messages).await?;
161
162    let tool_defs: Vec<ToolDefinition> = match &parameters.tool_choice {
163        ToolChoice::None => Vec::new(),
164        ToolChoice::Exact(name) => tool_defs
165            .into_iter()
166            .filter(|tool| tool.name() == name)
167            .collect(),
168        ToolChoice::Auto | ToolChoice::Required => tool_defs,
169    };
170    let has_function_tools = !tool_defs.is_empty();
171
172    if let ToolChoice::Exact(name) = &parameters.tool_choice
173        && !has_function_tools
174    {
175        return Err(GeminiError::Api(format!(
176            "Exact tool choice '{name}' is not present in tool definitions"
177        )));
178    }
179
180    let mut tools: Vec<GeminiTool> = Vec::new();
181    if has_function_tools {
182        tools.push(GeminiTool::FunctionTool {
183            function_declarations: convert_tool_definitions(tool_defs),
184        });
185    }
186
187    // Google's own tools cannot be combined with a narrowed tool choice: the
188    // model would be free to answer with a tool the caller did not ask about.
189    let builtins_allowed = !matches!(
190        parameters.tool_choice,
191        ToolChoice::None | ToolChoice::Exact(_)
192    );
193    let native = &parameters.native_tools.gemini;
194    if builtins_allowed && (parameters.websearch || native.google_search) {
195        tools.push(GeminiTool::GoogleSearchTool {
196            google_search: GoogleSearch {},
197        });
198    }
199    if builtins_allowed && (parameters.code_execution || native.code_execution) {
200        tools.push(GeminiTool::CodeExecutionTool {
201            code_execution: crate::types::CodeExecution {},
202        });
203    }
204    if builtins_allowed && native.url_context {
205        tools.push(GeminiTool::UrlContextTool {
206            url_context: crate::types::UrlContext {},
207        });
208    }
209
210    Ok(GenerateContentRequest {
211        system_instruction,
212        contents,
213        generation_config: build_generation_config(&parameters, None)?,
214        tools,
215        tool_config: build_tool_config(&parameters, has_function_tools),
216        safety_settings: Vec::new(),
217        cached_content: parameters
218            .cache
219            .gemini
220            .as_ref()
221            .map(|cache| cache.cached_content.clone()),
222    })
223}
224
225/// Turns one candidate's content into the events it represents, in wire order:
226/// reasoning, then text, then built-in tool output, then function calls.
227fn events_from_content(content: &GeminiContent) -> Vec<Event> {
228    let mut events = Vec::new();
229
230    events.extend(content.reasoning_chunks().into_iter().map(Event::Reasoning));
231    events.extend(
232        content
233            .text_chunks()
234            .into_iter()
235            .filter(|text| !text.is_empty())
236            .map(Event::Text),
237    );
238
239    for part in &content.parts {
240        if let Some(code) = &part.executable_code {
241            events.push(Event::BuiltInToolCall {
242                id: String::new(),
243                tool: "code_execution".to_string(),
244                detail: format!("```{}\n{}\n```", code.language.to_lowercase(), code.code),
245            });
246        }
247        if let Some(result) = &part.code_execution_result {
248            events.push(Event::BuiltInToolResult {
249                id: String::new(),
250                tool: "code_execution".to_string(),
251                result: format!("```output\n{}\n```", result.output),
252            });
253        }
254    }
255
256    // Tool calls are reported, never executed: the consumer decides.
257    events.extend(
258        content
259            .function_call_parts()
260            .into_iter()
261            .map(|(call, signature)| {
262                // Gemini signs each function call rather than the turn, so the
263                // signature rides on the call it belongs to.
264                Event::ToolCall(aither_core::llm::ToolCall {
265                    id: tool_call_id(),
266                    name: call.name,
267                    arguments: call.args,
268                    reasoning_state: signature
269                        .map(|value| ReasoningState::new(PROVIDER_NAME, value)),
270                })
271            }),
272    );
273
274    events
275}
276
277fn respond_stream_inner(
278    cfg: crate::config::GeminiConfig,
279    request: LLMRequest,
280) -> impl Stream<Item = Result<Event, GeminiError>> + Send {
281    async_stream::stream! {
282        let gemini_request = match build_generate_request(&cfg, request).await {
283            Ok(request) => request,
284            Err(e) => {
285                yield Err(e);
286                return;
287            }
288        };
289
290        debug!("Gemini request: {:?}", gemini_request);
291
292        // Use streaming endpoint for true streaming output
293        let stream = match stream_generate(&cfg, &cfg.text_model, gemini_request).await {
294            Ok(s) => s,
295            Err(e) => {
296                yield Err(e);
297                return;
298            }
299        };
300        futures_lite::pin!(stream);
301        let mut usage: Option<Usage> = None;
302        let mut finish_reason: Option<String> = None;
303
304        while let Some(result) = stream.next().await {
305            let response = match result {
306                Ok(r) => r,
307                Err(e) => {
308                    yield Err(e);
309                    continue;
310                }
311            };
312
313            debug!("Gemini stream chunk: {:?}", response);
314
315            if let Some(meta) = &response.usage_metadata {
316                usage = Some(usage_from_metadata(meta));
317            }
318
319            let Some(candidate) = response.primary_candidate() else {
320                // Chunks without candidates carry metadata, not content — but a
321                // blocked prompt is reported this way and must not pass silently.
322                if let Some(feedback) = &response.prompt_feedback {
323                    yield Err(GeminiError::Api(format_prompt_feedback(feedback)));
324                }
325                continue;
326            };
327
328            let Some(content) = &candidate.content else {
329                if let Some(reason) = candidate.finish_reason.clone() {
330                    finish_reason = Some(reason);
331                    break;
332                }
333                continue;
334            };
335
336            for event in events_from_content(content) {
337                yield Ok(event);
338            }
339
340            if let Some(reason) = candidate.finish_reason.clone() {
341                finish_reason = Some(reason);
342                break;
343            }
344        }
345
346        if let Some(mut final_usage) = usage {
347            final_usage.stop_reason = finish_reason;
348            yield Ok(Event::Usage(final_usage));
349        } else if let Some(reason) = finish_reason {
350            yield Ok(Event::Usage(Usage {
351                stop_reason: Some(reason),
352                ..Usage::default()
353            }));
354        }
355    }
356}
357
358/// Simple UUID v4 generator for tool call IDs.
359fn uuid_v4() -> String {
360    use std::time::{SystemTime, UNIX_EPOCH};
361    let timestamp = SystemTime::now()
362        .duration_since(UNIX_EPOCH)
363        .map_or(0, |d| d.as_nanos());
364    format!("{timestamp:032x}")
365}
366
367fn tool_call_id() -> String {
368    format!("gemini_{}", uuid_v4())
369}
370
371fn parse_tool_response(content: &str) -> Option<(String, serde_json::Value, Option<String>)> {
372    let content = content.trim_start();
373    if !content.starts_with('[') {
374        return None;
375    }
376    let end = content.find(']')?;
377    let header = &content[1..end];
378    let mut header_split = header.splitn(2, ':');
379    let id = header_split.next()?.trim();
380    let name = header_split.next()?.trim().to_string();
381    let rest = &content[end + 1..];
382    let output = rest.strip_prefix(' ').unwrap_or(rest);
383    let _ = id;
384    let signature = None;
385    let response_value = match serde_json::from_str::<serde_json::Value>(output) {
386        Ok(serde_json::Value::Object(map)) => serde_json::Value::Object(map),
387        Ok(other) => {
388            let mut map = serde_json::Map::new();
389            map.insert("result".to_string(), other);
390            serde_json::Value::Object(map)
391        }
392        Err(_) => {
393            let mut map = serde_json::Map::new();
394            map.insert(
395                "result".to_string(),
396                serde_json::Value::String(output.to_string()),
397            );
398            serde_json::Value::Object(map)
399        }
400    };
401    Some((name, response_value, signature))
402}
403
404const fn usage_from_metadata(meta: &UsageMetadata) -> Usage {
405    Usage {
406        prompt_tokens: meta.prompt_token_count,
407        completion_tokens: meta.candidates_token_count,
408        total_tokens: meta.total_token_count,
409        reasoning_tokens: meta.thoughts_token_count,
410        cache_read_tokens: meta.cached_content_token_count,
411        cache_write_tokens: None,
412        cost_usd: None,
413        stop_reason: None,
414    }
415}
416
417/// Indexes every tool call by id, yielding its function name and, where the
418/// model signed it, its thought signature.
419///
420/// A tool *result* has to look both up: Gemini scopes the signature to the call
421/// rather than the result, so the result cannot carry it.
422fn index_tool_calls(messages: &[Message]) -> ToolCallIndex<'_> {
423    let mut names = HashMap::new();
424    let mut signatures = HashMap::new();
425    let mut positions = HashMap::new();
426    for message in messages {
427        for tc in message.tool_calls() {
428            positions.insert(tc.id.as_str(), positions.len());
429            names.insert(tc.id.as_str(), tc.name.as_str());
430            if let Some(signature) = tc
431                .reasoning_state
432                .as_ref()
433                .and_then(|state| state.payload_for(PROVIDER_NAME))
434            {
435                signatures.insert(tc.id.as_str(), signature);
436            }
437        }
438    }
439    ToolCallIndex {
440        names,
441        signatures,
442        positions,
443    }
444}
445
446/// Parses a tool result as JSON, or wraps it as a string `result`.
447fn tool_response_value(content: &str) -> serde_json::Value {
448    match serde_json::from_str::<serde_json::Value>(content) {
449        Ok(serde_json::Value::Object(map)) => serde_json::Value::Object(map),
450        Ok(other) => serde_json::json!({ "result": other }),
451        Err(_) => serde_json::json!({ "result": content }),
452    }
453}
454
455/// Lookups keyed by tool-call id.
456struct ToolCallIndex<'a> {
457    names: HashMap<&'a str, &'a str>,
458    signatures: HashMap<&'a str, &'a str>,
459    /// Position of the call in the conversation, which is the order Gemini
460    /// expects its responses in.
461    positions: HashMap<&'a str, usize>,
462}
463
464/// Emits the pending tool results as one `user` Content in call order.
465///
466/// Gemini requires every `functionResponse` answering a model turn to share a
467/// single Content; results arrive in completion order, so they are sorted by
468/// the position of the call they answer.
469fn flush_tool_results(contents: &mut Vec<GeminiContent>, pending: &mut Vec<(usize, Part)>) {
470    if pending.is_empty() {
471        return;
472    }
473    pending.sort_by_key(|(position, _)| *position);
474    let parts = pending.drain(..).map(|(_, part)| part).collect();
475    contents.push(GeminiContent::with_parts("user", parts));
476}
477
478async fn messages_to_gemini(
479    messages: &[Message],
480) -> Result<(Option<GeminiContent>, Vec<GeminiContent>), GeminiError> {
481    let mut system_parts = Vec::new();
482    let mut contents = Vec::new();
483
484    let index = index_tool_calls(messages);
485    let mut pending_results: Vec<(usize, Part)> = Vec::new();
486
487    for message in messages {
488        if message.role() != Role::Tool {
489            flush_tool_results(&mut contents, &mut pending_results);
490        }
491        match message.role() {
492            Role::Configuration => {
493                return Err(GeminiError::Api(
494                    "Gemini takes no per-message effort update".to_string(),
495                ));
496            }
497            Role::System => system_parts.push(Part::text(message.content())),
498            Role::User => {
499                let attachments = message.attachments();
500                if attachments.is_empty() {
501                    contents.push(GeminiContent::text("user", message.content()));
502                } else {
503                    // Build parts with attachments
504                    let mut parts = Vec::new();
505
506                    // Add attachment parts first
507                    for attachment in attachments {
508                        parts.push(url_to_part(attachment).await?);
509                    }
510
511                    // Add text content
512                    if !message.content().is_empty() {
513                        parts.push(Part::text(message.content()));
514                    }
515
516                    contents.push(GeminiContent::with_parts("user", parts));
517                }
518            }
519            Role::Tool => {
520                // Get the function name from the tool_call_id
521                let tool_call_id = message.tool_call_id().unwrap_or("");
522                let base_id = tool_call_id.to_string();
523                let signature = index
524                    .signatures
525                    .get(tool_call_id)
526                    .map(|value| (*value).to_string());
527
528                if let Some(&function_name) = index.names.get(tool_call_id) {
529                    pending_results.push((
530                        index.positions[tool_call_id],
531                        Part::function_response_with_signature(
532                            function_name.to_string(),
533                            tool_response_value(message.content()),
534                            signature,
535                        ),
536                    ));
537                } else {
538                    // Fallback: try legacy format or send as user message
539                    if let Some((name, response, sig)) = parse_tool_response(message.content()) {
540                        pending_results.push((
541                            usize::MAX,
542                            Part::function_response_with_signature(name, response, sig),
543                        ));
544                    } else {
545                        // Last resort - wrap as text
546                        debug!("Tool message without matching tool_call_id: {}", base_id);
547                        flush_tool_results(&mut contents, &mut pending_results);
548                        contents.push(GeminiContent::text("user", message.content()));
549                    }
550                }
551            }
552            Role::Assistant => {
553                let tool_calls = message.tool_calls();
554                if tool_calls.is_empty() {
555                    // Regular text response
556                    contents.push(GeminiContent::text("model", message.content()));
557                } else {
558                    // Assistant message with function calls
559                    let mut parts = Vec::new();
560
561                    // Add text content if present
562                    if !message.content().is_empty() {
563                        parts.push(Part::text(message.content()));
564                    }
565
566                    // Add function call parts with thought signatures extracted from IDs
567                    for tc in tool_calls {
568                        let signature = tc
569                            .reasoning_state
570                            .as_ref()
571                            .and_then(|state| state.payload_for(PROVIDER_NAME))
572                            .map(String::from);
573                        parts.push(Part::function_call_with_signature(
574                            tc.name.clone(),
575                            tc.arguments.clone(),
576                            signature,
577                        ));
578                    }
579
580                    contents.push(GeminiContent::with_parts("model", parts));
581                }
582            }
583        }
584    }
585
586    flush_tool_results(&mut contents, &mut pending_results);
587
588    let system_instruction = if system_parts.is_empty() {
589        None
590    } else {
591        Some(GeminiContent::system(system_parts))
592    };
593
594    Ok((system_instruction, contents))
595}
596
597fn format_prompt_feedback(feedback: &PromptFeedback) -> String {
598    let reason = feedback
599        .block_reason
600        .as_deref()
601        .unwrap_or("unknown reason")
602        .to_string();
603    if feedback.safety_ratings.is_empty() {
604        return format!("Gemini response blocked: {reason}");
605    }
606
607    let ratings = feedback
608        .safety_ratings
609        .iter()
610        .map(format_safety_rating)
611        .collect::<Vec<_>>()
612        .join(", ");
613    format!("Gemini response blocked: {reason}; safety: {ratings}")
614}
615
616fn format_safety_rating(rating: &SafetyRating) -> String {
617    let status = rating
618        .blocked
619        .map_or("unspecified", |b| if b { "blocked" } else { "allowed" });
620    let probability = rating.probability.as_deref().unwrap_or("unknown");
621    format!("{} ({status}, probability: {probability})", rating.category)
622}
623
624/// # Errors
625///
626/// Returns [`GeminiError`] when the requested reasoning effort has no Gemini
627/// equivalent.
628fn build_generation_config(
629    parameters: &Parameters,
630    modalities: Option<Vec<String>>,
631) -> Result<Option<GenerationConfig>, GeminiError> {
632    let thinking_config = build_thinking_config(parameters)?;
633    let mut config = GenerationConfig {
634        temperature: parameters.temperature,
635        top_p: parameters.top_p,
636        top_k: parameters.top_k,
637        max_output_tokens: parameters.max_tokens.map(
638            #[allow(clippy::cast_possible_wrap)]
639            |value| value as i32,
640        ),
641        stop_sequences: parameters.stop.clone(),
642        response_modalities: modalities,
643        thinking_config,
644        seed: parameters.seed.map(
645            #[allow(clippy::cast_possible_wrap)]
646            |value| value as i32,
647        ),
648        presence_penalty: parameters.presence_penalty,
649        frequency_penalty: parameters.frequency_penalty,
650        response_logprobs: parameters.logprobs,
651        logprobs: parameters.top_logprobs.map(i32::from),
652        ..Default::default()
653    };
654    if let Some(schema) = &parameters.response_format {
655        config.response_mime_type = Some("application/json".into());
656        config.response_json_schema = Some(schema.clone().to_value());
657    } else if parameters.structured_outputs {
658        config.response_mime_type = Some("application/json".into());
659    }
660    if config.is_meaningful() {
661        Ok(Some(config))
662    } else {
663        Ok(None)
664    }
665}
666
667fn build_tool_config(parameters: &Parameters, has_tools: bool) -> Option<ToolConfig> {
668    if !has_tools {
669        return None;
670    }
671    let (mode, allowed) = match &parameters.tool_choice {
672        ToolChoice::None => return None,
673        ToolChoice::Auto => (FunctionCallingMode::Auto, None),
674        ToolChoice::Required => (FunctionCallingMode::Any, None),
675        ToolChoice::Exact(name) => (FunctionCallingMode::Any, Some(vec![name.clone()])),
676    };
677    Some(ToolConfig {
678        function_calling_config: Some(FunctionCallingConfig {
679            mode,
680            allowed_function_names: allowed,
681        }),
682    })
683}
684
685/// Builds `thinkingConfig` from the portable reasoning parameters.
686///
687/// Depth (`reasoning_effort`) and visibility (`include_reasoning`) are separate
688/// controls: asking for a deeper think does not require the thoughts to be
689/// returned, and vice versa. Either one alone is enough to emit the config.
690/// # Errors
691///
692/// Returns [`GeminiError`] when the requested effort has no Gemini equivalent.
693fn build_thinking_config(parameters: &Parameters) -> Result<Option<ThinkingConfig>, GeminiError> {
694    let thinking_level = parameters
695        .reasoning_effort
696        .map(ThinkingLevel::try_from)
697        .transpose()?;
698    if !parameters.include_reasoning && thinking_level.is_none() {
699        return Ok(None);
700    }
701    Ok(Some(ThinkingConfig {
702        include_thoughts: parameters.include_reasoning.then_some(true),
703        thinking_level,
704    }))
705}
706
707fn convert_tool_definitions(defs: Vec<ToolDefinition>) -> Vec<FunctionDeclaration> {
708    defs.into_iter()
709        .map(|tool| FunctionDeclaration {
710            name: tool.name().to_string(),
711            description: tool.description().to_string(),
712            parameters: Some(tool.arguments_openai_schema()),
713        })
714        .collect()
715}
716
717/// Convert a typed attachment to a Gemini content part.
718async fn url_to_part(attachment: &Attachment) -> Result<Part, GeminiError> {
719    let url = attachment.url();
720    let media_type = attachment.media_type().as_ref();
721    match url.scheme() {
722        "data" => parse_data_url(url.as_str(), media_type),
723        "file" => read_file_to_part(url, media_type).await,
724        "http" | "https" => Ok(Part::from_file(media_type, url.as_str())),
725        scheme => Err(GeminiError::Api(format!(
726            "Gemini does not support attachment URL scheme '{scheme}'"
727        ))),
728    }
729}
730
731fn parse_data_url(url: &str, media_type: &str) -> Result<Part, GeminiError> {
732    use base64::Engine;
733
734    let after_data = url
735        .strip_prefix("data:")
736        .ok_or_else(|| GeminiError::Api("Malformed attachment data URL".to_string()))?;
737    let (header, data) = after_data
738        .split_once(',')
739        .ok_or_else(|| GeminiError::Api("Attachment data URL is missing payload".to_string()))?;
740    let encoded_media_type = header.strip_suffix(";base64").ok_or_else(|| {
741        GeminiError::Api("Attachment data URL must use base64 encoding".to_string())
742    })?;
743    if encoded_media_type != media_type {
744        return Err(GeminiError::Api(format!(
745            "Attachment MIME type '{media_type}' does not match data URL MIME type '{encoded_media_type}'"
746        )));
747    }
748    let bytes = base64::engine::general_purpose::STANDARD.decode(data)?;
749    Ok(Part::inline_media(media_type, bytes))
750}
751
752#[cfg(not(target_arch = "wasm32"))]
753async fn read_file_to_part(url: &url::Url, media_type: &str) -> Result<Part, GeminiError> {
754    let path = url.to_file_path().map_err(|()| {
755        GeminiError::Api("Attachment file URL could not be converted to a path".to_string())
756    })?;
757    let data = async_fs::read(&path).await.map_err(|error| {
758        GeminiError::Api(format!(
759            "Failed to read attachment '{}': {error}",
760            path.display()
761        ))
762    })?;
763    Ok(Part::inline_media(media_type, data))
764}
765
766#[cfg(target_arch = "wasm32")]
767async fn read_file_to_part(_url: &url::Url, _media_type: &str) -> Result<Part, GeminiError> {
768    Err(GeminiError::Api(
769        "file:// attachments are not supported on wasm32".to_string(),
770    ))
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776    use aither_core::llm::model::ReasoningEffort;
777
778    #[tokio::test]
779    async fn data_attachments_preserve_declared_media_types() {
780        for media_type in ["image/png", "audio/wav", "video/mp4", "application/pdf"] {
781            let attachment = Attachment::new(
782                format!("data:{media_type};base64,AA==")
783                    .parse()
784                    .expect("data URL"),
785                media_type.parse().expect("MIME type"),
786            );
787            let part = url_to_part(&attachment).await.expect("encode attachment");
788            let value = serde_json::to_value(part).expect("serialize part");
789            assert_eq!(value["inlineData"]["mimeType"], media_type);
790        }
791    }
792
793    #[tokio::test]
794    async fn remote_attachment_uses_file_data_with_media_type() {
795        let attachment = Attachment::new(
796            "https://ai.google.dev/static/gemini-api/docs/files/sample.pdf"
797                .parse()
798                .expect("remote URL"),
799            "application/pdf".parse().expect("PDF MIME"),
800        );
801        let part = url_to_part(&attachment).await.expect("encode attachment");
802        let value = serde_json::to_value(part).expect("serialize part");
803        assert_eq!(value["fileData"]["mimeType"], "application/pdf");
804        assert_eq!(
805            value["fileData"]["fileUri"],
806            "https://ai.google.dev/static/gemini-api/docs/files/sample.pdf"
807        );
808    }
809
810    /// A loopback server that records the request and answers `200` with
811    /// the given JSON body.
812    fn responding_server(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
813        use std::io::{Read, Write};
814        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stub server");
815        let addr = listener.local_addr().expect("stub server address");
816        let (sender, received) = std::sync::mpsc::channel();
817        std::thread::spawn(move || {
818            let (mut stream, _) = listener.accept().expect("accept the request");
819            let mut request = Vec::new();
820            let mut chunk = [0_u8; 8192];
821            let body_start = loop {
822                let read = stream.read(&mut chunk).expect("read the request");
823                request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
824                if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
825                    break end + 4;
826                }
827            };
828            let head_str =
829                String::from_utf8_lossy(request.get(..body_start).expect("head")).into_owned();
830            let length = head_str.lines().find_map(|line| {
831                line.to_ascii_lowercase()
832                    .strip_prefix("content-length:")
833                    .map(|v| v.trim().parse::<usize>().expect("numeric length"))
834            });
835            let chunked = head_str
836                .to_ascii_lowercase()
837                .contains("transfer-encoding: chunked");
838            let complete = |request: &[u8]| {
839                if chunked {
840                    request.ends_with(b"0\r\n\r\n")
841                } else {
842                    request.len() >= body_start + length.unwrap_or(0)
843                }
844            };
845            while !complete(&request) {
846                let read = stream.read(&mut chunk).expect("read the body");
847                request.extend_from_slice(chunk.get(..read).expect("read within the chunk"));
848            }
849            let raw =
850                String::from_utf8_lossy(request.get(body_start..).expect("body")).into_owned();
851            let decoded_body = if chunked {
852                // Strip the chunk-size lines: chunks are `hex\r\ndata`.
853                let mut out = String::new();
854                let mut rest = raw.as_str();
855                while let Some((size, after)) = rest.split_once("\r\n") {
856                    let size = usize::from_str_radix(size.trim(), 16).expect("hex size");
857                    if size == 0 {
858                        break;
859                    }
860                    out.push_str(after.get(..size).expect("full chunk"));
861                    rest = &after[size + 2..];
862                }
863                out
864            } else {
865                raw
866            };
867            sender
868                .send(format!("{head_str}{decoded_body}"))
869                .expect("the test is listening");
870            let response = format!(
871                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
872                body.len(),
873                body
874            );
875            let _ = stream.write_all(response.as_bytes());
876        });
877        (format!("http://{addr}"), received)
878    }
879
880    /// `count_tokens` posts the converted contents to
881    /// `/v1beta/models/{model}:countTokens` and reads `totalTokens` back.
882    #[tokio::test]
883    async fn count_tokens_posts_to_the_count_endpoint() {
884        let (base_url, received) = responding_server("{\"totalTokens\": 2097}");
885        let client = Gemini::new("key").with_base_url(base_url);
886        assert_eq!(client.token_counting(), TokenCounting::Endpoint);
887        let request = LLMRequest::new(vec![Message::user("Plan the migration.")]);
888        let counted = client.count_tokens(&request).await.expect("count succeeds");
889        assert_eq!(counted, Some(2097));
890
891        let sent = received.recv().expect("the request arrives");
892        let (head, body) = sent.split_once("\r\n\r\n").expect("head and body");
893        assert!(
894            head.lines()
895                .next()
896                .is_some_and(|line| line.contains(":countTokens")),
897            "{head}"
898        );
899        let body: serde_json::Value = serde_json::from_str(body).expect("a JSON body");
900        assert_eq!(
901            body["generateContentRequest"]["contents"][0]["role"], "user",
902            "{body}"
903        );
904    }
905
906    #[test]
907    fn data_url_mime_mismatch_fails() {
908        let error = parse_data_url("data:image/png;base64,AA==", "audio/wav")
909            .expect_err("MIME mismatch must fail");
910        assert!(error.to_string().contains("does not match"));
911    }
912
913    fn thinking_json(params: &Parameters) -> serde_json::Value {
914        let config = build_thinking_config(params)
915            .expect("effort supported by Gemini")
916            .expect("thinking config");
917        serde_json::to_value(config).expect("serialize thinking config")
918    }
919
920    /// Gemini names the field `thinkingLevel`; there is no `tokenBudget`, so a
921    /// misnamed field is accepted by serde and then ignored on the wire.
922    #[test]
923    fn thinking_config_uses_gemini_field_names() {
924        let value = thinking_json(&Parameters::default().reasoning_effort(ReasoningEffort::Medium));
925        assert_eq!(value["thinkingLevel"], "medium");
926        assert_eq!(value.get("tokenBudget"), None);
927        assert_eq!(value.get("thinkingBudget"), None);
928    }
929
930    /// `thinkingLevel` and the legacy `thinkingBudget` are mutually exclusive:
931    /// sending both is a 400, so only the level is ever modelled.
932    #[test]
933    fn thinking_config_never_pairs_a_budget_with_a_level() {
934        for effort in [
935            ReasoningEffort::Minimal,
936            ReasoningEffort::Low,
937            ReasoningEffort::Medium,
938            ReasoningEffort::High,
939        ] {
940            let value = thinking_json(&Parameters::default().reasoning_effort(effort));
941            let object = value.as_object().expect("thinking config object");
942            assert!(
943                object.keys().all(|key| key != "thinkingBudget"),
944                "effort {effort:?} paired a budget with a level"
945            );
946            assert!(object.contains_key("thinkingLevel"));
947        }
948    }
949
950    #[test]
951    fn minimal_effort_maps_to_the_minimal_level() {
952        let value =
953            thinking_json(&Parameters::default().reasoning_effort(ReasoningEffort::Minimal));
954        assert_eq!(value["thinkingLevel"], "minimal");
955    }
956
957    /// Gemini's ladder stops at High. Clamping `XHigh` or `Max` down to High would
958    /// hand back less reasoning than the caller asked for, silently.
959    #[test]
960    fn efforts_above_gemini_ceiling_are_rejected() {
961        for effort in [ReasoningEffort::XHigh, ReasoningEffort::Max] {
962            let error = build_thinking_config(&Parameters::default().reasoning_effort(effort))
963                .expect_err("effort above the Gemini ceiling must fail");
964            assert!(
965                error.to_string().contains("tops out at High"),
966                "unexpected error for {effort:?}: {error}"
967            );
968        }
969    }
970
971    /// The signature used to be base64'd into the tool-call id behind a `|ts|`
972    /// separator, because core had nowhere to put it. It now rides on the call,
973    /// and the id is a plain identifier again.
974    #[tokio::test]
975    async fn thought_signature_round_trips_without_mangling_the_id() {
976        let call = aither_core::llm::ToolCall::new("gemini_abc", "lookup", serde_json::json!({}))
977            .with_reasoning_state(ReasoningState::new(PROVIDER_NAME, "sig-xyz"));
978        let message = Message::assistant_with_tool_calls("", vec![call]);
979
980        let (_, contents) = messages_to_gemini(&[message]).await.expect("convert");
981        let value = serde_json::to_value(&contents).expect("serialize contents");
982        let part = &value[0]["parts"][0];
983
984        assert_eq!(part["thoughtSignature"], "sig-xyz");
985        assert_eq!(part["functionCall"]["name"], "lookup");
986    }
987
988    #[tokio::test]
989    async fn generated_tool_call_ids_carry_no_smuggled_signature() {
990        assert!(!tool_call_id().contains("|ts|"));
991    }
992
993    /// Signatures are Gemini's; another provider's state must not be replayed.
994    #[tokio::test]
995    async fn foreign_reasoning_state_is_not_sent_as_a_signature() {
996        let call = aither_core::llm::ToolCall::new("gemini_abc", "lookup", serde_json::json!({}))
997            .with_reasoning_state(ReasoningState::new("anthropic", "sig-from-claude"));
998        let message = Message::assistant_with_tool_calls("", vec![call]);
999
1000        let (_, contents) = messages_to_gemini(&[message]).await.expect("convert");
1001        let value = serde_json::to_value(&contents).expect("serialize contents");
1002        assert_eq!(value[0]["parts"][0].get("thoughtSignature"), None);
1003    }
1004
1005    fn call(id: &str, name: &str) -> aither_core::llm::ToolCall {
1006        aither_core::llm::ToolCall::new(id, name, serde_json::json!({}))
1007    }
1008
1009    fn responses(content: &serde_json::Value) -> Vec<(String, String)> {
1010        content["parts"]
1011            .as_array()
1012            .expect("parts")
1013            .iter()
1014            .map(|part| {
1015                (
1016                    part["functionResponse"]["name"]
1017                        .as_str()
1018                        .expect("function name")
1019                        .to_string(),
1020                    part["functionResponse"]["response"]["result"]
1021                        .as_str()
1022                        .expect("result")
1023                        .to_string(),
1024                )
1025            })
1026            .collect()
1027    }
1028
1029    fn pairs(items: [(&str, &str); 2]) -> Vec<(String, String)> {
1030        items
1031            .into_iter()
1032            .map(|(a, b)| (a.to_string(), b.to_string()))
1033            .collect()
1034    }
1035
1036    #[tokio::test]
1037    async fn parallel_tool_results_share_one_content() {
1038        let messages = [
1039            Message::assistant_with_tool_calls("", vec![call("a", "weather"), call("b", "time")]),
1040            Message::tool("a", "sunny"),
1041            Message::tool("b", "noon"),
1042        ];
1043        let (_, contents) = messages_to_gemini(&messages).await.expect("convert");
1044        let value = serde_json::to_value(&contents).expect("serialize");
1045        assert_eq!(value.as_array().expect("contents").len(), 2);
1046        assert_eq!(value[1]["role"], "user");
1047        assert_eq!(
1048            responses(&value[1]),
1049            pairs([("weather", "sunny"), ("time", "noon")])
1050        );
1051    }
1052
1053    #[tokio::test]
1054    async fn same_function_results_stay_distinct_and_ordered() {
1055        let messages = [
1056            Message::assistant_with_tool_calls("", vec![call("a", "lookup"), call("b", "lookup")]),
1057            Message::tool("a", "first"),
1058            Message::tool("b", "second"),
1059        ];
1060        let (_, contents) = messages_to_gemini(&messages).await.expect("convert");
1061        let value = serde_json::to_value(&contents).expect("serialize");
1062        assert_eq!(value.as_array().expect("contents").len(), 2);
1063        assert_eq!(
1064            responses(&value[1]),
1065            pairs([("lookup", "first"), ("lookup", "second")])
1066        );
1067    }
1068
1069    #[tokio::test]
1070    async fn out_of_order_results_follow_call_order_and_keep_signatures() {
1071        let signed =
1072            call("b", "time").with_reasoning_state(ReasoningState::new(PROVIDER_NAME, "sig-b"));
1073        let messages = [
1074            Message::assistant_with_tool_calls("", vec![call("a", "weather"), signed]),
1075            Message::tool("b", "noon"),
1076            Message::tool("a", "sunny"),
1077            Message::user("thanks"),
1078        ];
1079        let (_, contents) = messages_to_gemini(&messages).await.expect("convert");
1080        let value = serde_json::to_value(&contents).expect("serialize");
1081        assert_eq!(value.as_array().expect("contents").len(), 3);
1082        assert_eq!(
1083            responses(&value[1]),
1084            pairs([("weather", "sunny"), ("time", "noon")])
1085        );
1086        assert_eq!(value[1]["parts"][0].get("thoughtSignature"), None);
1087        assert_eq!(value[1]["parts"][1]["thoughtSignature"], "sig-b");
1088        assert_eq!(value[2]["parts"][0]["text"], "thanks");
1089    }
1090
1091    /// Gemini has no "no thinking" level; the caller should omit effort instead.
1092    #[test]
1093    fn none_effort_is_rejected() {
1094        let error =
1095            build_thinking_config(&Parameters::default().reasoning_effort(ReasoningEffort::None))
1096                .expect_err("None effort must fail");
1097        assert!(error.to_string().contains("no 'none' thinking level"));
1098    }
1099
1100    /// Depth and visibility are independent: asking for effort alone must still
1101    /// produce a config, and asking for thoughts alone must still produce one.
1102    #[test]
1103    fn effort_and_visibility_are_independent() {
1104        let effort_only =
1105            thinking_json(&Parameters::default().reasoning_effort(ReasoningEffort::High));
1106        assert_eq!(effort_only["thinkingLevel"], "high");
1107        assert_eq!(effort_only.get("includeThoughts"), None);
1108
1109        let thoughts_only = thinking_json(&Parameters::default().include_reasoning(true));
1110        assert_eq!(thoughts_only["includeThoughts"], true);
1111        assert_eq!(thoughts_only.get("thinkingLevel"), None);
1112
1113        assert!(
1114            build_thinking_config(&Parameters::default())
1115                .expect("no effort requested")
1116                .is_none()
1117        );
1118    }
1119
1120    /// These reached the wire only if `build_generation_config` populates them;
1121    /// they were declared on the struct but never filled.
1122    #[test]
1123    fn generation_config_forwards_every_sampling_parameter() {
1124        let params = Parameters::default()
1125            .seed(42)
1126            .presence_penalty(0.5)
1127            .frequency_penalty(0.25)
1128            .logprobs(true)
1129            .top_logprobs(3);
1130        let config = build_generation_config(&params, None)
1131            .expect("effort supported by Gemini")
1132            .expect("generation config");
1133        let value = serde_json::to_value(config).expect("serialize generation config");
1134        assert_eq!(value["seed"], 42);
1135        assert_eq!(value["presencePenalty"], 0.5);
1136        assert_eq!(value["frequencyPenalty"], 0.25);
1137        assert_eq!(value["responseLogprobs"], true);
1138        assert_eq!(value["logprobs"], 3);
1139    }
1140}