agentai-core 0.7.1

Shared building blocks of the AgentAI crates, such as the HTTP client abstraction.
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
//! HTTP client abstraction.

use async_trait::async_trait;
use serde::Serialize;
use serde::de::DeserializeOwned;
use thiserror::Error;

/// HTTP method of a [`HttpRequest`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Method {
    Get,
    Post,
    Delete,
}

/// A request sent with a [`HttpClient`]. The body is always plain bytes, so a client only
/// has to send them.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HttpRequest {
    pub method: Method,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<Vec<u8>>,
}

impl HttpRequest {
    /// Creates a request without headers and body.
    pub fn new(method: Method, url: impl Into<String>) -> Self {
        Self {
            method,
            url: url.into(),
            headers: Vec::new(),
            body: None,
        }
    }

    /// Creates a `GET` request.
    pub fn get(url: impl Into<String>) -> Self {
        Self::new(Method::Get, url)
    }

    /// Creates a `POST` request.
    pub fn post(url: impl Into<String>) -> Self {
        Self::new(Method::Post, url)
    }

    /// Creates a `DELETE` request.
    pub fn delete(url: impl Into<String>) -> Self {
        Self::new(Method::Delete, url)
    }

    /// Adds a header.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Adds `Authorization: Bearer <token>`. An empty token adds nothing, for servers without
    /// authentication.
    pub fn with_bearer_token(self, token: &str) -> Self {
        if token.is_empty() {
            self
        } else {
            self.with_header("Authorization", format!("Bearer {token}"))
        }
    }

    /// Sets the body.
    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Sets a JSON body and its `Content-Type`.
    pub fn with_json(self, body: &impl Serialize) -> Result<Self, HttpError> {
        let body = serde_json::to_vec(body).map_err(HttpError::Json)?;
        Ok(self
            .with_header("Content-Type", "application/json")
            .with_body(body))
    }

    /// Sets a `multipart/form-data` body and its `Content-Type`.
    pub fn with_multipart(self, form: Multipart) -> Self {
        let (content_type, body) = form.into_body();
        self.with_header("Content-Type", content_type)
            .with_body(body)
    }

    /// Returns the value of the first header with this name, ignoring case.
    pub fn header(&self, name: &str) -> Option<&str> {
        find_header(&self.headers, name)
    }
}

/// A response returned by a [`HttpClient`], with the whole body read.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HttpResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl HttpResponse {
    /// Creates a response without headers.
    pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
        Self {
            status,
            headers: Vec::new(),
            body: body.into(),
        }
    }

    /// Adds a header.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Returns `true` for a 2xx status.
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// Returns the response for a 2xx status, otherwise [`HttpError::Status`] with the API's
    /// error message.
    pub fn error_for_status(self) -> Result<Self, HttpError> {
        if self.is_success() {
            Ok(self)
        } else {
            Err(HttpError::Status {
                status: self.status,
                message: self.error_message(),
            })
        }
    }

    /// The message of a JSON error body (`error.message`, or FastAPI's `detail` as a string,
    /// an object with `message` or a list of validation errors), otherwise the whole body.
    fn error_message(&self) -> String {
        self.json::<serde_json::Value>()
            .ok()
            .and_then(|json| {
                let detail = &json["detail"];
                json["error"]["message"]
                    .as_str()
                    .or_else(|| detail.as_str())
                    .or_else(|| detail["message"].as_str())
                    .or_else(|| detail[0]["msg"].as_str())
                    .map(str::to_string)
            })
            .unwrap_or_else(|| self.text())
    }

    /// Returns the value of the first header with this name, ignoring case.
    pub fn header(&self, name: &str) -> Option<&str> {
        find_header(&self.headers, name)
    }

    /// The `Content-Type` header without its parameters, `None` when it is missing or empty.
    pub fn content_type(&self) -> Option<&str> {
        self.header("content-type")
            .and_then(|value| value.split(';').next())
            .map(str::trim)
            .filter(|value| !value.is_empty())
    }

    /// Parses the body as JSON.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, HttpError> {
        serde_json::from_slice(&self.body).map_err(HttpError::Json)
    }

    /// Returns the body as text, replacing invalid UTF-8.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }
}

