linger-openai-sdk 0.1.1

Rust-native async SDK for OpenAI APIs with typed requests, streaming, uploads, retries, and pluggable transports.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use crate::error::LingerError;
use crate::transport::{BodyStream, HttpRequest};
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::fmt;

/// EN: Request body for `POST /v1/containers`.
/// 中文:`POST /v1/containers` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateContainerRequest {
    /// EN: Container name.
    /// 中文:容器名称。
    pub name: String,
    /// EN: Files to copy into the container at creation time.
    /// 中文:创建容器时复制到容器内的文件 ID。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub file_ids: Vec<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateContainerRequest {
    /// EN: Starts building a container creation request.
    /// 中文:开始构建容器创建请求。
    pub fn builder() -> CreateContainerRequestBuilder {
        CreateContainerRequestBuilder::default()
    }
}

/// EN: Builder for container creation requests.
/// 中文:容器创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateContainerRequestBuilder {
    name: Option<String>,
    file_ids: Vec<String>,
    extra: BTreeMap<String, Value>,
}

impl CreateContainerRequestBuilder {
    /// EN: Sets the container name.
    /// 中文:设置容器名称。
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// EN: Adds a file id to copy into the container.
    /// 中文:添加一个要复制到容器中的文件 ID。
    pub fn file_id(mut self, file_id: impl Into<String>) -> Self {
        self.file_ids.push(file_id.into());
        self
    }

    /// EN: Replaces the file id list.
    /// 中文:替换文件 ID 列表。
    pub fn file_ids(mut self, file_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.file_ids = file_ids.into_iter().map(Into::into).collect();
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateContainerRequest, LingerError> {
        validate_non_empty_values("file_ids", &self.file_ids, false)?;
        validate_extra_fields(&self.extra)?;
        Ok(CreateContainerRequest {
            name: required_string("name", self.name)?,
            file_ids: self.file_ids,
            extra: self.extra,
        })
    }
}

/// EN: Request body descriptor for `POST /v1/containers/{container_id}/files`.
/// 中文:`POST /v1/containers/{container_id}/files` 的请求体描述。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateContainerFileRequest {
    /// EN: Existing OpenAI file id to copy into the container.
    /// 中文:要复制到容器中的已有 OpenAI 文件 ID。
    pub file_id: Option<String>,
    /// EN: Raw file content to upload directly into the container.
    /// 中文:要直接上传到容器中的原始文件内容。
    pub file: Option<ContainerFileUpload>,
}

impl CreateContainerFileRequest {
    /// EN: Starts building a container file creation request.
    /// 中文:开始构建容器文件创建请求。
    pub fn builder() -> CreateContainerFileRequestBuilder {
        CreateContainerFileRequestBuilder::default()
    }

    pub(crate) fn apply_body(&self, request: &mut HttpRequest) -> Result<(), LingerError> {
        match (&self.file_id, &self.file) {
            (Some(file_id), None) => {
                request.insert_header("content-type", "application/json");
                request.set_body(serde_json::to_vec(&ContainerFileIdBody { file_id })?);
            }
            (None, Some(file)) => {
                let boundary = multipart_boundary(&file.content);
                request.insert_header(
                    "content-type",
                    format!("multipart/form-data; boundary={boundary}"),
                );
                request.set_body_stream(file.multipart_stream(boundary));
            }
            _ => {
                return Err(LingerError::invalid_config(
                    "exactly one of file_id or file is required",
                ));
            }
        }
        Ok(())
    }
}

#[derive(Serialize)]
struct ContainerFileIdBody<'a> {
    file_id: &'a str,
}

/// EN: Builder for container file creation requests.
/// 中文:容器文件创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateContainerFileRequestBuilder {
    file_id: Option<String>,
    file: Option<ContainerFileUpload>,
}

impl CreateContainerFileRequestBuilder {
    /// EN: Sets an existing OpenAI file id to copy into the container.
    /// 中文:设置要复制到容器中的已有 OpenAI 文件 ID。
    pub fn file_id(mut self, file_id: impl Into<String>) -> Self {
        self.file_id = Some(file_id.into());
        self
    }

