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
616
617
618
619
620
621
622
623
624
625
626
627
628
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/assistants`.
/// 中文:`POST /v1/assistants` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateAssistantRequest {
/// EN: Assistant model id.
/// 中文:Assistant 使用的模型 ID。
pub model: String,
/// EN: Optional assistant name.
/// 中文:可选的 Assistant 名称。
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// EN: Optional assistant description.
/// 中文:可选的 Assistant 描述。
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// EN: Optional assistant instructions.
/// 中文:可选的 Assistant 指令。
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
/// EN: Tool descriptors available to the assistant.
/// 中文:Assistant 可用的工具描述。
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<Value>,
/// EN: Optional metadata.
/// 中文:可选元数据。
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: BTreeMap<String, String>,
/// EN: Forward-compatible optional fields not yet covered by handwritten types.
/// 中文:手写类型尚未覆盖的前向兼容可选字段。
#[serde(flatten)]
pub extra: BTreeMap<String, Value>,
}
impl CreateAssistantRequest {
/// EN: Starts building an Assistant creation request.
/// 中文:开始构建 Assistant 创建请求。
pub fn builder() -> CreateAssistantRequestBuilder {
CreateAssistantRequestBuilder::default()
}
}
/// EN: Builder for Assistant creation requests.
/// 中文:Assistant 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateAssistantRequestBuilder {
model: Option<String>,
name: Option<String>,
description: Option<String>,
instructions: Option<String>,
tools: Vec<Value>,
metadata: BTreeMap<String, String>,
extra: BTreeMap<String, Value>,
}
impl CreateAssistantRequestBuilder {
/// EN: Sets the Assistant model id.
/// 中文:设置 Assistant 模型 ID。
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
/// EN: Sets the optional Assistant name.
/// 中文:设置可选的 Assistant 名称。
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
/// EN: Sets the optional Assistant description.
/// 中文:设置可选的 Assistant 描述。
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
/// EN: Sets the optional Assistant instructions.
/// 中文:设置可选的 Assistant 指令。
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
/// EN: Adds a tool descriptor.
/// 中文:添加一个工具描述。
pub fn tool(mut self, tool: Value) -> Self {
self.tools.push(tool);
self
}
/// EN: Replaces the tool descriptor list.
/// 中文:替换工具描述列表。
pub fn tools(mut self, tools: impl IntoIterator<Item = Value>) -> Self {
self.tools = tools.into_iter().collect();
self
}
/// 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: 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<CreateAssistantRequest, LingerError> {
let model = required_string("model", self.model)?;
validate_optional_string("name", self.name.as_deref())?;
validate_optional_string("description", self.description.as_deref())?;
validate_optional_string("instructions", self.instructions.as_deref())?;
if self.tools.iter().any(Value::is_null) {
return Err(LingerError::invalid_config("tools must not contain null"));
}
for key in self.metadata.keys() {
if key.trim().is_empty() {
return Err(LingerError::invalid_config(
"metadata keys must not be empty",
));
}
}
Ok(CreateAssistantRequest {
model,
name: self.name,
description: self.description,
instructions: self.instructions,
tools: self.tools,
metadata: self.metadata,
extra: self.extra,
})
}
}
/// EN: Request body for `POST /v1/assistants/{assistant_id}`.
/// 中文:`POST /v1/assistants/{assistant_id}` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ModifyAssistantRequest {
/// EN: Optional replacement model id.
/// 中文:可选的替换模型 ID。
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
/// EN: Optional assistant name.
/// 中文:可选的 Assistant 名称。
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// EN: Optional assistant description.
/// 中文:可选的 Assistant 描述。
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// EN: Optional assistant instructions.
/// 中文:可选的 Assistant 指令。
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
/// EN: Tool descriptors available to the assistant.
/// 中文:Assistant 可用的工具描述。
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<Value>,
/// EN: Optional metadata replacement.
/// 中文:可选的元数据替换。
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: BTreeMap<String, String>,
/// EN: Forward-compatible optional fields not yet covered by handwritten types.
/// 中文:手写类型尚未覆盖的前向兼容可选字段。
#[serde(flatten)]
pub extra: BTreeMap<String, Value>,
}
impl ModifyAssistantRequest {
/// EN: Starts building an Assistant modify request.
/// 中文:开始构建 Assistant 修改请求。
pub fn builder() -> ModifyAssistantRequestBuilder {
ModifyAssistantRequestBuilder::default()
}
}
/// EN: Builder for Assistant modify requests.
/// 中文:Assistant 修改请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ModifyAssistantRequestBuilder {
model: Option<String>,
name: Option<String>,
description: Option<String>,
instructions: Option<String>,
tools: Vec<Value>,
metadata: BTreeMap<String, String>,
extra: BTreeMap<String, Value>,
}
impl ModifyAssistantRequestBuilder {
/// EN: Sets the optional replacement model id.
/// 中文:设置可选的替换模型 ID。
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
/// EN: Sets the optional Assistant name.
/// 中文:设置可选的 Assistant 名称。
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
/// EN: Sets the optional Assistant description.
/// 中文:设置可选的 Assistant 描述。
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
/// EN: Sets the optional Assistant instructions.
/// 中文:设置可选的 Assistant 指令。
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
/// EN: Adds a tool descriptor.
/// 中文:添加一个工具描述。
pub fn tool(mut self, tool: Value) -> Self {
self.tools.push(tool);
self
}
/// EN: Replaces the tool descriptor list.
/// 中文:替换工具描述列表。
pub fn tools(mut self, tools: impl IntoIterator<Item = Value>) -> Self {
self.tools = tools.into_iter().collect();
self
}
/// 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: 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<ModifyAssistantRequest, LingerError> {
validate_optional_string("model", self.model.as_deref())?;
validate_optional_string("name", self.name.as_deref())?;
validate_optional_string("description", self.description.as_deref())?;
validate_optional_string("instructions", self.instructions.as_deref())?;
if self.tools.iter().any(Value::is_null) {
return Err(LingerError::invalid_config("tools must not contain null"));
}
for key in self.metadata.keys() {
if key.trim().is_empty() {
return Err(LingerError::invalid_config(
"metadata keys must not be empty",
));
}
}
Ok(ModifyAssistantRequest {
model: self.model,
name: self.name,
description: self.description,
instructions: self.instructions,
tools: self.tools,
metadata: self.metadata,
extra: self.extra,
})
}
}
/// EN: Assistant object returned by the Assistants API.
/// 中文:Assistants API 返回的 Assistant 对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct Assistant {
/// EN: Assistant id.
/// 中文:Assistant ID。
pub id: String,
/// EN: API object type.
/// 中文:API 对象类型。
pub object: String,
/// EN: Unix timestamp for creation.
/// 中文:创建时间的 Unix 时间戳。
pub created_at: u64,
/// EN: Assistant model id.
/// 中文:Assistant 模型 ID。
pub model: String,
/// EN: Assistant name, when returned.
/// 中文:Assistant 名称,如响应中存在。
#[serde(default)]
pub name: Option<String>,
/// EN: Assistant description, when returned.
/// 中文:Assistant 描述,如响应中存在。
#[serde(default)]
pub description: Option<String>,
/// EN: Assistant instructions, when returned.
/// 中文:Assistant 指令,如响应中存在。
#[serde(default)]
pub instructions: Option<String>,
/// EN: Tool descriptors returned by the API.
/// 中文:API 返回的工具描述。
#[serde(default)]
pub tools: Vec<Value>,
/// EN: Metadata returned by the API.
/// 中文:API 返回的元数据。
#[serde(default)]
pub metadata: BTreeMap<String, String>,
/// EN: Response format returned by the API, when present.
/// 中文:API 返回的响应格式,如存在。
#[serde(default)]
pub response_format: Option<Value>,
/// EN: Temperature returned by the API, when present.
/// 中文:API 返回的 temperature,如存在。
#[serde(default)]
pub temperature: Option<f64>,
/// EN: Top-p returned by the API, when present.
/// 中文:API 返回的 top_p,如存在。
#[serde(default)]
pub top_p: Option<f64>,
/// 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 Assistant {
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 Assistant list returned by the Assistants API.
/// 中文:Assistants API 返回的分页 Assistant 列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct AssistantPage {
/// EN: API list object type.
/// 中文:API 列表对象类型。
pub object: String,
/// EN: Assistants on this page.
/// 中文:本页 Assistant。
#[serde(default)]
pub data: Vec<Assistant>,
/// EN: First Assistant id on this page.
/// 中文:本页第一个 Assistant ID。
#[serde(default)]
pub first_id: Option<String>,
/// EN: Last Assistant id on this page.
/// 中文:本页最后一个 Assistant ID。
#[serde(default)]
pub last_id: Option<String>,
/// EN: Whether more Assistants are available.
/// 中文:是否还有更多 Assistant。
pub has_more: bool,
/// EN: OpenAI request id from response headers.
/// 中文:响应头中的 OpenAI 请求 ID。
#[serde(skip)]
request_id: Option<RequestId>,
}
impl AssistantPage {
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: Sort order for Assistant list pagination.
/// 中文:Assistant 列表分页的排序方向。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AssistantListOrder {
/// EN: Ascending order.
/// 中文:升序。
Asc,
/// EN: Descending order.
/// 中文:降序。
Desc,
}
impl AssistantListOrder {
pub(crate) fn as_query_value(self) -> &'static str {
match self {
Self::Asc => "asc",
Self::Desc => "desc",
}
}
}
/// EN: Query parameters for `GET /v1/assistants`.
/// 中文:`GET /v1/assistants` 的查询参数。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AssistantListRequest {
/// EN: Maximum number of assistants to retrieve.
/// 中文:要获取的最大 Assistant 数量。
pub limit: Option<u8>,
/// EN: Sort order by creation timestamp.
/// 中文:按创建时间戳排序的方向。
pub order: Option<AssistantListOrder>,
/// EN: Cursor after which the next page starts.
/// 中文:下一页开始位置之前的游标。
pub after: Option<String>,
/// EN: Cursor before which the previous page starts.
/// 中文:上一页开始位置之后的游标。
pub before: Option<String>,
}
impl AssistantListRequest {
/// EN: Starts building Assistant list query parameters.
/// 中文:开始构建 Assistant 列表查询参数。
pub fn builder() -> AssistantListRequestBuilder {
AssistantListRequestBuilder::default()
}
pub(crate) fn path(&self) -> String {
path_with_query(
"/v1/assistants",
AssistantListQuery {
limit: self.limit,
order: self.order.map(AssistantListOrder::as_query_value),
after: self.after.as_deref(),
before: self.before.as_deref(),
},
)
}
}
/// EN: Builder for Assistant list query parameters.
/// 中文:Assistant 列表查询参数的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct AssistantListRequestBuilder {
limit: Option<u8>,
order: Option<AssistantListOrder>,
after: Option<String>,
before: Option<String>,
}
impl AssistantListRequestBuilder {
/// EN: Sets the maximum number of assistants to retrieve.
/// 中文:设置要获取的最大 Assistant 数量。
pub fn limit(mut self, limit: u8) -> Self {
self.limit = Some(limit);
self
}
/// EN: Sets the sort order by creation timestamp.
/// 中文:设置按创建时间戳排序的方向。
pub fn order(mut self, order: AssistantListOrder) -> Self {
self.order = Some(order);
self
}
/// EN: Sets the cursor after which the next page starts.
/// 中文:设置下一页开始位置之前的游标。
pub fn after(mut self, after: impl Into<String>) -> Self {
self.after = Some(after.into());
self
}
/// EN: Sets the cursor before which the previous page starts.
/// 中文:设置上一页开始位置之后的游标。
pub fn before(mut self, before: impl Into<String>) -> Self {
self.before = Some(before.into());
self
}
/// EN: Builds and validates the query parameters.
/// 中文:构建并校验查询参数。
pub fn build(self) -> Result<AssistantListRequest, LingerError> {
if let Some(limit) = self.limit {
if limit == 0 || limit > 100 {
return Err(LingerError::invalid_config(
"limit must be between 1 and 100",
));
}
}
if let Some(after) = &self.after {
if after.trim().is_empty() {
return Err(LingerError::invalid_config("after must not be empty"));
}
}
if let Some(before) = &self.before {
if before.trim().is_empty() {
return Err(LingerError::invalid_config("before must not be empty"));
}
}
Ok(AssistantListRequest {
limit: self.limit,
order: self.order,
after: self.after,
before: self.before,
})
}
}
/// EN: Deletion result returned by the Assistants API.
/// 中文:Assistants API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct AssistantDeletion {
/// EN: Deleted Assistant id.
/// 中文:已删除的 Assistant ID。
pub id: String,
/// EN: API object type.
/// 中文:API 对象类型。
pub object: String,
/// EN: Whether the Assistant was deleted.
/// 中文:Assistant 是否已删除。
pub deleted: bool,
/// EN: OpenAI request id from response headers.
/// 中文:响应头中的 OpenAI 请求 ID。
#[serde(skip)]
request_id: Option<RequestId>,
}
impl AssistantDeletion {
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()
}
}
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_optional_string(name: &str, value: Option<&str>) -> Result<(), LingerError> {
if value.is_some_and(|value| value.trim().is_empty()) {
return Err(LingerError::invalid_config(format!(
"{name} must not be empty"
)));
}
Ok(())
}
struct AssistantListQuery<'a> {
limit: Option<u8>,
order: Option<&'static str>,
after: Option<&'a str>,
before: Option<&'a str>,
}
fn path_with_query(base: &str, params: AssistantListQuery<'_>) -> String {
let mut query = Vec::new();
if let Some(limit) = params.limit {
query.push(format!("limit={limit}"));
}
if let Some(order) = params.order {
query.push(format!("order={order}"));
}
if let Some(after) = params.after {
query.push(format!("after={}", encode_query_value(after)));
}
if let Some(before) = params.before {
query.push(format!("before={}", encode_query_value(before)));
}
if query.is_empty() {
base.to_string()
} else {
format!("{base}?{}", query.join("&"))
}
}
fn encode_query_value(value: &str) -> String {
let mut encoded = String::new();
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
encoded.push(byte as char);
}
_ => {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
encoded.push('%');
encoded.push(HEX[(byte >> 4) as usize] as char);
encoded.push(HEX[(byte & 0x0F) as usize] as char);
}
}
}
encoded
}