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
use crate::error::LingerError;
use crate::files::{FileExpirationPolicy, FileObject};
use crate::transport::HttpRequest;
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// EN: Request body for `POST /v1/uploads`.
/// 中文:`POST /v1/uploads` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateUploadRequest {
    /// EN: Total expected upload size in bytes.
    /// 中文:预期上传总大小,单位为字节。
    pub bytes: u64,
    /// EN: Final filename for the completed upload.
    /// 中文:完成上传后的最终文件名。
    pub filename: String,
    /// EN: MIME type for the completed upload.
    /// 中文:完成上传后的 MIME 类型。
    pub mime_type: String,
    /// EN: OpenAI file purpose.
    /// 中文:OpenAI 文件用途。
    pub purpose: String,
    /// EN: Optional expiration policy for supported purposes.
    /// 中文:受支持用途的可选过期策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_after: Option<FileExpirationPolicy>,
}

impl CreateUploadRequest {
    /// EN: Starts building an upload creation request.
    /// 中文:开始构建上传创建请求。
    pub fn builder() -> CreateUploadRequestBuilder {
        CreateUploadRequestBuilder::default()
    }
}

/// EN: Builder for upload creation requests.
/// 中文:上传创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateUploadRequestBuilder {
    bytes: Option<u64>,
    filename: Option<String>,
    mime_type: Option<String>,
    purpose: Option<String>,
    expires_after: Option<FileExpirationPolicy>,
}

impl CreateUploadRequestBuilder {
    /// EN: Sets the total expected upload size in bytes.
    /// 中文:设置预期上传总大小,单位为字节。
    pub fn bytes(mut self, bytes: u64) -> Self {
        self.bytes = Some(bytes);
        self
    }

    /// EN: Sets the final filename.
    /// 中文:设置最终文件名。
    pub fn filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// EN: Sets the MIME type.
    /// 中文:设置 MIME 类型。
    pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.mime_type = Some(mime_type.into());
        self
    }

    /// EN: Sets the file purpose.
    /// 中文:设置文件用途。
    pub fn purpose(mut self, purpose: impl Into<String>) -> Self {
        self.purpose = Some(purpose.into());
        self
    }

    /// EN: Sets the optional expiration policy.
    /// 中文:设置可选的过期策略。
    pub fn expires_after(mut self, expires_after: FileExpirationPolicy) -> Self {
        self.expires_after = Some(expires_after);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateUploadRequest, LingerError> {
        let bytes = self
            .bytes
            .filter(|bytes| *bytes > 0)
            .ok_or_else(|| LingerError::invalid_config("bytes must be greater than zero"))?;
        let filename = required_string("filename", self.filename)?;
        let mime_type = required_string("mime_type", self.mime_type)?;
        let purpose = required_string("purpose", self.purpose)?;
        if let Some(expires_after) = &self.expires_after {
            expires_after.validate_for_uploads()?;
        }
        Ok(CreateUploadRequest {
            bytes,
            filename,
            mime_type,
            purpose,
            expires_after: self.expires_after,
        })
    }
}

/// EN: Upload object returned by the Uploads API.
/// 中文:Uploads API 返回的上传对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct Upload {
    /// EN: Upload id.
    /// 中文:上传 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Total expected upload size in bytes.
    /// 中文:预期上传总大小,单位为字节。
    pub bytes: u64,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Unix timestamp for expiration.
    /// 中文:过期时间的 Unix 时间戳。
    pub expires_at: u64,
    /// EN: Final filename.
    /// 中文:最终文件名。
    pub filename: String,
    /// EN: File purpose.
    /// 中文:文件用途。
    pub purpose: String,
    /// EN: Upload status.
    /// 中文:上传状态。
    pub status: UploadStatus,
    /// EN: Completed file object, when returned.
    /// 中文:完成后返回的文件对象。
    #[serde(default)]
    pub file: Option<FileObject>,
    /// 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 Upload {
    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: Status of an OpenAI upload.
/// 中文:OpenAI 上传状态。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum UploadStatus {
    /// EN: Upload accepts more parts.
    /// 中文:上传仍接受更多分段。
    Pending,
    /// EN: Upload completed and produced a file.
    /// 中文:上传已完成并生成文件。
    Completed,
    /// EN: Upload was cancelled.
    /// 中文:上传已取消。
    Cancelled,
    /// EN: Upload expired before completion.
    /// 中文:上传在完成前过期。
    Expired,
    /// EN: Unknown status retained for forward compatibility.
    /// 中文:为前向兼容保留的未知状态。
    #[serde(other)]
    Unknown,
}