    /// EN: Sets raw file content to upload into the container.
    /// 中文:设置要上传到容器中的原始文件内容。
    pub fn file(mut self, file: ContainerFileUpload) -> Self {
        self.file = Some(file);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateContainerFileRequest, LingerError> {
        match (&self.file_id, &self.file) {
            (Some(file_id), None) if !file_id.trim().is_empty() => {}
            (Some(_), None) => return Err(LingerError::invalid_config("file_id is required")),
            (None, Some(_)) => {}
            (None, None) => {
                return Err(LingerError::invalid_config(
                    "exactly one of file_id or file is required",
                ));
            }
            (Some(_), Some(_)) => {
                return Err(LingerError::invalid_config(
                    "file_id and file are mutually exclusive",
                ));
            }
        }
        Ok(CreateContainerFileRequest {
            file_id: self.file_id,
            file: self.file,
        })
    }
}

/// EN: Uploadable container file bytes and multipart metadata.
/// 中文:可上传容器文件字节和 multipart 元数据。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerFileUpload {
    /// EN: Filename sent in the multipart part.
    /// 中文:multipart 分段中发送的文件名。
    pub filename: String,
    /// EN: Content type sent for the file part.
    /// 中文:文件分段发送的内容类型。
    pub content_type: String,
    content: Bytes,
}

impl ContainerFileUpload {
    /// EN: Creates an upload from already available bytes without copying them.
    /// 中文:通过已有字节创建上传对象,不复制这些字节。
    pub fn from_bytes(
        filename: impl Into<String>,
        content: impl Into<Bytes>,
    ) -> Result<Self, LingerError> {
        let filename = filename.into();
        validate_header_param("filename", &filename)?;
        Ok(Self {
            filename,
            content_type: "application/octet-stream".to_string(),
            content: content.into(),
        })
    }

    /// EN: Sets the file part content type.
    /// 中文:设置文件分段的内容类型。
    pub fn content_type(mut self, content_type: impl Into<String>) -> Result<Self, LingerError> {
        let content_type = content_type.into();
        validate_header_value("content_type", &content_type)?;
        self.content_type = content_type;
        Ok(self)
    }

    /// EN: Returns the file bytes as a cheap `Bytes` clone.
    /// 中文:以低成本 `Bytes` 克隆返回文件字节。
    pub fn bytes(&self) -> Bytes {
        self.content.clone()
    }

    fn multipart_stream(
        &self,
        boundary: String,
    ) -> impl futures_core::Stream<Item = Result<Bytes, LingerError>> {
        let chunks = vec![
            Ok(Bytes::from(format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
                escape_multipart_param(&self.filename),
                self.content_type
            ))),
            Ok(self.content.clone()),
            Ok(Bytes::from(format!("\r\n--{boundary}--\r\n"))),
        ];
        futures_util::stream::iter(chunks)
    }
}

