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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::types::{Content, ModelSpec, StopReason, Usage, WebCitation, WebSearchResult};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use tracing::{debug, warn};

// ============================================================================
// Request Types
// ============================================================================

/// Request structure for OpenAI Response API
#[derive(Debug, Default, Serialize)]
pub(in crate::openai) struct OpenAiRequest {
    pub model: String,
    pub input: Vec<InputItem>,
    pub tools: Vec<OpenAiTool>,
    pub tool_choice: OpenAiToolChoice,
    pub parallel_tool_calls: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<u32>,
    /// Sampling temperature. Omitted when the model reasons: reasoning
    /// models reject sampling parameters with a 400.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ReasoningConfig>,
    pub stream: bool,
    pub include: Vec<String>,
    /// Always false: the provider stores nothing from a call.
    pub store: bool,
}

/// `tool_choice` on the Responses API: a mode string, or an object naming
/// the function the model must call. Defaults to `Auto`, the API's own
/// default.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(in crate::openai) enum OpenAiToolChoice {
    #[default]
    Auto,
    None,
    Required,
    Function {
        name: String,
    },
}

impl Serialize for OpenAiToolChoice {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::None => serializer.serialize_str("none"),
            Self::Required => serializer.serialize_str("required"),
            Self::Function { name } => {
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("type", "function")?;
                map.serialize_entry("name", name)?;
                map.end()
            }
        }
    }
}

/// Individual input item in the top-level `input` array.
/// Only types accepted by the Responses API are valid here (message, function_call, etc.).
/// Images and files live in message content or structured function-call output.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum InputItem {
    Message {
        content: Vec<MessageContentPart>,
        role: String,
        /// The model's own label on its message, sent back as it came.
        #[serde(skip_serializing_if = "Option::is_none")]
        phase: Option<String>,
    },
    FunctionCall {
        call_id: String,
        name: String,
        arguments: String,
    },
    FunctionCallOutput {
        call_id: String,
        output: FunctionOutput,
    },
    /// The model's reasoning, handed back where it produced it. The API
    /// requires `summary` and reads only `encrypted_content`, so the summary
    /// stays empty.
    Reasoning {
        summary: Vec<String>,
        encrypted_content: String,
    },
}

/// Text-only results keep the string form; attachments use ordered content parts.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub(in crate::openai) enum FunctionOutput {
    Text(String),
    Parts(Vec<MessageContentPart>),
}

impl InputItem {
    pub(in crate::openai) fn message(role: &str, content: Vec<MessageContentPart>) -> Self {
        Self::Message { content, role: role.to_string(), phase: None }
    }
}

/// Content parts inside a message or structured function-call output.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum MessageContentPart {
    #[serde(rename = "input_text")]
    Text { text: String },
    #[serde(rename = "output_text")]
    OutputText { text: String },
    #[serde(rename = "input_image")]
    Image { image_url: String },
    #[serde(rename = "input_file")]
    File {
        #[serde(skip_serializing_if = "Option::is_none")]
        filename: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        file_data: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        file_url: Option<String>,
    },
}

/// Tool definition for Response API: a function the caller runs, or the
/// hosted search a search call offers.
/// Note: Response API uses a flat structure (name, description, parameters at top level),
/// unlike the Chat Completions API, which nests them under 'function'.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai) enum OpenAiTool {
    #[serde(rename = "function")]
    Function {
        name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        parameters: serde_json::Value,
    },

    /// Bare `{"type": "web_search"}`. No tuning fields: `search_context_size`
    /// is optional on OpenAI (default `medium`) and xAI rejects the argument
    /// with a 400.
    #[serde(rename = "web_search")]
    WebSearch,
}

/// Reasoning configuration
#[derive(Debug, Serialize)]
pub(in crate::openai) struct ReasoningConfig {
    pub effort: ReasoningEffort,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<&'static str>,
}