/// Percent-encodes `value` for use as one path segment or query value of a URL: everything but
/// the unreserved characters of RFC 3986 (letters, digits, `-`, `.`, `_`, `~`) is escaped.
///
/// ```rust
/// assert_eq!(agentai_core::percent_encode("a/b?c d"), "a%2Fb%3Fc%20d");
/// ```
pub fn percent_encode(value: &str) -> String {
    let mut encoded = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            encoded.push(byte as char);
        } else {
            encoded.push_str(&format!("%{byte:02X}"));
        }
    }
    encoded
}

fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.as_str())
}

/// Errors of a [`HttpClient`] and of building or reading a request.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum HttpError {
    /// The request could not be sent or the response could not be read (connection,
    /// timeout, TLS, ...).
    #[error("HTTP request failed: {0}")]
    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// A JSON body could not be written or read.
    #[error("invalid JSON body: {0}")]
    Json(serde_json::Error),
    /// The server answered with an error status, see [`HttpResponse::error_for_status`].
    #[error("HTTP status {status}: {message}")]
    Status { status: u16, message: String },
    /// The bytes of a [`Media`](crate::message::Media) are not valid base64.
    #[error("invalid base64 media: {0}")]
    InvalidMedia(String),
}

impl HttpError {
    /// Creates a [`HttpError::Transport`] from any error.
    pub fn transport(err: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
        Self::Transport(err.into())
    }
}

/// Sends HTTP requests.
///
/// Crates such as `agentai-image` send their requests through this trait instead of a
/// particular HTTP client. [`ReqwestClient`] (feature `reqwest`) implements it.
///
/// The returned future is `Send`. Clients whose futures are not `Send` (for example in the
/// browser) will need a relaxed bound, which comes with WebAssembly support.
#[async_trait]
pub trait HttpClient: Send + Sync + 'static {
    /// Sends the request and reads the whole response. A response with an error status is
    /// still `Ok`; only failures to send or read are errors.
    async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpError>;
}

/// A `multipart/form-data` body, built in memory.
///
/// ```rust
/// # use agentai_core::{HttpRequest, Multipart};
/// let request = HttpRequest::post("https://example.com/upload").with_multipart(
///     Multipart::new()
///         .with_text("prompt", "a cat")
///         .with_file("image", "cat.png", "image/png", vec![0x89, b'P', b'N', b'G']),
/// );
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Multipart {
    parts: Vec<FormPart>,
}

#[derive(Debug, Clone, PartialEq)]
struct FormPart {
    name: String,
    filename: Option<String>,
    content_type: Option<String>,
    data: Vec<u8>,
}

impl Multipart {
    /// Creates an empty form.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a text field.
    pub fn with_text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.parts.push(FormPart {
            name: name.into(),
            filename: None,
            content_type: None,
            data: value.into().into_bytes(),
        });
        self
    }

    /// Adds a file field.
    pub fn with_file(
        mut self,
        name: impl Into<String>,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
    ) -> Self {
        self.parts.push(FormPart {
            name: name.into(),
            filename: Some(filename.into()),
            content_type: Some(content_type.into()),
            data: data.into(),
        });
        self
    }

    /// Adds a field with a JSON value (`Content-Type: application/json`, no filename).
    pub fn with_json(
        mut self,
        name: impl Into<String>,
        value: &impl Serialize,
    ) -> Result<Self, HttpError> {
        self.parts.push(FormPart {
            name: name.into(),
            filename: None,
            content_type: Some("application/json".into()),
            data: serde_json::to_vec(value).map_err(HttpError::Json)?,
        });
        Ok(self)
    }

    /// Returns the `Content-Type` header value and the body.
    fn into_body(self) -> (String, Vec<u8>) {
        let boundary = self.boundary();
        let mut body = Vec::new();
        for part in self.parts {
            body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
            let name = escape(&part.name);
            let mut head = format!("Content-Disposition: form-data; name=\"{name}\"");
            if let Some(filename) = &part.filename {
                head.push_str(&format!("; filename=\"{}\"", escape(filename)));
            }
            head.push_str("\r\n");
            if let Some(content_type) = &part.content_type {
                head.push_str(&format!("Content-Type: {content_type}\r\n"));
            }
            head.push_str("\r\n");
            body.extend_from_slice(head.as_bytes());
            body.extend_from_slice(&part.data);
            body.extend_from_slice(b"\r\n");
        }
        body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
        (format!("multipart/form-data; boundary={boundary}"), body)
    }

    /// A boundary that appears in no part. Chosen without randomness or a clock, so it works
    /// in every environment.
    fn boundary(&self) -> String {
        (0u64..)
            .map(|n| format!("agentai-boundary-{n:016x}"))
            .find(|boundary| {
                !self
                    .parts
                    .iter()
                    .any(|part| contains(&part.data, boundary.as_bytes()))
            })
            .expect("some boundary is not in the data")
    }
}

fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

/// Quotes and line breaks would end the header value early.
fn escape(value: &str) -> String {
    value
        .replace('"', "%22")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

#[cfg(feature = "test-support")]
pub mod mock;
#[cfg(feature = "reqwest")]
mod reqwest;
#[cfg(feature = "reqwest")]
pub use reqwest::ReqwestClient;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn multipart_json_part_has_a_content_type_and_no_filename() {
        let form = Multipart::new()
            .with_json("request", &serde_json::json!({"model": "m"}))
            .unwrap()
            .with_file("image", "a.png", "image/png", vec![1u8]);
        let (_, body) = form.into_body();
        let body = String::from_utf8_lossy(&body);
        assert!(body.contains(
            "Content-Disposition: form-data; name=\"request\"\r\nContent-Type: application/json\r\n\r\n{\"model\":\"m\"}\r\n"
        ));
        assert!(
            body.contains("name=\"image\"; filename=\"a.png\"\r\nContent-Type: image/png\r\n\r\n")
        );
    }

    #[test]
    fn error_for_status_reads_every_error_shape() {
        let message = |body: &str| match HttpResponse::new(400, body).error_for_status() {
            Err(HttpError::Status {
                status: 400,
                message,
            }) => message,
            other => panic!("{other:?}"),
        };
        assert_eq!(message(r#"{"error": {"message": "openai"}}"#), "openai");
        assert_eq!(message(r#"{"detail": "omlx"}"#), "omlx");
        assert_eq!(message(r#"{"detail": {"message": "eleven"}}"#), "eleven");
        assert_eq!(
            message(r#"{"detail": [{"msg": "validation"}]}"#),
            "validation"
        );
        assert_eq!(message(r#"{"other":1}"#), r#"{"other":1}"#);
        assert_eq!(message("bad gateway"), "bad gateway");
        assert!(HttpResponse::new(204, "").error_for_status().is_ok());
    }

    #[test]
    fn multipart_body_has_the_fields_and_files_between_boundaries() {
        let request = HttpRequest::post("u").with_multipart(
            Multipart::new().with_text("prompt", "a cat").with_file(
                "image[]",
                "a.png",
                "image/png",
                b"PNG".to_vec(),
            ),
        );
        let boundary = "agentai-boundary-0000000000000000";
        assert_eq!(
            request.header("content-type"),
            Some(format!("multipart/form-data; boundary={boundary}").as_str())
        );
        let expected = format!(
            "--{boundary}\r\n\
             Content-Disposition: form-data; name=\"prompt\"\r\n\r\n\
             a cat\r\n\
             --{boundary}\r\n\
             Content-Disposition: form-data; name=\"image[]\"; filename=\"a.png\"\r\n\
             Content-Type: image/png\r\n\r\n\
             PNG\r\n\
             --{boundary}--\r\n"
        );
        assert_eq!(String::from_utf8(request.body.unwrap()).unwrap(), expected);
    }

    #[test]
    fn multipart_boundary_never_appears_in_the_data() {
        let data = "agentai-boundary-0000000000000000";
        let request =
            HttpRequest::post("u").with_multipart(Multipart::new().with_text("prompt", data));
        let content_type = request.header("Content-Type").unwrap();
        assert!(content_type.ends_with("agentai-boundary-0000000000000001"));
    }
}