/// EN: Upload part object returned after adding part data.
/// 中文:添加分段数据后返回的上传分段对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct UploadPart {
    /// EN: Upload part id.
    /// 中文:上传分段 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Parent upload id.
    /// 中文:父上传 ID。
    pub upload_id: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl UploadPart {
    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: Uploadable part bytes and multipart metadata.
/// 中文:可上传分段字节及 multipart 元数据。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct UploadPartData {
    /// EN: Filename sent in the multipart part.
    /// 中文:multipart 分段中发送的文件名。
    pub filename: String,
    /// EN: Content type sent for the part.
    /// 中文:分段发送的内容类型。
    pub content_type: String,
    content: Bytes,
}

impl UploadPartData {
    /// EN: Creates upload part data 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 multipart part content type.
    /// 中文:设置 multipart 分段内容类型。
    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 part bytes as a cheap `Bytes` clone.
    /// 中文:以廉价 `Bytes` 克隆返回分段字节。
    pub fn bytes(&self) -> Bytes {
        self.content.clone()
    }
}

/// EN: Request body descriptor for `POST /v1/uploads/{upload_id}/parts`.
/// 中文:`POST /v1/uploads/{upload_id}/parts` 的请求体描述。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateUploadPartRequest {
    /// EN: Part data to add to the upload.
    /// 中文:要添加到上传的分段数据。
    pub data: UploadPartData,
}

impl CreateUploadPartRequest {
    /// EN: Starts building an upload part request.
    /// 中文:开始构建上传分段请求。
    pub fn builder() -> CreateUploadPartRequestBuilder {
        CreateUploadPartRequestBuilder::default()
    }

    pub(crate) fn apply_multipart_body(&self, request: &mut HttpRequest) {
        let boundary = multipart_boundary(&self.data.content);
        request.insert_header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        );
        request.set_body_stream(self.multipart_stream(boundary));
    }

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

/// EN: Builder for upload part requests.
/// 中文:上传分段请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateUploadPartRequestBuilder {
    data: Option<UploadPartData>,
}

impl CreateUploadPartRequestBuilder {
    /// EN: Sets the upload part data.
    /// 中文:设置上传分段数据。
    pub fn data(mut self, data: UploadPartData) -> Self {
        self.data = Some(data);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateUploadPartRequest, LingerError> {
        let data = self
            .data
            .ok_or_else(|| LingerError::invalid_config("data is required"))?;
        Ok(CreateUploadPartRequest { data })
    }
}

/// EN: Request body for `POST /v1/uploads/{upload_id}/complete`.
/// 中文:`POST /v1/uploads/{upload_id}/complete` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CompleteUploadRequest {
    /// EN: Ordered upload part ids to combine.
    /// 中文:要按顺序合并的上传分段 ID。
    pub part_ids: Vec<String>,
    /// EN: Optional MD5 checksum.
    /// 中文:可选的 MD5 校验值。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,
}

impl CompleteUploadRequest {
    /// EN: Starts building an upload completion request.
    /// 中文:开始构建上传完成请求。
    pub fn builder() -> CompleteUploadRequestBuilder {
        CompleteUploadRequestBuilder::default()
    }
}

/// EN: Builder for upload completion requests.
/// 中文:上传完成请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CompleteUploadRequestBuilder {
    part_ids: Vec<String>,
    md5: Option<String>,
}

impl CompleteUploadRequestBuilder {
    /// EN: Adds an upload part id in completion order.
    /// 中文:按完成顺序添加上传分段 ID。
    pub fn part_id(mut self, part_id: impl Into<String>) -> Self {
        self.part_ids.push(part_id.into());
        self
    }

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

    /// EN: Sets the optional MD5 checksum.
    /// 中文:设置可选的 MD5 校验值。
    pub fn md5(mut self, md5: impl Into<String>) -> Self {
        self.md5 = Some(md5.into());
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CompleteUploadRequest, LingerError> {
        if self.part_ids.is_empty() {
            return Err(LingerError::invalid_config("part_ids is required"));
        }
        for part_id in &self.part_ids {
            if part_id.trim().is_empty() {
                return Err(LingerError::invalid_config(
                    "part_ids must not contain empty values",
                ));
            }
        }
        if self
            .md5
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            return Err(LingerError::invalid_config("md5 must not be empty"));
        }
        Ok(CompleteUploadRequest {
            part_ids: self.part_ids,
            md5: self.md5,
        })
    }
}

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 multipart_boundary(content: &Bytes) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-upload-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('"', "\\\"")
}