Skip to main content

a2a_protocol_server/tool_loop/
openai.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`OpenAiChatModel`]: a [`ToolModel`] for the chat-completions API that
5//! `OpenAI`, llama.cpp's llama-server, vLLM and Ollama all serve.
6//!
7//! It runs on the hyper client the bundled push sender uses, so it adds no
8//! dependency: plaintext HTTP always, HTTPS with the `tls-rustls` feature.
9//! `deny.toml` keeps reqwest out of this crate.
10
11use std::fmt;
12use std::future::Future;
13use std::pin::Pin;
14use std::time::Duration;
15
16use bytes::Bytes;
17use http_body_util::{BodyExt as _, Full, LengthLimitError, Limited};
18use serde_json::{Map, Value, json};
19
20use super::model::{ChatMessage, ChatRequest, ModelError, ModelTurn, TextSink, ToolModel};
21use super::openai_parse::parse_completion;
22use crate::causes::with_causes;
23use crate::push::sender::PushHttpClient;
24
25/// How long one turn may take, request and whole response, by default.
26///
27/// A small local model on a CPU can take a minute over a long conversation;
28/// two is the bound past which the caller is better served by a failed task
29/// than by waiting.
30pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
31
32/// The most of a response body read when no cap is set. A chat completion
33/// is kilobytes; the cap exists so an endpoint does not get to choose how
34/// much memory a turn takes.
35pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
36
37/// The most of an error response's body kept in [`ModelError::Status`].
38pub const ERROR_BODY_LIMIT: usize = 512;
39
40/// The media type of a streamed completion.
41const EVENT_STREAM: &str = "text/event-stream";
42
43/// A [`ToolModel`] that sends each turn as `POST {base}/chat/completions`.
44///
45/// ```rust,no_run
46/// use a2a_protocol_server::tool_loop::OpenAiChatModel;
47///
48/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
49/// // llama.cpp's llama-server, with Qwen3's thinking turned off.
50/// let mut extra = serde_json::Map::new();
51/// extra.insert("chat_template_kwargs".into(), serde_json::json!({"enable_thinking": false}));
52/// let model = OpenAiChatModel::new("http://127.0.0.1:8080/v1", "qwen3:1.7b")?
53///     .with_extra_body(extra);
54/// # Ok(()) }
55/// ```
56///
57/// Tool-call arguments are read whether the server sends them as a JSON
58/// string, as `OpenAI` does, or as an object, as some compatible servers do.
59pub struct OpenAiChatModel {
60    client: PushHttpClient,
61    endpoint: hyper::Uri,
62    model: String,
63    api_key: Option<String>,
64    timeout: Duration,
65    max_response_bytes: usize,
66    extra: Map<String, Value>,
67    /// Whether a streamed turn asks for its connection to be closed after it.
68    close_after_stream: bool,
69}
70
71impl fmt::Debug for OpenAiChatModel {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("OpenAiChatModel")
74            .field("endpoint", &self.endpoint)
75            .field("model", &self.model)
76            .field("api_key", &self.api_key.as_ref().map(|_| "[redacted]"))
77            .field("timeout", &self.timeout)
78            .field("max_response_bytes", &self.max_response_bytes)
79            .field("close_after_stream", &self.close_after_stream)
80            .finish_non_exhaustive()
81    }
82}
83
84impl OpenAiChatModel {
85    /// A client for `model` at `base_url`, the API's base including its
86    /// version segment (`https://api.openai.com/v1`,
87    /// `http://127.0.0.1:8080/v1`).
88    ///
89    /// # Errors
90    ///
91    /// [`ModelError::Config`] when `base_url` is not an `http://` or
92    /// `https://` URL, or is `https://` in a build without `tls-rustls` —
93    /// refused here rather than at the first turn.
94    pub fn new(base_url: &str, model: impl Into<String>) -> Result<Self, ModelError> {
95        let endpoint = format!("{}/chat/completions", base_url.trim_end_matches('/'));
96        let endpoint: hyper::Uri = endpoint
97            .parse()
98            .map_err(|e| ModelError::Config(format!("'{base_url}' is not a URL: {e}")))?;
99        match endpoint.scheme_str() {
100            Some("http") => {}
101            #[cfg(feature = "tls-rustls")]
102            Some("https") => {}
103            #[cfg(not(feature = "tls-rustls"))]
104            Some("https") => {
105                return Err(ModelError::Config(
106                    "this build of OpenAiChatModel speaks HTTP only and cannot reach an \
107                     https:// endpoint; enable the `tls-rustls` feature (on by default in \
108                     a2a-protocol-sdk)"
109                        .to_owned(),
110                ));
111            }
112            _ => {
113                return Err(ModelError::Config(format!(
114                    "'{base_url}' is not an http:// or https:// URL"
115                )));
116            }
117        }
118        Ok(Self {
119            client: crate::push::sender::build_push_http_client(),
120            endpoint,
121            model: model.into(),
122            api_key: None,
123            timeout: DEFAULT_TIMEOUT,
124            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
125            close_after_stream: true,
126            extra: Map::new(),
127        })
128    }
129
130    /// Verifies the server against `tls_config` instead of Mozilla's roots:
131    /// a private CA, or a client certificate for mutual TLS.
132    #[cfg(feature = "tls-rustls")]
133    #[must_use]
134    // By value, as it has always been taken: a public signature changed to a
135    // reference is a break.
136    #[allow(clippy::needless_pass_by_value)]
137    pub fn with_tls_config(mut self, tls_config: rustls::ClientConfig) -> Self {
138        self.client = crate::push::sender::build_push_https_client(&tls_config);
139        self
140    }
141
142    /// Sends `key` as `Authorization: Bearer {key}`. Local servers need
143    /// none.
144    #[must_use]
145    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
146        self.api_key = Some(key.into());
147        self
148    }
149
150    /// Bounds each turn — connecting, sending and reading the whole
151    /// response. Default [`DEFAULT_TIMEOUT`].
152    #[must_use]
153    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
154        self.timeout = timeout;
155        self
156    }
157
158    /// Caps the response body read, in bytes. Default
159    /// [`DEFAULT_MAX_RESPONSE_BYTES`].
160    #[must_use]
161    pub const fn with_max_response_bytes(mut self, max: usize) -> Self {
162        self.max_response_bytes = max;
163        self
164    }
165
166    /// Lets a streamed turn's connection be reused for the next turn.
167    ///
168    /// By default each streamed turn asks for its connection to be closed
169    /// after it (`Connection: close`): llama.cpp's llama-server says
170    /// `keep-alive` and then closes the connection just after a streamed
171    /// answer (seen on llama.cpp `9daa0aa`, 2026-11-13: three of three
172    /// attempts to reuse the connection found it closed), and a pooled
173    /// connection would carry the next turn into that close ("connection
174    /// closed before message completed"). An endpoint that keeps its
175    /// connections (a hosted provider, a proxy) gains a handshake per turn
176    /// from this, which over TLS and a remote network is not free: call
177    /// this for such an endpoint (adversarial review N16, 2026-11-13). The
178    /// cost was not measured here: the only endpoint at hand was a local one.
179    #[must_use]
180    pub const fn with_stream_connection_reuse(mut self) -> Self {
181        self.close_after_stream = false;
182        self
183    }
184
185    /// Adds `fields` to every request body: `temperature`,
186    /// `chat_template_kwargs`, `tool_choice` and the like. The fields this
187    /// client writes itself — `model`, `messages`, and `tools` when there
188    /// are tools — win over an extra of the same name.
189    #[must_use]
190    pub fn with_extra_body(mut self, fields: Map<String, Value>) -> Self {
191        self.extra.extend(fields);
192        self
193    }
194
195    /// The request body for one turn.
196    fn request_body(&self, request: ChatRequest<'_>) -> Value {
197        let mut messages = Vec::with_capacity(request.messages.len() + 1);
198        if !request.preamble.is_empty() {
199            messages.push(json!({"role": "system", "content": request.preamble}));
200        }
201        messages.extend(request.messages.iter().map(wire_message));
202        let mut body = self.extra.clone();
203        body.insert("model".to_owned(), Value::from(self.model.as_str()));
204        body.insert("messages".to_owned(), Value::Array(messages));
205        if !request.tools.is_empty() {
206            let tools = request
207                .tools
208                .iter()
209                .map(|t| {
210                    json!({
211                        "type": "function",
212                        "function": {
213                            "name": t.name,
214                            "description": t.description,
215                            "parameters": t.parameters,
216                        }
217                    })
218                })
219                .collect();
220            body.insert("tools".to_owned(), Value::Array(tools));
221        }
222        Value::Object(body)
223    }
224
225    /// Sends one turn, accepting `accept`; the response, refused unless it
226    /// is a success.
227    async fn send(
228        &self,
229        body: Bytes,
230        accept: &'static str,
231    ) -> Result<hyper::Response<hyper::body::Incoming>, ModelError> {
232        let mut builder = hyper::Request::post(self.endpoint.clone())
233            .header(hyper::header::CONTENT_TYPE, "application/json")
234            .header(hyper::header::ACCEPT, accept);
235        if accept == EVENT_STREAM && self.close_after_stream {
236            // See `with_stream_connection_reuse`: llama-server closes the
237            // connection after a streamed answer, and a pooled one would
238            // carry the next turn into the close.
239            builder = builder.header(hyper::header::CONNECTION, "close");
240        }
241        if let Some(key) = &self.api_key {
242            let mut value = hyper::header::HeaderValue::from_str(&format!("Bearer {key}"))
243                .map_err(|_| {
244                    ModelError::Config(
245                        "the API key holds characters an HTTP header cannot carry".to_owned(),
246                    )
247                })?;
248            value.set_sensitive(true);
249            builder = builder.header(hyper::header::AUTHORIZATION, value);
250        }
251        let request = builder
252            .body(Full::new(body))
253            .map_err(|e| ModelError::Config(format!("the request could not be built: {e}")))?;
254        let response = self
255            .client
256            .request(request)
257            .await
258            .map_err(|e| ModelError::Transport(with_causes(&e)))?;
259        let status = response.status();
260        if !status.is_success() {
261            // Read before the body consumes the response.
262            let retry_after =
263                super::retry::parse_retry_after(response.headers(), std::time::SystemTime::now());
264            let body = read_prefix(response.into_body(), ERROR_BODY_LIMIT).await;
265            let body = truncated(&body, ERROR_BODY_LIMIT);
266            if status == hyper::StatusCode::TOO_MANY_REQUESTS {
267                return Err(ModelError::RateLimited { retry_after, body });
268            }
269            return Err(ModelError::Status {
270                status: status.as_u16(),
271                body,
272            });
273        }
274        Ok(response)
275    }
276
277    /// Sends one turn and reads its answer, without the timeout.
278    async fn exchange(&self, body: Bytes) -> Result<ModelTurn, ModelError> {
279        let response = self.send(body, "application/json").await?;
280        self.whole(response).await
281    }
282
283    /// Reads a whole (unstreamed) completion.
284    async fn whole(
285        &self,
286        response: hyper::Response<hyper::body::Incoming>,
287    ) -> Result<ModelTurn, ModelError> {
288        let body = Limited::new(response.into_body(), self.max_response_bytes)
289            .collect()
290            .await
291            .map_err(|e| {
292                if e.downcast_ref::<LengthLimitError>().is_some() {
293                    ModelError::ResponseTooLarge(self.max_response_bytes)
294                } else {
295                    ModelError::Transport(e.to_string())
296                }
297            })?
298            .to_bytes();
299        parse_completion(&body)
300    }
301
302    /// Sends one turn asking for a stream, and reads its events; a server
303    /// that answers with the whole completion instead is read whole, its
304    /// text handed to `sink` in one piece.
305    async fn exchange_streaming(
306        &self,
307        body: Bytes,
308        sink: &TextSink,
309    ) -> Result<ModelTurn, ModelError> {
310        let response = self.send(body, EVENT_STREAM).await?;
311        let streamed = response
312            .headers()
313            .get(hyper::header::CONTENT_TYPE)
314            .and_then(|v| v.to_str().ok())
315            .is_some_and(|v| v.starts_with(EVENT_STREAM));
316        if streamed {
317            return super::openai_stream::read(response.into_body(), self.max_response_bytes, sink)
318                .await;
319        }
320        let turn = self.whole(response).await?;
321        sink.push(&turn.text);
322        Ok(turn)
323    }
324}
325
326impl ToolModel for OpenAiChatModel {
327    fn model_name(&self) -> &str {
328        &self.model
329    }
330
331    /// `openai`: the conventions name the API a client speaks, not the
332    /// server behind it ("multiple systems … are accessible by `OpenAI`
333    /// client libraries. In such cases, `gen_ai.provider.name` is set to
334    /// `openai`").
335    fn provider_name(&self) -> &'static str {
336        "openai"
337    }
338
339    /// The endpoint's host, without an IPv6 address's brackets, and its
340    /// port, or the scheme's when it names none.
341    fn server(&self) -> Option<(&str, u16)> {
342        let host = self.endpoint.host()?;
343        let host = host
344            .strip_prefix('[')
345            .and_then(|h| h.strip_suffix(']'))
346            .unwrap_or(host);
347        let port = self.endpoint.port_u16().unwrap_or_else(|| {
348            if self.endpoint.scheme_str() == Some("https") {
349                443
350            } else {
351                80
352            }
353        });
354        Some((host, port))
355    }
356
357    fn complete<'a>(
358        &'a self,
359        request: ChatRequest<'a>,
360    ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>> {
361        let body = serde_json::to_vec(&self.request_body(request)).map(Bytes::from);
362        Box::pin(async move {
363            let body = body.map_err(|e| ModelError::Config(format!("request encoding: {e}")))?;
364            tokio::time::timeout(self.timeout, self.exchange(body))
365                .await
366                .unwrap_or(Err(ModelError::Timeout(self.timeout)))
367        })
368    }
369
370    /// Asks for the turn as a stream (`"stream": true`, with its usage), and
371    /// hands `text` each piece of the answer as it arrives. Each streamed
372    /// turn has a connection of its own (`Connection: close`) unless
373    /// [`with_stream_connection_reuse`](Self::with_stream_connection_reuse)
374    /// was called.
375    fn complete_streaming<'a>(
376        &'a self,
377        request: ChatRequest<'a>,
378        text: &'a TextSink,
379    ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>> {
380        let mut body = self.request_body(request);
381        if let Value::Object(fields) = &mut body {
382            fields.insert("stream".to_owned(), Value::Bool(true));
383            fields.insert("stream_options".to_owned(), json!({"include_usage": true}));
384        }
385        let body = serde_json::to_vec(&body).map(Bytes::from);
386        Box::pin(async move {
387            let body = body.map_err(|e| ModelError::Config(format!("request encoding: {e}")))?;
388            tokio::time::timeout(self.timeout, self.exchange_streaming(body, text))
389                .await
390                .unwrap_or(Err(ModelError::Timeout(self.timeout)))
391        })
392    }
393}
394
395/// One conversation message on the wire.
396fn wire_message(message: &ChatMessage) -> Value {
397    match message {
398        ChatMessage::System(text) => json!({"role": "system", "content": text}),
399        ChatMessage::User(text) => json!({"role": "user", "content": text}),
400        ChatMessage::Assistant { text, tool_calls } if tool_calls.is_empty() => {
401            json!({"role": "assistant", "content": text})
402        }
403        ChatMessage::Assistant { text, tool_calls } => {
404            let calls: Vec<Value> = tool_calls
405                .iter()
406                .map(|c| {
407                    json!({
408                        "id": c.id,
409                        "type": "function",
410                        "function": {"name": c.name, "arguments": c.arguments},
411                    })
412                })
413                .collect();
414            let content = if text.is_empty() {
415                Value::Null
416            } else {
417                Value::from(text.as_str())
418            };
419            json!({"role": "assistant", "content": content, "tool_calls": calls})
420        }
421        ChatMessage::ToolResult {
422            call_id, content, ..
423        } => json!({"role": "tool", "tool_call_id": call_id, "content": content}),
424    }
425}
426
427/// Reads up to `limit` bytes of `body` and drops the rest unread.
428async fn read_prefix(mut body: hyper::body::Incoming, limit: usize) -> Vec<u8> {
429    let mut out = Vec::new();
430    while out.len() < limit {
431        match body.frame().await {
432            Some(Ok(frame)) => {
433                if let Ok(data) = frame.into_data() {
434                    out.extend_from_slice(&data);
435                }
436            }
437            Some(Err(_)) | None => break,
438        }
439    }
440    out
441}
442
443/// `bytes` as one printable line of text, at most `limit` bytes of it, cut on a
444/// character boundary.
445///
446/// The text is the provider's, and it reaches the operator's log through
447/// [`ModelError`]'s `Display`. A control character in it would be written
448/// raw: a newline starts a log line the provider wrote, an escape sequence
449/// reaches the operator's terminal. Each is written as the escape Rust gives
450/// it (`\n`, `\u{1b}`), and the bound is on what is shown, so an escape is
451/// kept whole or left out.
452fn truncated(bytes: &[u8], limit: usize) -> String {
453    let text = String::from_utf8_lossy(bytes);
454    let mut shown = String::with_capacity(text.len().min(limit));
455    for c in text.chars() {
456        let before = shown.len();
457        if c.is_control() {
458            shown.extend(c.escape_default());
459        } else {
460            shown.push(c);
461        }
462        if shown.len() > limit {
463            shown.truncate(before);
464            break;
465        }
466    }
467    shown
468}
469
470#[cfg(test)]
471#[path = "openai_tests.rs"]
472mod tests;