#[derive(Debug, Clone, Copy, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub(in crate::openai) enum ReasoningEffort {
    /// Reasoning off, on models that allow it.
    None,
    Low,
    Medium,
    High,
    XHigh,
    Max,
}

// ============================================================================
// Response Types
// ============================================================================

/// A complete Response API response: what web search reads. Chat responses
/// arrive as a stream and are never decoded in this shape.
#[derive(Debug, Deserialize)]
pub(in crate::openai) struct OpenAiResponseCompletion {
    pub status: String,
    pub output: Vec<OutputItem>,
}

/// Individual output item. Only messages are read; `web_search_call` and
/// every other item type decode as `Unknown`.
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub(in crate::openai) enum OutputItem {
    #[serde(rename = "message")]
    Message { content: Vec<OutputContent> },
    #[serde(other)]
    Unknown,
}

/// Content within an output message
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub(in crate::openai) enum OutputContent {
    #[serde(rename = "output_text")]
    OutputText {
        text: String,
        #[serde(default)]
        annotations: Vec<OutputAnnotation>,
    },
    #[serde(rename = "text")]
    Text {
        text: String,
        #[serde(default)]
        annotations: Vec<OutputAnnotation>,
    },
    #[serde(other)]
    Unknown,
}

impl OutputContent {
    fn text(&self) -> Option<&str> {
        match self {
            OutputContent::OutputText { text, .. } | OutputContent::Text { text, .. } => Some(text),
            OutputContent::Unknown => None,
        }
    }

    fn annotations(&self) -> &[OutputAnnotation] {
        match self {
            OutputContent::OutputText { annotations, .. }
            | OutputContent::Text { annotations, .. } => annotations,
            OutputContent::Unknown => &[],
        }
    }
}

