use super::types::{
Blob, FileData, FunctionCall, FunctionCallingConfig, FunctionCallingMode, FunctionDeclaration,
FunctionResponse, FunctionResponsePart, GeminiContent, GeminiPart, GeminiPartData,
GeminiRequest, GeminiResponse, GeminiTool, GeminiToolConfig, GenerationConfig,
GroundingMetadata, GroundingWeb, ThinkingConfig, ThinkingLevel, UsageMetadata,
};
use crate::effort;
use crate::error::{LlmError, LlmErrorKind, ProviderError};
use crate::types::{
Attachment, ChatRequest, Content, ContentPart, Effort, Message, Role, StopReason, StreamEvent,
ThinkingDisplay, ToolChoice, ToolResult, ToolUse, Usage, WebCitation, WebSearchResult,
replay_safe_tool_args,
};
use anyhow::Result;
use std::collections::{BTreeSet, HashMap};
const SPELLING: &[(Effort, ThinkingLevel)] = &[
(Effort::Min, ThinkingLevel::Minimal),
(Effort::Low, ThinkingLevel::Low),
(Effort::Medium, ThinkingLevel::Medium),
(Effort::High, ThinkingLevel::High),
(Effort::XHigh, ThinkingLevel::XHigh),
];
const DEFAULT_LEVELS: &[Effort] = &[Effort::Low, Effort::Medium, Effort::High];
pub(crate) fn effort_levels(declared: Option<&[Effort]>) -> Vec<Effort> {
effort::offered_levels(SPELLING, declared.unwrap_or(DEFAULT_LEVELS))
}
fn thinking_config(effort: Option<Effort>, declared: Option<&[Effort]>) -> Option<ThinkingConfig> {
let levels = declared.unwrap_or(DEFAULT_LEVELS);
let thinking_level = effort::resolve_among(SPELLING, levels, effort?)?;
Some(ThinkingConfig { include_thoughts: None, thinking_level: Some(thinking_level) })
}
fn tool_use_from_call(
function_call: FunctionCall,
signature: Option<String>,
counter: &mut usize,
) -> ToolUse {
let FunctionCall { id, name, args } = function_call;
let id = id.unwrap_or_else(|| format!("call_{name}_{counter}"));
*counter += 1;
ToolUse { id, name, args, malformed_args: None, signature }
}
pub(in crate::gemini) fn stream_events_from_part(
part: GeminiPart,
tool_call_counter: &mut usize,
) -> Vec<StreamEvent> {
let GeminiPart { thought, thought_signature, data } = part;
let (text, inline_data) = match data {
Some(GeminiPartData::FunctionCall { function_call }) => {
return vec![StreamEvent::ToolUse(tool_use_from_call(
function_call,
thought_signature,
tool_call_counter,
))];
}
Some(GeminiPartData::Text { text }) => (Some(text), None),
Some(GeminiPartData::InlineData { inline_data }) => (None, Some(inline_data)),
_ => (None, None),
};
let mut events = Vec::new();
if let Some(text) = text {
if thought {
events
.push(StreamEvent::ThinkingDelta { thinking: text, signature: thought_signature });
return events;
}
events.push(StreamEvent::TextDelta(text));
}
if thought_signature.is_some() {
events.push(StreamEvent::ThinkingDelta {
thinking: String::new(),
signature: thought_signature,
});
}
if let Some(blob) = inline_data {
events.push(StreamEvent::ContentPart(ContentPart::document(blob.mime_type, blob.data)));
}
events
}
fn grounding_chunk_indices(grounding: &GroundingMetadata) -> Vec<usize> {
let mut used: BTreeSet<usize> = BTreeSet::new();
for support in &grounding.grounding_supports {
used.extend(support.grounding_chunk_indices.iter().copied());
}
if used.is_empty() {
(0..grounding.grounding_chunks.len()).collect()
} else {
used.into_iter().collect()
}
}
fn grounding_web_entries(grounding: &GroundingMetadata) -> Vec<GroundingWeb> {
let indices = grounding_chunk_indices(grounding);
let mut seen_uris: BTreeSet<&str> = BTreeSet::new();
let mut entries = Vec::new();
for idx in indices {
let Some(chunk) = grounding.grounding_chunks.get(idx) else { continue };
let Some(web) = chunk.web.as_ref() else { continue };
if web.uri.is_empty() || !seen_uris.insert(web.uri.as_str()) {
continue;
}
entries.push(web.clone());
}
entries
}
pub(in crate::gemini) fn format_grounding_sources(grounding: &GroundingMetadata) -> Option<String> {
let lines = grounding_web_entries(grounding)
.into_iter()
.map(|web| {
if web.title.is_empty() {
format!("- {}", web.uri)
} else {
format!("- {} ({})", web.title, web.uri)
}
})
.collect::<Vec<String>>();
if lines.is_empty() {
return None;
}
Some(format!("\n\nSources:\n{}", lines.join("\n")))
}
fn gemini_part_for_image(image: Attachment) -> GeminiPart {
match image {
Attachment::Base64 { media_type, data } => {
GeminiPart::inline_data(Blob { mime_type: media_type, data })
}
Attachment::Url { url } => {
GeminiPart::file_data(FileData { mime_type: "image".to_string(), file_uri: url })
}
}
}
fn gemini_part_for_document(document: Attachment) -> GeminiPart {
match document {
Attachment::Base64 { media_type, data } => {
GeminiPart::inline_data(Blob { mime_type: media_type, data })
}
Attachment::Url { url } => GeminiPart::text(format!("[Document URL: {url}]")),
}
}
impl From<&ToolUse> for GeminiPart {
fn from(tool_use: &ToolUse) -> Self {
GeminiPart::function_call(
FunctionCall {
id: Some(tool_use.id.clone()),
name: tool_use.name.clone(),
args: replay_safe_tool_args(tool_use).into_owned(),
},
tool_use.signature.clone(),
)
}
}
fn function_response_parts(
result: &ToolResult,
tool_names: &HashMap<&str, &str>,
) -> Vec<GeminiPart> {
let name = tool_names
.get(result.tool_use_id.as_str())
.copied()
.unwrap_or_else(|| tool_name_from_id(&result.tool_use_id))
.to_string();
let text = result.content.as_text();
let payload = match serde_json::from_str::<serde_json::Value>(&text) {
Ok(serde_json::Value::String(s)) => serde_json::Value::String(s),
Ok(v) => v,
Err(_) => serde_json::Value::String(text),
};
let response = if result.is_error {
serde_json::json!({ "error": payload })
} else {
serde_json::json!({ "output": payload })
};
let function_parts: Vec<FunctionResponsePart> = result
.content
.images()
.map(|image| FunctionResponsePart::from_attachment(image, "Image"))
.chain(
result
.content
.documents()
.map(|document| FunctionResponsePart::from_attachment(document, "Document")),
)
.collect();
let parts = if function_parts.is_empty() { None } else { Some(function_parts) };
let id = Some(result.tool_use_id.clone());
vec![GeminiPart::function_response(FunctionResponse { id, name, response, parts })]
}
fn tool_name_from_id(id: &str) -> &str {
id.strip_prefix("call_").and_then(|s| s.rsplit_once('_').map(|(name, _)| name)).unwrap_or(id)
}
impl FunctionResponsePart {
fn from_attachment(attachment: &Attachment, kind: &str) -> Self {
let inline_data = match attachment {
Attachment::Base64 { media_type, data } => {
Blob { mime_type: media_type.clone(), data: data.clone() }
}
Attachment::Url { url } => {
Blob { mime_type: "text/plain".to_string(), data: format!("[{kind} URL: {url}]") }
}
};
FunctionResponsePart { inline_data }
}
}
fn gemini_parts(content: &Content, tool_names: &HashMap<&str, &str>) -> Vec<GeminiPart> {
match content {
Content::Text(text) => vec![GeminiPart::text(text.clone())],
Content::Parts(parts) => {
parts.iter().flat_map(|p| gemini_parts_for_part(p, tool_names)).collect()
}
}
}
fn gemini_parts_for_part(part: &ContentPart, tool_names: &HashMap<&str, &str>) -> Vec<GeminiPart> {
match part {
ContentPart::Text(text) => vec![GeminiPart::text(text.clone())],
ContentPart::Image(image) => vec![gemini_part_for_image(image.clone())],
ContentPart::Document(document) => vec![gemini_part_for_document(document.clone())],
ContentPart::Thinking { text, signature } => {
vec![GeminiPart::thought(text.clone(), signature.clone())]
}
ContentPart::RedactedThinking { .. } => vec![],
ContentPart::ToolUse(tool_use) => vec![GeminiPart::from(tool_use)],
ContentPart::ToolResult(result) => function_response_parts(result, tool_names),
}
}
fn role_to_str(role: &Role) -> &str {
match role {
Role::User => "user",
Role::Model => "model",
Role::System => "user",
Role::Custom(s) => s,
}
}
pub(in crate::gemini) fn gemini_content(
message: &Message,
tool_names: &HashMap<&str, &str>,
) -> GeminiContent {
GeminiContent {
role: Some(role_to_str(&message.role).to_string()),
parts: gemini_parts(&message.content, tool_names),
}
}
pub(in crate::gemini) fn to_gemini_request(
request: &ChatRequest,
thinking_display: Option<ThinkingDisplay>,
declared: Option<&[Effort]>,
) -> Result<GeminiRequest> {
let system_instruction = {
let parts: Vec<GeminiPart> =
request.system_prompts().map(|s| GeminiPart::text(s.to_string())).collect();
(!parts.is_empty()).then_some(GeminiContent {
role: None, parts,
})
};
let tool_names: HashMap<&str, &str> = request
.messages
.iter()
.filter_map(|m| match &m.content {
Content::Parts(parts) => Some(parts),
Content::Text(_) => None,
})
.flatten()
.filter_map(|p| match p {
ContentPart::ToolUse(tu) => Some((tu.id.as_str(), tu.name.as_str())),
_ => None,
})
.collect();
let contents: Vec<GeminiContent> =
request.messages.iter().map(|m| gemini_content(m.as_ref(), &tool_names)).collect();
let gemini_tools = if request.tools.is_empty() {
None
} else {
Some(vec![GeminiTool::function_declarations(
request
.tools
.iter()
.cloned()
.map(|tool| FunctionDeclaration {
name: tool.name,
description: tool.description.unwrap_or_default(),
parameters: tool.input_schema,
})
.collect(),
)])
};
let tool_choice = request.resolved_tool_choice()?;
let tool_config = gemini_tools.as_ref().map(|_| {
let (mode, allowed_function_names) = match tool_choice {
None => (FunctionCallingMode::Auto, None),
Some(ToolChoice::Required) => (FunctionCallingMode::Any, None),
Some(ToolChoice::Tool(name)) => (FunctionCallingMode::Any, Some(vec![name.clone()])),
Some(ToolChoice::Forbid) => (FunctionCallingMode::None, None),
};
GeminiToolConfig {
function_calling_config: FunctionCallingConfig { mode, allowed_function_names },
}
});
let mut thinking_config = thinking_config(request.effort, declared);
tracing::debug!(
model = %request.model,
effort = ?request.effort,
thinking_level = ?thinking_config.as_ref().and_then(|config| config.thinking_level),
"Gemini effort config"
);
if let Some(config) = &mut thinking_config {
config.include_thoughts = thinking_display.map(|display| match display {
ThinkingDisplay::Off => false,
ThinkingDisplay::Concise | ThinkingDisplay::Detailed => true,
});
}
let generation_config = if request.max_tokens.is_some()
|| request.stop_sequences.is_some()
|| thinking_config.is_some()
{
Some(GenerationConfig {
max_output_tokens: request.max_tokens,
stop_sequences: request.stop_sequences.clone(),
thinking_config,
})
} else {
None
};
Ok(GeminiRequest {
contents,
system_instruction,
generation_config,
tools: gemini_tools,
tool_config,
})
}
impl From<&UsageMetadata> for Usage {
fn from(m: &UsageMetadata) -> Self {
Usage {
input_tokens: m.prompt_token_count,
output_tokens: m
.candidates_token_count
.saturating_add(m.thoughts_token_count.unwrap_or(0)),
cache_read_tokens: m.cached_content_token_count,
cache_write_tokens: None,
}
}
}
pub(in crate::gemini) fn stop_reason(value: &str) -> StopReason {
match value {
"STOP" => StopReason::EndTurn,
"MAX_TOKENS" => StopReason::MaxTokens,
"PROHIBITED_CONTENT" | "SAFETY" | "SPII" | "RECITATION" | "BLOCKLIST" | "LANGUAGE" => {
StopReason::Refusal
}
other => StopReason::Other(other.to_string()),
}
}
pub(in crate::gemini) fn finish_reason_error(reason: &str) -> Option<LlmError> {
if reason != "MALFORMED_FUNCTION_CALL" {
return None;
}
Some(LlmError::new(
LlmErrorKind::Unknown,
ProviderError {
provider_code: Some(reason.to_string()),
message: "the model generated a malformed function call; retrying usually succeeds"
.to_string(),
..Default::default()
},
))
}
pub(in crate::gemini) fn prompt_blocked_error(reason: &str) -> LlmError {
tracing::warn!(block_reason = reason, "gemini blocked the prompt");
LlmError::new(
LlmErrorKind::ContentPolicy,
ProviderError {
provider_code: Some(reason.to_string()),
message: format!("Gemini blocked the prompt (blockReason: {reason})"),
..Default::default()
},
)
}
impl TryFrom<GeminiResponse> for WebSearchResult {
type Error = LlmError;
fn try_from(response: GeminiResponse) -> Result<Self, LlmError> {
let candidate = response.candidates.first().ok_or_else(|| {
LlmError::malformed_response(format!(
"No candidates in Gemini response ({response:?}) for web search"
))
})?;
let content = candidate
.content
.parts
.iter()
.filter_map(|p| p.text_value().filter(|t| !t.is_empty()))
.collect::<Vec<&str>>()
.join("\n");
let mut citations: Vec<WebCitation> = Vec::new();
if let Some(ref grounding) = candidate.grounding_metadata {
for web in grounding_web_entries(grounding) {
let GroundingWeb { uri, title } = web;
let title = if title.is_empty() { uri.clone() } else { title };
citations.push(WebCitation { title, uri });
}
}
Ok(WebSearchResult { content: Content::Text(content), citations })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn thinking_level(effort: Effort, declared: Option<&[Effort]>) -> serde_json::Value {
let config = thinking_config(Some(effort), declared).expect("Gemini always reasons");
let value = serde_json::to_value(config).expect("thinking config should serialize");
assert!(value.get("includeThoughts").is_none());
value["thinkingLevel"].clone()
}
#[test]
fn undeclared_models_reason_at_low_medium_or_high() {
assert_eq!(effort_levels(None), vec![Effort::Low, Effort::Medium, Effort::High]);
for (requested, expected) in [
(Effort::Min, "LOW"),
(Effort::Low, "LOW"),
(Effort::Medium, "MEDIUM"),
(Effort::High, "HIGH"),
(Effort::XHigh, "HIGH"),
(Effort::Max, "HIGH"),
] {
assert_eq!(thinking_level(requested, None), expected, "at {requested}");
}
}
#[test]
fn hydrogen_declared_xhigh_reaches_the_wire() {
let declared = [Effort::Low, Effort::Medium, Effort::High, Effort::XHigh];
assert_eq!(effort_levels(Some(&declared)), declared);
assert_eq!(thinking_level(Effort::XHigh, Some(&declared)), "XHIGH");
assert_eq!(thinking_level(Effort::Max, Some(&declared)), "XHIGH");
}
#[test]
fn a_declared_min_sends_the_minimal_thinking_level() {
let declared = [Effort::Min, Effort::Low, Effort::High];
assert_eq!(effort_levels(Some(&declared)), declared);
assert_eq!(thinking_level(Effort::Min, Some(&declared)), "MINIMAL");
assert_eq!(thinking_level(Effort::Medium, Some(&declared)), "LOW");
}
}