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

use crate::openai_compatible::{ReasoningEffort, SearchOptions, ThinkingConfig};
use crate::types::{Content, ModelSpec, StopReason, Usage, WebCitation, WebSearchResult};
use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::HashSet;

/// OpenAI message structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIMessage {
    pub role: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<OpenAIContent>,
    /// DeepSeek reasoning content - required for DeepSeek thinking models (V4+) when tool_calls are present
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OpenAIToolCall>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
}

impl OpenAIMessage {
    pub(in crate::openai_compatible) fn new(
        role: impl Into<String>,
        content: Option<OpenAIContent>,
    ) -> Self {
        Self {
            role: role.into(),
            content,
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    pub(in crate::openai_compatible) fn system_text(text: String) -> Self {
        Self::new("system", Some(OpenAIContent::Text(text)))
    }

    /// Prepend text to the message content (for models that don't support system role).
    pub(in crate::openai_compatible) fn prepend_text(&mut self, prefix: &str) {
        match &mut self.content {
            Some(OpenAIContent::Text(text)) => {
                *text = format!("{prefix}\n\n{text}");
            }
            Some(OpenAIContent::List(items)) => {
                items.insert(0, OpenAIContentItem::Text { text: prefix.to_string() });
            }
            None => {
                self.content = Some(OpenAIContent::Text(prefix.to_string()));
            }
        }
    }

    pub(in crate::openai_compatible) fn with_tool_calls(
        role: impl Into<String>,
        content: Option<OpenAIContent>,
        reasoning_content: Option<String>,
        tool_calls: Vec<OpenAIToolCall>,
    ) -> Self {
        Self {
            role: role.into(),
            content,
            reasoning_content,
            tool_calls: Some(tool_calls),
            tool_call_id: None,
        }
    }

    pub(in crate::openai_compatible) fn tool_response(
        tool_use_id: String,
        content: OpenAIContent,
    ) -> Self {
        Self {
            role: "tool".to_string(),
            content: Some(content),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: Some(tool_use_id),
        }
    }
}

/// OpenAI request structure
#[derive(Debug, Default, Serialize)]
pub(in crate::openai_compatible) struct OpenAIRequest {
    pub(in crate::openai_compatible) model: String,
    pub(in crate::openai_compatible) messages: Vec<OpenAIMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) reasoning_effort: Option<ReasoningEffort>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) stream_options: Option<OpenAIStreamOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) stop: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) tools: Option<Vec<OpenAITool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) tool_choice: Option<OpenAIToolChoice>,
    /// Provider-native thinking parameter, when the target accepts a `thinking`
    /// object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) thinking: Option<ThinkingConfig>,
    /// Qwen enable_thinking parameter (top-level bool)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) enable_thinking: Option<bool>,
    /// Qwen enable_search parameter (top-level bool)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) enable_search: Option<bool>,
    /// Qwen search_options parameter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(in crate::openai_compatible) search_options: Option<SearchOptions>,
    /// Provider-specific request escape hatch. Keep typed fields above when a
    /// parameter has stable cross-provider semantics.
    #[serde(flatten)]
    pub(in crate::openai_compatible) extra_body: Map<String, Value>,
}

/// `tool_choice` on Chat Completions: a mode string, or an object naming the
/// function the model must call. Omitted for the server's default (`auto`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::openai_compatible) enum OpenAIToolChoice {
    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::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("function", &serde_json::json!({ "name": name }))?;
                map.end()
            }
        }
    }
}

#[derive(Debug, Serialize)]
pub(in crate::openai_compatible) struct OpenAIStreamOptions {
    include_usage: bool,
}

impl OpenAIStreamOptions {
    pub(in crate::openai_compatible) fn include_usage() -> Self {
        Self { include_usage: true }
    }
}

#[derive(Debug, Serialize)]
pub(in crate::openai_compatible) struct OpenAITool {
    #[serde(rename = "type")]
    pub(in crate::openai_compatible) tool_type: String,
    pub(in crate::openai_compatible) function: OpenAIToolFunction,
}

