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

mod convert;
pub(crate) use convert::effort_levels;
mod types;
mod websocket;

use self::convert::to_openai_request;
use self::types::{
    InputItem, ListModelsResponse, MessageContentPart, OpenAiRequest, OpenAiResponseCompletion,
    OpenAiTool, OpenAiUsage, ResponseStreamEvent, stop_reason_from_status,
};
pub use self::websocket::OpenAiTransport;
use self::websocket::ResponsesWsTransport;
use crate::WireStyle;
use crate::client::{ChatClient, Client, ClientResponse, ProviderClient, within};
use crate::error::{
    LlmError, LlmErrorKind, ProviderError, error_details, http_status_to_kind, openai_error_kind,
    parse_error_body,
};
use crate::extra_body::decorate;
use crate::stream_driver::{StreamMapper, drive_stream};
use crate::streaming::collect;
use crate::system_messages;
use crate::types::{
    ChatRequest, ChatResponse, ChatResponseStream, Effort, ModelSpec, StopReason, StreamEvent,
    ThinkingDisplay, ToolUse, Usage, WebSearchResult, decoded_tool_use, supported_efforts_by_model,
};
use anyhow::{Context, Result};
use async_trait::async_trait;
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::{Map, Value};
use std::collections::HashMap;
use tracing::{debug, warn};

/// The OpenAI API, for [`Client::new`]. Its Chat Completions endpoint is at
/// the same base, for [`OpenAiCompatible`](crate::openai_compatible::OpenAiCompatible).
pub const BASE_URL: &str = "https://api.openai.com/v1";

/// OpenAI Responses API client, one instance per conversation.
#[derive(Clone)]
pub struct OpenAi {
    client: ProviderClient,
    /// The WebSocket transport, which continues one conversation. `None` when
    /// using HTTP/SSE. Only `stream_chat` rides it; see `chat` for why.
    websocket: Option<ResponsesWsTransport>,
    extra_body: Map<String, Value>,
    thinking_display: Option<ThinkingDisplay>,
    max_request_images: Option<u32>,
    supported_efforts: HashMap<String, Vec<Effort>>,
}

impl OpenAi {
    /// A client that carries every call over HTTP.
    pub fn new(client: Client) -> Self {
        Self {
            client: ProviderClient::new(client, classify_http_response),
            websocket: None,
            extra_body: Map::new(),
            thinking_display: None,
            max_request_images: None,
            supported_efforts: HashMap::new(),
        }
    }

    /// Carry calls as `transport` describes instead.
    pub fn with_transport(mut self, transport: OpenAiTransport) -> Self {
        self.websocket = match transport {
            OpenAiTransport::HttpSse => None,
            OpenAiTransport::WebsocketAuto => {
                Some(ResponsesWsTransport::new(self.client.raw().clone()))
            }
        };
        self
    }

    /// Add these fields to every chat request body. They are sent as given:
    /// pass only what [`WireStyle::conflicts`] clears.
    pub fn with_extra_body(mut self, extra_body: Map<String, Value>) -> Self {
        self.extra_body = extra_body;
        self
    }

    /// Ask for readable reasoning in this form. `None` leaves the provider's
    /// default.
    pub fn with_thinking_display(mut self, display: Option<ThinkingDisplay>) -> Self {
        self.thinking_display = display;
        self
    }

    /// Send at most this many images per request: the newest stay and older
    /// ones become text markers. `None` sends them all.
    pub fn with_max_request_images(mut self, max_request_images: Option<u32>) -> Self {
        self.max_request_images = max_request_images;
        self
    }

    /// Round effort onto the levels each model in `models` declares.
    pub fn with_supported_efforts(mut self, models: &[ModelSpec]) -> Self {
        self.supported_efforts = supported_efforts_by_model(models);
        self
    }

    /// Lower `request` to the provider's wire shape; the provider never sees
    /// a request that fails here.
    fn wire_request(&self, request: &ChatRequest) -> Result<OpenAiRequest, LlmError> {
        system_messages::prepare(request, &WireStyle::OpenAiResponse, self.client.base_url())
            .map(|request| request.within_image_budget(self.max_request_images))
            .and_then(|request| {
                let declared = self.supported_efforts.get(&request.model).map(Vec::as_slice);
                to_openai_request(&request, self.thinking_display, declared)
            })
            .map_err(LlmError::request_conversion)
    }
}