/// Output Annotations
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(in crate::openai) enum OutputAnnotation {
    UrlCitation(UrlCitationAnnotation),
    Other(#[allow(dead_code)] serde_json::Value), // Unknown or malformed annotations (e.g. {}, unknown type)
}

#[derive(Debug, Deserialize)]
pub(in crate::openai) struct UrlCitationAnnotation {
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    text: Option<String>,
}

/// Nested token breakdown inside `input_tokens_details` (OpenAI Responses API).
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct OpenAiInputTokensDetails {
    #[serde(default)]
    cached_tokens: u32,
    #[serde(default)]
    cache_write_tokens: Option<u32>,
}

/// Usage information
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct OpenAiUsage {
    #[serde(default)]
    pub input_tokens: u32,
    #[serde(default)]
    pub output_tokens: u32,
    /// The cache-read and cache-write subsets of `input_tokens`.
    /// Field name is `input_tokens_details` in the Responses API
    /// (vs `prompt_tokens_details` in the older Chat Completions API).
    #[serde(default)]
    pub input_tokens_details: Option<OpenAiInputTokensDetails>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai) struct ListModelsResponse {
    pub data: Vec<OpenAiModel>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai) struct OpenAiModel {
    id: String,
    #[serde(default)]
    created: Option<i64>,
    #[serde(default)]
    owned_by: Option<String>,
}

impl From<OpenAiModel> for ModelSpec {
    fn from(model: OpenAiModel) -> Self {
        let description = openai_model_description(&model);
        ModelSpec { id: model.id, description, ..Default::default() }
    }
}

fn openai_model_description(model: &OpenAiModel) -> Option<String> {
    let mut parts = Vec::new();

    if let Some(owner) = model.owned_by.as_deref().map(str::trim).filter(|owner| !owner.is_empty())
    {
        parts.push(format!("Owned by {owner}"));
    }

    if let Some(created) = model.created.and_then(format_created_date) {
        parts.push(format!("created {created}"));
    }

    if parts.is_empty() { None } else { Some(parts.join(", ")) }
}

fn format_created_date(timestamp: i64) -> Option<String> {
    chrono::DateTime::from_timestamp(timestamp, 0).map(|dt| dt.date_naive().to_string())
}

// ============================================================================
// Streaming Types
// ============================================================================

/// One flat struct for every event shape on the Response API stream; `kind`
/// is the event type.
#[derive(Debug, Deserialize, Default)]
pub(in crate::openai) struct ResponseStreamEvent {
    #[serde(rename = "type", default)]
    pub kind: String,
    #[serde(default)]
    pub response: Option<serde_json::Value>,
    #[serde(default)]
    pub item: Option<serde_json::Value>,
    #[serde(default)]
    pub delta: Option<String>,
}

// ============================================================================
// Conversions
// ============================================================================

impl From<OpenAiUsage> for Usage {
    fn from(usage: OpenAiUsage) -> Self {
        // `input_tokens` is cache-inclusive (see `Usage`). GPT-5.6 and later
        // report the cache-write count; older models and some providers on
        // this wire do not.
        let details = usage.input_tokens_details;
        Usage {
            input_tokens: usage.input_tokens,
            output_tokens: usage.output_tokens,
            cache_read_tokens: details.as_ref().map(|d| d.cached_tokens),
            cache_write_tokens: details.and_then(|d| d.cache_write_tokens),
        }
    }
}

pub(in crate::openai) fn stop_reason_from_status(value: &str) -> StopReason {
    match value {
        // Response API top-level status field
        "completed" => StopReason::EndTurn,
        // Output-limit truncation: the partial output is preserved.
        "incomplete" => StopReason::MaxTokens,
        other => StopReason::Other(other.to_string()),
    }
}

/// The non-empty text of every message output item.
fn extract_text_from_messages(output: &[OutputItem]) -> Vec<String> {
    let mut text_parts = Vec::new();

    for item in output {
        if let OutputItem::Message { content, .. } = item {
            for content_item in content {
                if let Some(text) = content_item.text().filter(|text| !text.is_empty()) {
                    text_parts.push(text.to_string());
                }
            }
        }
    }

    text_parts
}

impl TryFrom<OpenAiResponseCompletion> for WebSearchResult {
    type Error = anyhow::Error;

    fn try_from(completion: OpenAiResponseCompletion) -> Result<Self> {
        let OpenAiResponseCompletion { status, output, .. } = completion;

        if status != "completed" {
            anyhow::bail!("Response not completed, status: {status}");
        }

        let text_parts = extract_text_from_messages(&output);

        if text_parts.is_empty() {
            warn!("No text content found in web search response. Output items: {}", output.len());
            for (idx, item) in output.iter().enumerate() {
                debug!("Output item {idx}: {item:?}");
            }
        }

        let mut citations: Vec<WebCitation> = Vec::new();
        let mut seen_urls: HashSet<String> = HashSet::new();

        for item in &output {
            if let OutputItem::Message { content, .. } = item {
                for content_item in content {
                    for annotation in content_item.annotations() {
                        let OutputAnnotation::UrlCitation(UrlCitationAnnotation {
                            url,
                            title,
                            text: annotation_text,
                            ..
                        }) = annotation
                        else {
                            continue;
                        };

                        let Some(url) = url else { continue };
                        let trimmed = url.trim();
                        if trimmed.is_empty() {
                            continue;
                        }

                        if !seen_urls.insert(trimmed.to_string()) {
                            continue;
                        }

                        // Title, else the annotated text, else the URL.
                        let citation_title = title
                            .as_ref()
                            .filter(|t| !t.trim().is_empty())
                            .or_else(|| {
                                annotation_text
                                    .as_ref()
                                    .filter(|txt| !txt.trim().is_empty() && txt.as_str() != "{}")
                            })
                            .cloned()
                            .unwrap_or_else(|| trimmed.to_string());

                        citations
                            .push(WebCitation { title: citation_title, uri: trimmed.to_string() });
                    }
                }
            }
        }

        let content = Content::Text(text_parts.join("\n"));
        Ok(WebSearchResult { content, citations })
    }
}