a2a_protocol_server/tool_loop/
openai.rs1use 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
25pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
31
32pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
36
37pub const ERROR_BODY_LIMIT: usize = 512;
39
40const EVENT_STREAM: &str = "text/event-stream";
42
43pub 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 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 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 #[cfg(feature = "tls-rustls")]
133 #[must_use]
134 #[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 #[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 #[must_use]
153 pub const fn with_timeout(mut self, timeout: Duration) -> Self {
154 self.timeout = timeout;
155 self
156 }
157
158 #[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 #[must_use]
180 pub const fn with_stream_connection_reuse(mut self) -> Self {
181 self.close_after_stream = false;
182 self
183 }
184
185 #[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 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 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 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 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 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 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 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 fn provider_name(&self) -> &'static str {
336 "openai"
337 }
338
339 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 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
395fn 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
427async 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
443fn 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;