/// Post `request` and read its stream to the completed response. Both
/// Responses endpoints serve the stream; the ChatGPT subscription one serves
/// nothing else.
async fn post_search(
    client: &ProviderClient,
    request: &OpenAiRequest,
) -> Result<OpenAiResponseCompletion, LlmError> {
    let mut stream = client.post_chunks::<ResponseStreamEvent, _>("/responses", request).await?;
    while let Some(event) = stream.next().await {
        if let Some(completion) = response_completion_from_stream_event(event?)? {
            return Ok(completion);
        }
    }

    Err(LlmError::unexpected_eof("stream ended before response was completed"))
}

fn classify_http_response(resp: ClientResponse) -> LlmError {
    // OpenAI error bodies may use `code` or `type`, depending on endpoint.
    let (code, message) = parse_error_body(&resp.body, &["code", "type"]);
    let kind = error_kind(code.as_deref(), message.as_deref(), http_status_to_kind(resp.status));
    LlmError::http(kind, resp.status, code, message.unwrap_or(resp.body))
}

fn stream_error(
    code: Option<String>,
    message: impl Into<String>,
    fallback: LlmErrorKind,
) -> LlmError {
    let message = message.into();
    let kind = error_kind(code.as_deref(), Some(&message), fallback);
    LlmError::new(kind, ProviderError { provider_code: code, message, ..Default::default() })
}

fn error_kind(code: Option<&str>, message: Option<&str>, fallback: LlmErrorKind) -> LlmErrorKind {
    openai_error_kind(code, message, fallback, responses_kind_from_code)
}

/// Codes seen only on the Responses wire, layered over the shared family table.
fn responses_kind_from_code(code: &str) -> Option<LlmErrorKind> {
    match code {
        "server_is_overloaded" => Some(LlmErrorKind::Overloaded),
        _ => None,
    }
}

fn response_completion_from_stream_event(
    event: ResponseStreamEvent,
) -> Result<Option<OpenAiResponseCompletion>, LlmError> {
    match event.kind.as_str() {
        "response.completed" | "response.done" => {
            let response = event.response.ok_or_else(|| {
                LlmError::malformed_response("stream completed without response payload")
            })?;
            let completion =
                serde_json::from_value::<OpenAiResponseCompletion>(response).map_err(|err| {
                    LlmError::malformed_response(format!(
                        "failed to parse completed streaming response: {err}"
                    ))
                })?;
            Ok(Some(completion))
        }
        "response.failed" => Err(response_failed_error(event.response.as_ref(), "Response failed")),
        "response.incomplete" => Err(incomplete_error(incomplete_reason(event.response.as_ref()))),
        _ => Ok(None),
    }
}

/// Classify a `response.failed` event from the error object on its response.
fn response_failed_error(response: Option<&Value>, fallback_message: &str) -> LlmError {
    // OpenAI puts the machine code in `code`; OpenAI-compatible gateways
    // (e.g. OpenCode zen) relay theirs in `type` — same fallback order as
    // `classify_http_response`.
    let (code, message) =
        response.map_or((None, None), |response| error_details(response, &["code", "type"]));
    failed_error(code, message.unwrap_or_else(|| fallback_message.to_string()))
}

/// A failed response, classified by the provider's machine code when it sent
/// one. Also the shape of a wrapped WebSocket error frame.
fn failed_error(code: Option<String>, message: String) -> LlmError {
    let code = code.unwrap_or_else(|| "unknown_error".to_string());
    stream_error(Some(code), message, LlmErrorKind::Unknown)
}

/// The `incomplete_details.reason` on a `response.incomplete` event.
fn incomplete_reason(response: Option<&Value>) -> &str {
    response
        .and_then(|response| response.pointer("/incomplete_details/reason"))
        .and_then(Value::as_str)
        .unwrap_or("unknown")
}

fn incomplete_error(reason: &str) -> LlmError {
    stream_error(
        Some(reason.to_string()),
        format!("incomplete response, reason: {reason}"),
        LlmErrorKind::Unknown,
    )
}

/// The `usage` object on a terminal `response.*` event; zero usage when it is
/// absent or undecodable.
fn usage_from_response(response: Option<&Value>) -> Usage {
    response
        .and_then(|response| response.get("usage"))
        .and_then(|usage| OpenAiUsage::deserialize(usage).ok())
        .map_or_else(Usage::default, Usage::from)
}

