ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

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};

/// Wire spelling for each supported Gemini thinking level.
const SPELLING: &[(Effort, ThinkingLevel)] = &[
    (Effort::Min, ThinkingLevel::Minimal),
    (Effort::Low, ThinkingLevel::Low),
    (Effort::Medium, ThinkingLevel::Medium),
    (Effort::High, ThinkingLevel::High),
    (Effort::XHigh, ThinkingLevel::XHigh),
];

/// The levels a model takes when it declares none: Gemini 4 and 3.8 always
/// reason, at `low`, `medium` or `high`. A model that takes `minimal`
/// declares `min`.
const DEFAULT_LEVELS: &[Effort] = &[Effort::Low, Effort::Medium, Effort::High];

/// The distinct effort levels a Gemini model exposes.
pub(crate) fn effort_levels(declared: Option<&[Effort]>) -> Vec<Effort> {
    effort::offered_levels(SPELLING, declared.unwrap_or(DEFAULT_LEVELS))
}

/// The thinking config for `effort` on a model that declares `declared`.
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;
    // Gemini's id is unique per call. A server that sends none gets ours,
    // which is unique only within one response.
    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 {
            // The signature rides on the same part — emit one delta carrying
            // both, rather than relying on the response builder to merge a
            // signature-only delta into the preceding thinking block.
            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 {
        // Vertex AI documents `thoughtSignature` on the Part that contains `functionCall`,
        // not nested inside the functionCall itself.
        // Preserve tool-call signatures by attaching them at the Part level.
        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(),
        )
    }
}

/// A `functionResponse` carries its call's id and function name. The name
/// comes from the originating tool call in the conversation — not from the
/// tool-use id, whose shape depends on which provider issued it.
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 })]
}

/// Fallback for a result whose originating call is no longer in the
/// conversation (the caller trimmed it): recover the name from the
/// `call_{name}_{counter}` id this client mints when the server sends none,
/// or send the raw id as a last resort.
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 {
    /// Inline data for a base64 attachment; a URL becomes a text placeholder
    /// labelled with `kind` since Gemini cannot fetch it from a tool result.
    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),
    }
}

/// `declared` is the effort levels the model declares, if any.
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, // systemInstruction should not have a role field per Gemini API spec
            parts,
        })
    };

    // Tool-use id → function name pairs from prior calls in the conversation, so
    // each functionResponse carries its stored name even when the id came
    // from another provider before a mid-conversation switch. Tool results
    // arrive bundled in single messages, so no merging is needed.
    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(),
        )])
    };

    // Without a tool choice, AUTO leaves the model free to answer in text or
    // call a tool. Not VALIDATED: its constrained decoding 400s with a bare
    // "invalid argument" on very complex schemas (thousands of nodes, seen on
    // MCP servers), failing the whole request; malformed arguments are
    // returned to the model instead. No config without function declarations:
    // built-in tools like google_search don't accept functionCallingConfig.
    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,
            // candidatesTokenCount excludes thinking tokens; Gemini reports
            // those separately as thoughtsTokenCount, so output is the sum.
            output_tokens: m
                .candidates_token_count
                .saturating_add(m.thoughts_token_count.unwrap_or(0)),
            // `promptTokenCount` is cache-inclusive (see `Usage`); Gemini has
            // no cache-write count.
            cache_read_tokens: m.cached_content_token_count,
            cache_write_tokens: None,
        }
    }
}

/// <https://ai.google.dev/api/generate-content#FinishReason>
pub(in crate::gemini) fn stop_reason(value: &str) -> StopReason {
    match value {
        "STOP" => StopReason::EndTurn,
        "MAX_TOKENS" => StopReason::MaxTokens,
        // Every "content was flagged / contains forbidden terms" reason —
        // the response was cut short, not a natural end of turn.
        "PROHIBITED_CONTENT" | "SAFETY" | "SPII" | "RECITATION" | "BLOCKLIST" | "LANGUAGE" => {
            StopReason::Refusal
        }
        other => StopReason::Other(other.to_string()),
    }
}

/// `MALFORMED_FUNCTION_CALL` means Gemini aborted the candidate and dropped
/// the invalid call entirely, usually leaving empty content. Treating that as
/// a normal stop would pass an empty reply off as complete, so surface it as
/// an error.
/// Transient in practice: retrying the same request usually succeeds.
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()
        },
    ))
}

/// `promptFeedback.blockReason`: Gemini rejected the prompt itself and
/// generates nothing, so the call fails terminally. Distinct from a candidate
/// `finishReason`, which ends a response that was being generated.
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");
    }
}