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
use crate::error::LingerError;
use crate::RequestId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// EN: Request body for `POST /v1/chat/completions`.
/// 中文:`POST /v1/chat/completions` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateChatCompletionRequest {
    /// EN: Model id used to create the chat completion.
    /// 中文:用于创建 chat completion 的模型 ID。
    pub model: String,
    /// EN: Chat messages for the completion.
    /// 中文:用于 completion 的聊天消息。
    pub messages: Vec<ChatMessage>,
    /// EN: Optional upper bound for generated completion tokens.
    /// 中文:可选的生成 completion token 上限。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<u32>,
    /// EN: Optional sampling temperature.
    /// 中文:可选的采样温度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateChatCompletionRequest {
    /// EN: Starts building a chat-completion request.
    /// 中文:开始构建 chat completion 请求。
    pub fn builder() -> CreateChatCompletionRequestBuilder {
        CreateChatCompletionRequestBuilder::default()
    }
}

/// EN: Builder for chat-completion requests.
/// 中文:Chat completion 请求构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateChatCompletionRequestBuilder {
    model: Option<String>,
    messages: Vec<ChatMessage>,
    max_completion_tokens: Option<u32>,
    temperature: Option<f32>,
    extra: BTreeMap<String, Value>,
}

impl CreateChatCompletionRequestBuilder {
    /// EN: Sets the model id.
    /// 中文:设置模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Appends a chat message.
    /// 中文:追加一条聊天消息。
    pub fn message(mut self, message: ChatMessage) -> Self {
        self.messages.push(message);
        self
    }

    /// EN: Sets the generated completion token limit.
    /// 中文:设置生成 completion token 上限。
    pub fn max_completion_tokens(mut self, max_completion_tokens: u32) -> Self {
        self.max_completion_tokens = Some(max_completion_tokens);
        self
    }

    /// EN: Sets the sampling temperature.
    /// 中文:设置采样温度。
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        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<CreateChatCompletionRequest, LingerError> {
        let model = self
            .model
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("model is required"))?;
        if self.messages.is_empty() {
            return Err(LingerError::invalid_config("messages is required"));
        }
        if self
            .messages
            .iter()
            .any(|message| message.role.trim().is_empty() || message.content.is_empty())
        {
            return Err(LingerError::invalid_config(
                "message role and content must not be empty",
            ));
        }
        Ok(CreateChatCompletionRequest {
            model,
            messages: self.messages,
            max_completion_tokens: self.max_completion_tokens,
            temperature: self.temperature,
            extra: self.extra,
        })
    }
}

/// EN: Request body for modifying a stored chat completion.
/// 中文:修改已存储 chat completion 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ModifyChatCompletionRequest {
    /// EN: Metadata to attach to the stored chat completion.
    /// 中文:要附加到已存储 chat completion 的元数据。
    pub metadata: BTreeMap<String, String>,
}

impl ModifyChatCompletionRequest {
    /// EN: Starts building a stored chat-completion modification request.
    /// 中文:开始构建已存储 chat completion 修改请求。
    pub fn builder() -> ModifyChatCompletionRequestBuilder {
        ModifyChatCompletionRequestBuilder::default()
    }
}

/// EN: Builder for stored chat-completion modification requests.
/// 中文:已存储 chat completion 修改请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ModifyChatCompletionRequestBuilder {
    metadata: BTreeMap<String, String>,
}

impl ModifyChatCompletionRequestBuilder {
    /// EN: Adds a metadata key/value pair.
    /// 中文:添加一个元数据键值对。
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<ModifyChatCompletionRequest, LingerError> {
        validate_metadata(&self.metadata)?;
        Ok(ModifyChatCompletionRequest {
            metadata: self.metadata,
        })
    }
}

/// EN: Chat message request item.
/// 中文:聊天消息请求项。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChatMessage {
    /// EN: Message role such as `developer`, `system`, `user`, or `assistant`.
    /// 中文:消息角色,例如 `developer`、`system`、`user` 或 `assistant`。
    pub role: String,
    /// EN: Text content for this message.
    /// 中文:该消息的文本内容。
    pub content: String,
}

impl ChatMessage {
    /// EN: Creates a developer message.
    /// 中文:创建 developer 消息。
    pub fn developer(content: impl Into<String>) -> Self {
        Self::new("developer", content)
    }