/// Perform a web search using OpenAI's built-in web search tool
pub(super) async fn search(
    transport: &Client,
    query: &str,
    model: &ModelSpec,
) -> Result<WebSearchResult, LlmError> {
    let client = ProviderClient::new(transport.clone(), classify_http_response);
    let request = OpenAiRequest {
        model: model.id.clone(),
        input: vec![InputItem::message(
            "user",
            vec![MessageContentPart::Text { text: query.to_string() }],
        )],
        tools: vec![OpenAiTool::WebSearch],
        stream: true,
        ..Default::default()
    };

    debug!("OpenAI web search request: {request:?}");
    let response = post_search(&client, &request).await?;
    debug!(
        "OpenAI web search response status: {}, output items: {}",
        response.status,
        response.output.len()
    );

    WebSearchResult::try_from(response)
        .with_context(|| format!("Failed to parse web search response for query: {query}"))
        .map_err(LlmError::response_decode)
}

#[async_trait]
impl ChatClient for OpenAi {
    /// Send a message and get a streaming response using the Response API
    async fn stream_chat(&self, request: ChatRequest) -> Result<ChatResponseStream, LlmError> {
        let wire = self.wire_request(&request)?;
        let body = decorate(&wire, &self.extra_body);

        // One deadline for the call, whichever transports it crosses: a
        // WebSocket attempt that falls back to HTTP/SSE does not start over.
        within(self.client.stream_idle_timeout(), async {
            if let Some(websocket) = self.websocket.as_ref()
                && let Some(stream) = websocket.stream_events(&body).await?
            {
                return Ok(drive_stream(stream, ResponseMapper::default()));
            }
            self.client.post_stream("/responses", &body, ResponseMapper::default()).await
        })
        .await?
    }

    /// A complete response rides HTTP/SSE even in WebSocket mode. The
    /// WebSocket session continues one conversation: its baseline is the last
    /// request's input prefix, which a one-off call over other input would
    /// overwrite with its own, and the one connection would queue such a call
    /// behind the stream in progress.
    async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
        let wire = self.wire_request(&request)?;
        let body = decorate(&wire, &self.extra_body);
        let stream =
            self.client.post_stream("/responses", &body, ResponseMapper::default()).await?;
        collect(stream, |_| {}).await.into_result()
    }

    async fn list_models(&self) -> Result<Vec<ModelSpec>, LlmError> {
        let resp: ListModelsResponse = self.client.get_json("/models", &()).await?;
        Ok(resp.data.into_iter().map(ModelSpec::from).collect())
    }
}

/// Maps Response API streaming events into the shared `StreamEvent` vocabulary.
/// Text and reasoning deltas pass straight through. Function calls are
/// extracted from the complete `item` JSON in `response.output_item.done`
/// instead of tracking incremental argument deltas.
#[derive(Default)]
struct ResponseMapper {
    pending_function_call_error: Option<LlmError>,
    /// Set once a terminal event (`response.completed`/`done`/`failed`/
    /// `incomplete`) is seen; later events are swallowed. A stream that ends
    /// with no terminal event is `drive_stream`'s to fail.
    completed: bool,
}

/// The model's own label on a message it wrote, `commentary` for a progress
/// note or `final_answer`: the wire field it travels in and the tag it is kept
/// under.
const PHASE: &str = "phase";

/// The encrypted content of a completed `reasoning` output item: what the
/// next request hands back as input so the model keeps its reasoning.
fn reasoning_encrypted_content(item: &Value) -> Option<&str> {
    if item.get("type").and_then(Value::as_str) != Some("reasoning") {
        return None;
    }
    item.get("encrypted_content").and_then(Value::as_str).filter(|content| !content.is_empty())
}

fn parse_function_call_item(item: &Value) -> Result<Option<ToolUse>, LlmError> {
    if item.get("type").and_then(|v| v.as_str()) != Some("function_call") {
        return Ok(None);
    }

    let name = item
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| LlmError::malformed_response("function_call item missing `name`"))?
        .to_string();
    let id = item
        .get("call_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| LlmError::malformed_response("function_call item missing `call_id`"))?
        .to_string();
    // Empty `arguments` is the wire convention for a no-arg call. Malformed
    // JSON is retained as a non-executable tool call so the caller can return a
    // tool-result error to the model after the response completes.
    let raw_args = item.get("arguments").and_then(|v| v.as_str()).unwrap_or("");
    Ok(Some(decoded_tool_use(id, name, raw_args)))
}