#[derive(Debug, Serialize)]
pub(in crate::openai_compatible) struct OpenAIToolFunction {
    pub(in crate::openai_compatible) name: String,
    pub(in crate::openai_compatible) description: String,
    pub(in crate::openai_compatible) parameters: serde_json::Value,
}

/// A complete chat completion: what web search reads. Chat responses arrive
/// as a stream and are never decoded in this shape.
#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAICompletion {
    choices: Vec<OpenAIChoice>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIChoice {
    message: OpenAIResponseMessage,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIResponseMessage {
    content: Option<String>,
    #[serde(default)]
    annotations: Vec<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIToolCall {
    pub(in crate::openai_compatible) id: String,
    #[serde(rename = "type")]
    pub(in crate::openai_compatible) call_type: String,
    pub(in crate::openai_compatible) function: FunctionCall,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(in crate::openai_compatible) struct FunctionCall {
    pub(in crate::openai_compatible) name: String,
    pub(in crate::openai_compatible) arguments: String,
}

#[derive(Debug, Default, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIUsage {
    #[serde(default)]
    prompt_tokens: u32,
    #[serde(default)]
    completion_tokens: u32,
    #[serde(default)]
    prompt_tokens_details: Option<OpenAIPromptTokensDetails>,
    #[serde(default)]
    prompt_cache_hit_tokens: Option<u32>,
}

#[derive(Debug, Default, Deserialize)]
struct OpenAIPromptTokensDetails {
    #[serde(default)]
    cached_tokens: u32,
    #[serde(default)]
    cache_write_tokens: Option<u32>,
}

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

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(in crate::openai_compatible) enum OpenAIModel {
    Object {
        id: String,
        #[serde(default)]
        created: Option<i64>,
        #[serde(default)]
        owned_by: Option<String>,
    },
    Id(String),
}

impl From<OpenAIModel> for ModelSpec {
    fn from(model: OpenAIModel) -> Self {
        match model {
            OpenAIModel::Object { id, created, owned_by } => {
                let description = openai_model_description(created, owned_by.as_deref());
                ModelSpec { id, description, ..Default::default() }
            }
            OpenAIModel::Id(id) => ModelSpec { id, ..Default::default() },
        }
    }
}

fn openai_model_description(created: Option<i64>, owned_by: Option<&str>) -> Option<String> {
    let mut parts = Vec::new();

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

    if let Some(created) = 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 response types
#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct ChatCompletionChunk {
    /// Defaulted: in-stream error payloads carry no `choices`, and some
    /// providers omit the field on the final usage-only chunk.
    #[serde(default)]
    pub(in crate::openai_compatible) choices: Vec<OpenAIStreamChoice>,
    #[serde(default)]
    pub(in crate::openai_compatible) usage: Option<OpenAIUsage>,
    /// In-stream error event. Local servers (notably LM Studio) abort a
    /// stream with an SSE `event: error` whose data is
    /// `{"error":{"message":...}}` — e.g. "Model unloaded." or "Context size
    /// has been exceeded." — instead of a non-success HTTP status.
    #[serde(default)]
    pub(in crate::openai_compatible) error: Option<Value>,
    /// llama.cpp's report of how much of the prompt it has read, sent ahead
    /// of the first output when the request set `return_progress`. Kept raw:
    /// an unexpected shape drops the report, never the chunk.
    #[serde(default)]
    pub(in crate::openai_compatible) prompt_progress: Option<Value>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIStreamChoice {
    pub(in crate::openai_compatible) delta: Option<OpenAIDelta>,
    pub(in crate::openai_compatible) finish_reason: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIDelta {
    pub(in crate::openai_compatible) content: Option<String>,
    /// Reasoning streamed alongside `content`, under DeepSeek's name. Read it
    /// through [`Self::take_reasoning_text`], never directly: proxies spell the
    /// same field `reasoning` (see below), and dropping it would make the
    /// next request omit `reasoning_content`, which DeepSeek rejects with
    /// HTTP 400 "reasoning_content in the thinking mode must be passed back".
    reasoning_content: Option<String>,
    /// The same field under OpenRouter's name. This is a separate field, not
    /// a serde alias, because gateways (Bifrost, vLLM's deprecation shim)
    /// send both keys on one delta and serde rejects an aliased key that
    /// appears twice as a duplicate field, failing the whole stream.
    reasoning: Option<String>,
    pub(in crate::openai_compatible) tool_calls: Option<Vec<OpenAIStreamToolCall>>,
}

impl OpenAIDelta {
    /// The delta's reasoning text under either spelling. `reasoning_content`
    /// wins when present; `reasoning` only fills in when the canonical key is
    /// absent or null. The two are never concatenated: a gateway that sends
    /// both carries the same text in each.
    pub(in crate::openai_compatible) fn take_reasoning_text(&mut self) -> Option<String> {
        self.reasoning_content.take().or_else(|| self.reasoning.take())
    }
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIStreamToolCall {
    pub(in crate::openai_compatible) index: u32,
    pub(in crate::openai_compatible) id: Option<String>,
    pub(in crate::openai_compatible) function: Option<OpenAIStreamFunction>,
}

#[derive(Debug, Deserialize)]
pub(in crate::openai_compatible) struct OpenAIStreamFunction {
    pub(in crate::openai_compatible) name: Option<String>,
    pub(in crate::openai_compatible) arguments: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub(in crate::openai_compatible) enum OpenAIContent {
    Text(String),
    List(Vec<OpenAIContentItem>),
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub(in crate::openai_compatible) struct ImageUrl {
    pub(in crate::openai_compatible) url: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(in crate::openai_compatible) enum OpenAIContentItem {
    Text { text: String },
    ImageUrl { image_url: ImageUrl },
}

impl From<OpenAIUsage> for Usage {
    fn from(usage: OpenAIUsage) -> Self {
        let prompt_tokens_details = usage.prompt_tokens_details;
        let cache_read_tokens = usage
            .prompt_cache_hit_tokens
            .or_else(|| prompt_tokens_details.as_ref().map(|details| details.cached_tokens));
        let cache_write_tokens =
            prompt_tokens_details.and_then(|details| details.cache_write_tokens);

        // `prompt_tokens` is cache-inclusive (see `Usage`): providers on this
        // wire count both cache subsets inside it. DeepSeek also spells the
        // read count `prompt_cache_hit_tokens`.
        Usage {
            input_tokens: usage.prompt_tokens,
            output_tokens: usage.completion_tokens,
            cache_read_tokens,
            cache_write_tokens,
        }
    }
}

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

    fn try_from(completion: OpenAICompletion) -> Result<Self> {
        let choice =
            completion.choices.first().ok_or_else(|| anyhow!("No choices in OpenAI response"))?;
        let content = choice.message.content.clone().unwrap_or_default();
        let citations = citations_from_annotations(&choice.message.annotations);

        Ok(WebSearchResult { content: Content::Text(content), citations })
    }
}

fn citations_from_annotations(annotations: &[Value]) -> Vec<WebCitation> {
    let mut seen_urls = HashSet::new();
    let mut citations = Vec::new();

    for annotation in annotations {
        if annotation.get("type").and_then(Value::as_str) != Some("url_citation") {
            continue;
        }

        let Some(url_citation) = annotation.get("url_citation") else {
            continue;
        };
        let Some(uri) = url_citation
            .get("url")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|url| !url.is_empty())
        else {
            continue;
        };

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

        let title = url_citation
            .get("title")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|title| !title.is_empty())
            .unwrap_or(uri)
            .to_string();
        citations.push(WebCitation { title, uri: uri.to_string() });
    }

    citations
}

pub(in crate::openai_compatible) fn stop_reason(value: &str) -> StopReason {
    match value {
        // OpenAI / OpenAI-compatible chat completion finish_reason values
        "stop" => StopReason::EndTurn,
        "length" => StopReason::MaxTokens,
        "content_filter" => StopReason::Refusal,
        other => StopReason::Other(other.to_string()),
    }
}