/// EN: Container object returned by the Containers API.
/// 中文:Containers API 返回的容器对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct Container {
    /// EN: Container id.
    /// 中文:容器 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Container name.
    /// 中文:容器名称。
    pub name: String,
    /// EN: Container status.
    /// 中文:容器状态。
    pub status: String,
    /// EN: Expiration policy, when returned.
    /// 中文:响应中存在时的过期策略。
    #[serde(default)]
    pub expires_after: Option<Value>,
    /// EN: Last active timestamp, when returned.
    /// 中文:响应中存在时的最后活跃时间戳。
    #[serde(default)]
    pub last_active_at: Option<u64>,
    /// EN: Configured memory limit, when returned.
    /// 中文:响应中存在时配置的内存限制。
    #[serde(default)]
    pub memory_limit: Option<String>,
    /// EN: Configured network policy, when returned.
    /// 中文:响应中存在时配置的网络策略。
    #[serde(default)]
    pub network_policy: Option<Value>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl Container {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Paginated container list returned by the Containers API.
/// 中文:Containers API 返回的分页容器列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ContainerPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Containers on this page.
    /// 中文:本页容器。
    #[serde(default)]
    pub data: Vec<Container>,
    /// EN: First container id on this page.
    /// 中文:本页第一个容器 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last container id on this page.
    /// 中文:本页最后一个容器 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more containers are available.
    /// 中文:是否还有更多容器。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ContainerPage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Deletion result returned by the Containers API.
/// 中文:Containers API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerDeletion {
    /// EN: Deleted container id.
    /// 中文:已删除的容器 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the container was deleted.
    /// 中文:容器是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ContainerDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Container file object returned by the Container Files API.
/// 中文:Container Files API 返回的容器文件对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ContainerFile {
    /// EN: Container file id.
    /// 中文:容器文件 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: File size in bytes.
    /// 中文:文件大小,单位为字节。
    pub bytes: u64,
    /// EN: Parent container id.
    /// 中文:父容器 ID。
    pub container_id: String,
    /// EN: File path inside the container.
    /// 中文:文件在容器内的路径。
    pub path: String,
    /// EN: Source of the file.
    /// 中文:文件来源。
    pub source: String,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ContainerFile {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Paginated container file list.
/// 中文:分页容器文件列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ContainerFilePage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Files on this page.
    /// 中文:本页文件。
    #[serde(default)]
    pub data: Vec<ContainerFile>,
    /// EN: First file id on this page.
    /// 中文:本页第一个文件 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last file id on this page.
    /// 中文:本页最后一个文件 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more files are available.
    /// 中文:是否还有更多文件。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ContainerFilePage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Deletion result returned by the Container Files API.
/// 中文:Container Files API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerFileDeletion {
    /// EN: Deleted container file id.
    /// 中文:已删除的容器文件 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the container file was deleted.
    /// 中文:容器文件是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ContainerFileDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Incremental container file content response.
/// 中文:增量容器文件内容响应。
pub struct ContainerFileContent {
    request_id: Option<RequestId>,
    body: BodyStream,
}

impl fmt::Debug for ContainerFileContent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContainerFileContent")
            .field("request_id", &self.request_id)
            .field("body", &"<stream>")
            .finish()
    }
}

impl ContainerFileContent {
    pub(crate) fn new(request_id: Option<RequestId>, body: BodyStream) -> Self {
        Self { request_id, body }
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }

    /// EN: Consumes this response and returns the incremental content stream.
    /// 中文:消耗此响应并返回增量内容流。
    pub fn into_stream(self) -> BodyStream {
        self.body
    }
}

fn required_string(name: &str, value: Option<String>) -> Result<String, LingerError> {
    value
        .filter(|value| !value.trim().is_empty())
        .ok_or_else(|| LingerError::invalid_config(format!("{name} is required")))
}

fn validate_non_empty_values(
    name: &str,
    values: &[String],
    require_non_empty: bool,
) -> Result<(), LingerError> {
    if require_non_empty && values.is_empty() {
        return Err(LingerError::invalid_config(format!("{name} is required")));
    }
    if values.iter().any(|value| value.trim().is_empty()) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain empty values"
        )));
    }
    Ok(())
}

fn validate_extra_fields(extra: &BTreeMap<String, Value>) -> Result<(), LingerError> {
    for (key, value) in extra {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "extra field names must not be empty",
            ));
        }
        if value.is_null() {
            return Err(LingerError::invalid_config(format!(
                "extra field {key} must not be null"
            )));
        }
    }
    Ok(())
}

fn multipart_boundary(content: &Bytes) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-boundary-{counter}");
        if !contains_bytes(content, boundary.as_bytes()) {
            return boundary;
        }
    }
    unreachable!("unbounded boundary counter")
}

fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

fn validate_header_param(name: &str, value: &str) -> Result<(), LingerError> {
    if value.trim().is_empty() {
        return Err(LingerError::invalid_config(format!("{name} is required")));
    }
    validate_header_value(name, value)
}

fn validate_header_value(name: &str, value: &str) -> Result<(), LingerError> {
    if value.contains('\r') || value.contains('\n') {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain CR or LF"
        )));
    }
    Ok(())
}

fn escape_multipart_param(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}