impl StreamMapper for ResponseMapper {
    type Raw = ResponseStreamEvent;

    fn map(&mut self, event: ResponseStreamEvent) -> Result<Vec<StreamEvent>, LlmError> {
        if self.completed {
            return Ok(vec![]);
        }
        match event.kind.as_str() {
            "response.output_text.delta" => {
                if let Some(delta) = event.delta {
                    Ok(vec![StreamEvent::TextDelta(delta)])
                } else {
                    Ok(vec![])
                }
            }
            "response.output_text.done" => Ok(vec![StreamEvent::ContentStop]),
            // Ignored: function calls arrive complete in
            // `response.output_item.done`.
            "response.content_part.added"
            | "response.content_part.done"
            | "response.output_item.added"
            | "response.function_call_arguments.delta"
            | "response.function_call_arguments.done" => Ok(vec![]),
            "response.output_item.done" => {
                if let Some(ref item) = event.item {
                    if let Some(encrypted_content) = reasoning_encrypted_content(item) {
                        // The stop closes the thinking part, so the next
                        // reasoning item starts its own.
                        return Ok(vec![
                            StreamEvent::ThinkingDelta {
                                thinking: String::new(),
                                signature: Some(encrypted_content.to_string()),
                            },
                            StreamEvent::ContentStop,
                        ]);
                    }
                    if item.get("type").and_then(Value::as_str) == Some("message")
                        && let Some(phase) = item.get(PHASE).and_then(Value::as_str)
                    {
                        return Ok(vec![StreamEvent::Tag {
                            name: PHASE.to_string(),
                            value: phase.to_string(),
                        }]);
                    }
                    match parse_function_call_item(item) {
                        Ok(Some(tool_use)) => return Ok(vec![StreamEvent::ToolUse(tool_use)]),
                        Ok(None) => {}
                        Err(err) => {
                            self.pending_function_call_error.get_or_insert(err);
                        }
                    }
                }
                Ok(vec![])
            }
            "response.completed" | "response.done" => {
                self.completed = true;
                if let Some(err) = self.pending_function_call_error.take() {
                    return Err(err);
                }
                let response = event.response.as_ref();
                let status = response
                    .and_then(|response| response.get("status"))
                    .and_then(Value::as_str)
                    .unwrap_or("completed");
                Ok(vec![StreamEvent::MessageStop {
                    usage: usage_from_response(response),
                    stop_reason: Some(stop_reason_from_status(status)),
                }])
            }
            "response.failed" => {
                self.completed = true;
                let err = response_failed_error(
                    event.response.as_ref(),
                    "Response failed with unknown error",
                );
                warn!(
                    "OpenAI response.failed: code={}, message={}",
                    err.detail.provider_code.as_deref().unwrap_or_default(),
                    err.detail.message
                );
                Err(err)
            }
            "response.reasoning_text.delta" | "response.reasoning_summary_text.delta" => {
                if let Some(delta) = event.delta {
                    Ok(vec![StreamEvent::ThinkingDelta { thinking: delta, signature: None }])
                } else {
                    Ok(vec![])
                }
            }
            "response.reasoning_text.done"
            | "response.reasoning_summary_text.done"
            | "response.reasoning_summary_part.added"
            | "response.reasoning_summary_part.done" => Ok(vec![]),
            "response.incomplete" => {
                self.completed = true;
                let response = event.response.as_ref();
                let reason = incomplete_reason(response);
                // Output-limit truncation is recoverable: preserve the partial
                // assistant message by emitting MessageStop with StopReason::MaxTokens
                // instead of an Error (which would bail and drop streamed content).
                // `length` is the Chat Completions name for the same stop, which
                // proxies bridging the two wires forward as-is (issue #235).
                if matches!(reason, "max_output_tokens" | "length") {
                    self.pending_function_call_error = None;
                    Ok(vec![StreamEvent::MessageStop {
                        usage: usage_from_response(response),
                        stop_reason: Some(StopReason::MaxTokens),
                    }])
                } else {
                    Err(incomplete_error(reason))
                }
            }
            // Metadata events
            "response.created" | "response.in_progress" => Ok(vec![]),
            other => {
                debug!("Unhandled streaming event type: {other}");
                Ok(vec![])
            }
        }
    }
}

#[cfg(test)]
mod tests;