    /// EN: Creates a system message.
    /// 中文:创建 system 消息。
    pub fn system(content: impl Into<String>) -> Self {
        Self::new("system", content)
    }

    /// EN: Creates a user message.
    /// 中文:创建 user 消息。
    pub fn user(content: impl Into<String>) -> Self {
        Self::new("user", content)
    }

    /// EN: Creates an assistant message.
    /// 中文:创建 assistant 消息。
    pub fn assistant(content: impl Into<String>) -> Self {
        Self::new("assistant", content)
    }

    /// EN: Creates a message with a custom role.
    /// 中文:创建自定义角色消息。
    pub fn new(role: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            role: role.into(),
            content: content.into(),
        }
    }
}

/// EN: Chat completion response object.
/// 中文:Chat completion 响应对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletion {
    /// EN: Chat completion id.
    /// 中文:Chat completion ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created: u64,
    /// EN: Model that produced the completion.
    /// 中文:生成 completion 的模型。
    pub model: String,
    /// EN: Completion choices.
    /// 中文:Completion 候选项。
    #[serde(default)]
    pub choices: Vec<ChatCompletionChoice>,
    /// EN: Token usage, when returned.
    /// 中文:Token 用量,如响应中存在。
    #[serde(default)]
    pub usage: Option<ChatCompletionUsage>,
    /// 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 ChatCompletion {
    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 stored chat completion list.
/// 中文:已存储 chat completion 的分页列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletionPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Chat completions on this page.
    /// 中文:本页中的 chat completion。
    #[serde(default)]
    pub data: Vec<ChatCompletion>,
    /// EN: First item id on this page.
    /// 中文:本页第一个项目 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last item id on this page.
    /// 中文:本页最后一个项目 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more items are available.
    /// 中文:是否还有更多项目。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ChatCompletionPage {
    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 for stored chat completions.
/// 中文:已存储 chat completion 的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChatCompletionDeletion {
    /// EN: Deleted chat completion id.
    /// 中文:已删除的 chat completion ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the chat completion was deleted.
    /// 中文:chat completion 是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ChatCompletionDeletion {
    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: Single chat completion choice.
/// 中文:单个 chat completion 候选项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletionChoice {
    /// EN: Choice index.
    /// 中文:候选项索引。
    pub index: u32,
    /// EN: Assistant message for this choice.
    /// 中文:该候选项的助手消息。
    pub message: ChatCompletionMessage,
    /// EN: Finish reason, when returned.
    /// 中文:结束原因,如响应中存在。
    #[serde(default)]
    pub finish_reason: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Chat completion message returned by the API.
/// 中文:API 返回的 chat completion 消息。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletionMessage {
    /// EN: Message role.
    /// 中文:消息角色。
    pub role: String,
    /// EN: Text content, when returned.
    /// 中文:文本内容,如响应中存在。
    #[serde(default)]
    pub content: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Stored chat completion message returned by the API.
/// 中文:API 返回的已存储 chat completion 消息。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletionStoredMessage {
    /// EN: Stored message id.
    /// 中文:已存储消息 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Message role.
    /// 中文:消息角色。
    pub role: String,
    /// EN: Text content, when returned.
    /// 中文:文本内容,如响应中存在。
    #[serde(default)]
    pub content: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Paginated stored chat completion messages.
/// 中文:已存储 chat completion 消息的分页列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ChatCompletionMessagePage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Stored messages on this page.
    /// 中文:本页中的已存储消息。
    #[serde(default)]
    pub data: Vec<ChatCompletionStoredMessage>,
    /// EN: First item id on this page.
    /// 中文:本页第一个项目 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last item id on this page.
    /// 中文:本页最后一个项目 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more items are available.
    /// 中文:是否还有更多项目。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl ChatCompletionMessagePage {
    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: Token usage for a chat completion.
/// 中文:Chat completion 的 token 用量。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChatCompletionUsage {
    /// EN: Prompt token count.
    /// 中文:Prompt token 数量。
    pub prompt_tokens: u64,
    /// EN: Completion token count.
    /// 中文:Completion token 数量。
    pub completion_tokens: u64,
    /// EN: Total token count.
    /// 中文:总 token 数量。
    pub total_tokens: u64,
}

fn validate_metadata(metadata: &BTreeMap<String, String>) -> Result<(), LingerError> {
    for key in metadata.keys() {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "metadata keys must not be empty",
            ));
        }
    }
    Ok(())
}