Skip to main content

openai_core/resources/
longtail.rs

1use std::time::Duration;
2
3use bytes::Bytes;
4use http::Method;
5use tokio_util::sync::CancellationToken;
6
7use super::*;
8use crate::files::UploadSource;
9use crate::generated::endpoints;
10use crate::json_payload::JsonPayload;
11use crate::response_meta::ApiResponse;
12use crate::stream::{RawSseStream, SseStream};
13use crate::transport::RequestSpec;
14
15macro_rules! json_payload_wrapper {
16    ($(#[$meta:meta])* $name:ident) => {
17        $(#[$meta])*
18        #[derive(Debug, Clone, Serialize, Deserialize)]
19        #[serde(transparent)]
20        pub struct $name(Value);
21
22        impl Default for $name {
23            fn default() -> Self {
24                Self(Value::Null)
25            }
26        }
27
28        impl From<Value> for $name {
29            fn from(value: Value) -> Self {
30                Self(value)
31            }
32        }
33
34        impl From<$name> for Value {
35            fn from(value: $name) -> Self {
36                value.0
37            }
38        }
39
40        impl $name {
41            /// 返回未经解释的原始 JSON 值。
42            pub fn as_raw(&self) -> &Value {
43                &self.0
44            }
45
46            /// 消费该包装器并返回原始 JSON 值。
47            pub fn into_raw(self) -> Value {
48                self.0
49            }
50
51            /// 返回载荷中的 `type` 字段,若存在且为字符串。
52            pub fn kind(&self) -> Option<&str> {
53                self.0.get("type").and_then(Value::as_str)
54            }
55        }
56    };
57}
58
59json_payload_wrapper!(
60    /// 表示 conversation item 的内容片段。
61    ConversationContentPart
62);
63json_payload_wrapper!(
64    /// 表示 conversation 创建时的初始条目。
65    ConversationInputItem
66);
67json_payload_wrapper!(
68    /// 表示 eval 数据源配置。
69    EvalDataSourceConfig
70);
71json_payload_wrapper!(
72    /// 表示 eval 测试标准项。
73    EvalTestingCriterion
74);
75json_payload_wrapper!(
76    /// 表示 eval run 的输入载荷。
77    EvalRunInput
78);
79json_payload_wrapper!(
80    /// 表示 eval 输出项载荷。
81    EvalOutput
82);
83json_payload_wrapper!(
84    /// 表示 skill version 内容载荷。
85    SkillVersionContent
86);
87
88/// 表示音频转写 segment ID。
89#[derive(Debug, Clone, Serialize, Deserialize)]
90#[serde(untagged)]
91pub enum AudioTranscriptionSegmentId {
92    /// 数值 ID。
93    Number(u64),
94    /// 字符串 ID。
95    String(String),
96}
97
98/// 表示音频转写分段。
99#[derive(Debug, Clone, Serialize, Deserialize, Default)]
100pub struct AudioTranscriptionSegment {
101    /// 分段 ID。
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub id: Option<AudioTranscriptionSegmentId>,
104    /// 平均 logprob。
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub avg_logprob: Option<f64>,
107    /// 压缩比。
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub compression_ratio: Option<f64>,
110    /// 结束时间。
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub end: Option<f64>,
113    /// 静音概率。
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub no_speech_prob: Option<f64>,
116    /// seek 偏移。
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub seek: Option<u64>,
119    /// 说话人。
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub speaker: Option<String>,
122    /// 开始时间。
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub start: Option<f64>,
125    /// 采样温度。
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub temperature: Option<f64>,
128    /// 文本内容。
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub text: Option<String>,
131    /// token ID 列表。
132    #[serde(default)]
133    pub tokens: Vec<u64>,
134    /// 分段类型。
135    #[serde(rename = "type")]
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub segment_type: Option<String>,
138    /// 额外字段。
139    #[serde(flatten)]
140    pub extra: BTreeMap<String, Value>,
141}
142
143/// 表示音频转写词级时间戳。
144#[derive(Debug, Clone, Serialize, Deserialize, Default)]
145pub struct AudioTranscriptionWord {
146    /// 词文本。
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub word: Option<String>,
149    /// 开始时间。
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub start: Option<f64>,
152    /// 结束时间。
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub end: Option<f64>,
155    /// 概率。
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub probability: Option<f64>,
158    /// 额外字段。
159    #[serde(flatten)]
160    pub extra: BTreeMap<String, Value>,
161}
162
163/// 表示 fine-tuning 超参数值。
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(untagged)]
166pub enum FineTuningHyperparameterValue {
167    /// 字符串配置,通常为 `auto`。
168    Text(String),
169    /// 整型配置。
170    Integer(u64),
171    /// 浮点配置。
172    Float(f64),
173}
174
175/// 表示 fine-tuning 超参数。
176#[derive(Debug, Clone, Serialize, Deserialize, Default)]
177pub struct FineTuningJobHyperparameters {
178    /// batch size。
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub batch_size: Option<FineTuningHyperparameterValue>,
181    /// learning rate multiplier。
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub learning_rate_multiplier: Option<FineTuningHyperparameterValue>,
184    /// epoch 数。
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub n_epochs: Option<FineTuningHyperparameterValue>,
187    /// 额外字段。
188    #[serde(flatten)]
189    pub extra: BTreeMap<String, Value>,
190}
191
192/// 表示 fine-tuning 错误。
193#[derive(Debug, Clone, Serialize, Deserialize, Default)]
194pub struct FineTuningJobError {
195    /// 错误码。
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub code: Option<String>,
198    /// 错误消息。
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub message: Option<String>,
201    /// 关联参数。
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub param: Option<String>,
204    /// 额外字段。
205    #[serde(flatten)]
206    pub extra: BTreeMap<String, Value>,
207}
208
209/// 表示 fine-tuning 指标。
210#[derive(Debug, Clone, Serialize, Deserialize, Default)]
211pub struct FineTuningMetrics {
212    /// 完整验证集 loss。
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub full_valid_loss: Option<f64>,
215    /// 完整验证集平均 token 准确率。
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub full_valid_mean_token_accuracy: Option<f64>,
218    /// 当前 step。
219    #[serde(skip_serializing_if = "Option::is_none")]
220    pub step: Option<u64>,
221    /// 训练 loss。
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub train_loss: Option<f64>,
224    /// 训练平均 token 准确率。
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub train_mean_token_accuracy: Option<f64>,
227    /// 验证 loss。
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub valid_loss: Option<f64>,
230    /// 验证平均 token 准确率。
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub valid_mean_token_accuracy: Option<f64>,
233    /// 额外字段。
234    #[serde(flatten)]
235    pub extra: BTreeMap<String, Value>,
236}
237
238/// 表示 Weights & Biases 集成配置。
239#[derive(Debug, Clone, Serialize, Deserialize, Default)]
240pub struct FineTuningWandbIntegration {
241    /// 项目名。
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub project: Option<String>,
244    /// 实体名。
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub entity: Option<String>,
247    /// 展示名称。
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub name: Option<String>,
250    /// 标签集合。
251    #[serde(default)]
252    #[serde(skip_serializing_if = "Vec::is_empty")]
253    pub tags: Vec<String>,
254    /// 额外字段。
255    #[serde(flatten)]
256    pub extra: BTreeMap<String, Value>,
257}
258
259/// 表示 fine-tuning 集成项。
260#[derive(Debug, Clone, Serialize, Deserialize, Default)]
261pub struct FineTuningJobIntegration {
262    /// 集成类型。
263    #[serde(rename = "type")]
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub integration_type: Option<String>,
266    /// Weights & Biases 配置。
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub wandb: Option<FineTuningWandbIntegration>,
269    /// 额外字段。
270    #[serde(flatten)]
271    pub extra: BTreeMap<String, Value>,
272}
273
274/// 表示 container 过期策略。
275#[derive(Debug, Clone, Serialize, Deserialize, Default)]
276pub struct ContainerExpiresAfter {
277    /// 锚点。
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub anchor: Option<String>,
280    /// 过期分钟数。
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub minutes: Option<u64>,
283    /// 额外字段。
284    #[serde(flatten)]
285    pub extra: BTreeMap<String, Value>,
286}
287
288/// 表示单个图像输出。
289#[derive(Debug, Clone, Serialize, Deserialize, Default)]
290pub struct ImageData {
291    /// 远程图片 URL。
292    pub url: Option<String>,
293    /// Base64 编码的图片内容。
294    pub b64_json: Option<String>,
295    /// 模型重写后的 prompt。
296    pub revised_prompt: Option<String>,
297    /// 额外字段。
298    #[serde(flatten)]
299    pub extra: BTreeMap<String, Value>,
300}
301
302/// 表示图像生成响应。
303#[derive(Debug, Clone, Serialize, Deserialize, Default)]
304pub struct ImageGenerationResponse {
305    /// 创建时间。
306    pub created: Option<u64>,
307    /// 图像结果列表。
308    #[serde(default)]
309    pub data: Vec<ImageData>,
310    /// 额外字段。
311    #[serde(flatten)]
312    pub extra: BTreeMap<String, Value>,
313}
314
315/// 表示图像生成请求参数。
316#[derive(Debug, Clone, Serialize, Deserialize, Default)]
317pub struct ImageGenerateParams {
318    /// 模型 ID。
319    #[serde(skip_serializing_if = "Option::is_none")]
320    pub model: Option<String>,
321    /// 生成提示词。
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub prompt: Option<String>,
324    /// 结果数量。
325    #[serde(skip_serializing_if = "Option::is_none")]
326    pub n: Option<u32>,
327    /// 图像尺寸。
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub size: Option<String>,
330    /// 图像质量。
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub quality: Option<String>,
333    /// 响应格式。
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub response_format: Option<String>,
336    /// 背景模式。
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub background: Option<String>,
339    /// 输出格式。
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub output_format: Option<String>,
342    /// 审核策略。
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub moderation: Option<String>,
345    /// 是否启用流式图片事件。
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub stream: Option<bool>,
348    /// 局部图片数量。
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub partial_images: Option<u32>,
351    /// 用户标识。
352    #[serde(skip_serializing_if = "Option::is_none")]
353    pub user: Option<String>,
354    /// 自定义 metadata。
355    #[serde(default, skip_serializing_if = "metadata_is_empty")]
356    pub metadata: BTreeMap<String, String>,
357    /// 额外字段。
358    #[serde(flatten)]
359    pub extra: BTreeMap<String, Value>,
360}
361
362/// 表示语音合成请求参数。
363#[derive(Debug, Clone, Serialize, Deserialize, Default)]
364pub struct AudioSpeechCreateParams {
365    /// 模型 ID。
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub model: Option<String>,
368    /// 声音名称。
369    #[serde(skip_serializing_if = "Option::is_none")]
370    pub voice: Option<String>,
371    /// 输入文本。
372    #[serde(skip_serializing_if = "Option::is_none")]
373    pub input: Option<String>,
374    /// 可选指令。
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub instructions: Option<String>,
377    /// 输出音频格式。
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub format: Option<String>,
380    /// 语速。
381    #[serde(skip_serializing_if = "Option::is_none")]
382    pub speed: Option<f32>,
383    /// 额外字段。
384    #[serde(flatten)]
385    pub extra: BTreeMap<String, Value>,
386}
387
388/// 表示音频转写响应。
389#[derive(Debug, Clone, Serialize, Deserialize, Default)]
390pub struct AudioTranscription {
391    /// 转写文本。
392    #[serde(default)]
393    pub text: String,
394    /// 语言代码。
395    pub language: Option<String>,
396    /// 音频时长。
397    pub duration: Option<f64>,
398    /// 分段结果。
399    #[serde(default)]
400    pub segments: Vec<AudioTranscriptionSegment>,
401    /// 词级结果。
402    #[serde(default)]
403    pub words: Vec<AudioTranscriptionWord>,
404    /// 额外字段。
405    #[serde(flatten)]
406    pub extra: BTreeMap<String, Value>,
407}
408
409/// 表示音频翻译响应。
410#[derive(Debug, Clone, Serialize, Deserialize, Default)]
411pub struct AudioTranslation {
412    /// 翻译文本。
413    #[serde(default)]
414    pub text: String,
415    /// 语言代码。
416    pub language: Option<String>,
417    /// 音频时长。
418    pub duration: Option<f64>,
419    /// 分段结果。
420    #[serde(default)]
421    pub segments: Vec<AudioTranscriptionSegment>,
422    /// 词级结果。
423    #[serde(default)]
424    pub words: Vec<AudioTranscriptionWord>,
425    /// 额外字段。
426    #[serde(flatten)]
427    pub extra: BTreeMap<String, Value>,
428}
429
430/// 表示 fine-tuning job。
431#[derive(Debug, Clone, Serialize, Deserialize, Default)]
432pub struct FineTuningJob {
433    /// Job ID。
434    pub id: String,
435    /// 对象类型。
436    #[serde(default)]
437    pub object: String,
438    /// 基础模型。
439    pub model: Option<String>,
440    /// 产出的微调模型。
441    pub fine_tuned_model: Option<String>,
442    /// 当前状态。
443    pub status: Option<String>,
444    /// 训练文件 ID。
445    pub training_file: Option<String>,
446    /// 验证文件 ID。
447    pub validation_file: Option<String>,
448    /// 创建时间。
449    pub created_at: Option<u64>,
450    /// 完成时间。
451    pub finished_at: Option<u64>,
452    /// 已训练 token 数。
453    pub trained_tokens: Option<u64>,
454    /// 自定义 metadata。
455    #[serde(default)]
456    pub metadata: BTreeMap<String, String>,
457    /// 超参数配置。
458    pub hyperparameters: Option<FineTuningJobHyperparameters>,
459    /// 结果文件。
460    #[serde(default)]
461    pub result_files: Vec<String>,
462    /// 错误信息。
463    pub error: Option<FineTuningJobError>,
464    /// 额外字段。
465    #[serde(flatten)]
466    pub extra: BTreeMap<String, Value>,
467}
468
469/// 表示 fine-tuning job 事件。
470#[derive(Debug, Clone, Serialize, Deserialize, Default)]
471pub struct FineTuningJobEvent {
472    /// 事件 ID。
473    pub id: Option<String>,
474    /// 对象类型。
475    #[serde(default)]
476    pub object: String,
477    /// 事件类型。
478    #[serde(rename = "type")]
479    pub event_type: Option<String>,
480    /// 日志级别。
481    pub level: Option<String>,
482    /// 事件消息。
483    pub message: Option<String>,
484    /// 创建时间。
485    pub created_at: Option<u64>,
486    /// 额外数据。
487    pub data: Option<FineTuningMetrics>,
488    /// 额外字段。
489    #[serde(flatten)]
490    pub extra: BTreeMap<String, Value>,
491}
492
493/// 表示 fine-tuning checkpoint。
494#[derive(Debug, Clone, Serialize, Deserialize, Default)]
495pub struct FineTuningCheckpoint {
496    /// Checkpoint ID。
497    pub id: String,
498    /// 对象类型。
499    #[serde(default)]
500    pub object: String,
501    /// 所属 job ID。
502    pub fine_tuning_job_id: Option<String>,
503    /// Checkpoint 模型 ID。
504    pub fine_tuned_model_checkpoint: Option<String>,
505    /// 步数。
506    pub step_number: Option<u64>,
507    /// 创建时间。
508    pub created_at: Option<u64>,
509    /// 指标。
510    pub metrics: Option<FineTuningMetrics>,
511    /// 额外字段。
512    #[serde(flatten)]
513    pub extra: BTreeMap<String, Value>,
514}
515
516/// 表示 fine-tuning checkpoint permission。
517#[derive(Debug, Clone, Serialize, Deserialize, Default)]
518pub struct FineTuningCheckpointPermission {
519    /// Permission ID。
520    pub id: String,
521    /// 对象类型。
522    #[serde(default)]
523    pub object: String,
524    /// 项目 ID。
525    pub project_id: Option<String>,
526    /// Checkpoint ID。
527    pub fine_tuning_checkpoint_id: Option<String>,
528    /// 创建时间。
529    pub created_at: Option<u64>,
530    /// 额外字段。
531    #[serde(flatten)]
532    pub extra: BTreeMap<String, Value>,
533}
534
535/// 表示 fine-tuning job 创建参数。
536#[derive(Debug, Clone, Serialize, Deserialize, Default)]
537pub struct FineTuningJobCreateParams {
538    /// 模型 ID。
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub model: Option<String>,
541    /// 训练文件 ID。
542    #[serde(skip_serializing_if = "Option::is_none")]
543    pub training_file: Option<String>,
544    /// 验证文件 ID。
545    #[serde(skip_serializing_if = "Option::is_none")]
546    pub validation_file: Option<String>,
547    /// 后缀。
548    #[serde(skip_serializing_if = "Option::is_none")]
549    pub suffix: Option<String>,
550    /// 随机种子。
551    #[serde(skip_serializing_if = "Option::is_none")]
552    pub seed: Option<u64>,
553    /// 超参数。
554    #[serde(skip_serializing_if = "Option::is_none")]
555    pub hyperparameters: Option<FineTuningJobHyperparameters>,
556    /// 集成配置。
557    #[serde(default, skip_serializing_if = "Vec::is_empty")]
558    pub integrations: Vec<FineTuningJobIntegration>,
559    /// 自定义 metadata。
560    #[serde(default, skip_serializing_if = "metadata_is_empty")]
561    pub metadata: BTreeMap<String, String>,
562    /// 额外字段。
563    #[serde(flatten)]
564    pub extra: BTreeMap<String, Value>,
565}
566
567/// 表示 batch 对象。
568#[derive(Debug, Clone, Serialize, Deserialize, Default)]
569pub struct Batch {
570    /// Batch ID。
571    pub id: String,
572    /// 对象类型。
573    #[serde(default)]
574    pub object: String,
575    /// 接口路径。
576    pub endpoint: Option<String>,
577    /// 当前状态。
578    pub status: Option<String>,
579    /// 输入文件 ID。
580    pub input_file_id: Option<String>,
581    /// 输出文件 ID。
582    pub output_file_id: Option<String>,
583    /// 错误文件 ID。
584    pub error_file_id: Option<String>,
585    /// 完成窗口。
586    pub completion_window: Option<String>,
587    /// 创建时间。
588    pub created_at: Option<u64>,
589    /// 取消时间。
590    pub cancelled_at: Option<u64>,
591    /// 开始取消时间。
592    pub cancelling_at: Option<u64>,
593    /// 完成时间。
594    pub completed_at: Option<u64>,
595    /// 过期时间。
596    pub expired_at: Option<u64>,
597    /// 预计过期时间。
598    pub expires_at: Option<u64>,
599    /// 失败时间。
600    pub failed_at: Option<u64>,
601    /// 开始最终整理时间。
602    pub finalizing_at: Option<u64>,
603    /// 开始执行时间。
604    pub in_progress_at: Option<u64>,
605    /// 自定义 metadata。
606    #[serde(default)]
607    pub metadata: BTreeMap<String, String>,
608    /// 处理该 batch 的模型。
609    pub model: Option<String>,
610    /// 请求统计。
611    pub request_counts: Option<BatchRequestCounts>,
612    /// 错误摘要。
613    pub errors: Option<BatchErrors>,
614    /// token 用量统计。
615    pub usage: Option<BatchUsage>,
616    /// 额外字段。
617    #[serde(flatten)]
618    pub extra: BTreeMap<String, Value>,
619}
620
621/// 表示 batch 的单条错误。
622#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
623pub struct BatchError {
624    /// 错误码。
625    pub code: Option<String>,
626    /// 输入文件中的行号。
627    pub line: Option<u64>,
628    /// 错误消息。
629    pub message: Option<String>,
630    /// 相关参数名。
631    pub param: Option<String>,
632    /// 额外字段。
633    #[serde(flatten)]
634    pub extra: BTreeMap<String, Value>,
635}
636
637/// 表示 batch 的错误摘要列表。
638#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
639pub struct BatchErrors {
640    /// 错误列表。
641    #[serde(default)]
642    pub data: Vec<BatchError>,
643    /// 对象类型。
644    pub object: Option<String>,
645    /// 额外字段。
646    #[serde(flatten)]
647    pub extra: BTreeMap<String, Value>,
648}
649
650/// 表示 batch 内各状态请求数。
651#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
652pub struct BatchRequestCounts {
653    /// 已完成请求数。
654    #[serde(default)]
655    pub completed: u64,
656    /// 失败请求数。
657    #[serde(default)]
658    pub failed: u64,
659    /// 总请求数。
660    #[serde(default)]
661    pub total: u64,
662    /// 额外字段。
663    #[serde(flatten)]
664    pub extra: BTreeMap<String, Value>,
665}
666
667/// 表示 batch 输入 token 明细。
668#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
669pub struct BatchUsageInputTokensDetails {
670    /// 缓存命中的 token 数。
671    pub cached_tokens: Option<u64>,
672    /// 额外字段。
673    #[serde(flatten)]
674    pub extra: BTreeMap<String, Value>,
675}
676
677/// 表示 batch 输出 token 明细。
678#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
679pub struct BatchUsageOutputTokensDetails {
680    /// reasoning token 数。
681    pub reasoning_tokens: Option<u64>,
682    /// 额外字段。
683    #[serde(flatten)]
684    pub extra: BTreeMap<String, Value>,
685}
686
687/// 表示 batch token 用量。
688#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
689pub struct BatchUsage {
690    /// 输入 token 数。
691    #[serde(default)]
692    pub input_tokens: u64,
693    /// 输入 token 明细。
694    pub input_tokens_details: Option<BatchUsageInputTokensDetails>,
695    /// 输出 token 数。
696    #[serde(default)]
697    pub output_tokens: u64,
698    /// 输出 token 明细。
699    pub output_tokens_details: Option<BatchUsageOutputTokensDetails>,
700    /// 总 token 数。
701    #[serde(default)]
702    pub total_tokens: u64,
703    /// 额外字段。
704    #[serde(flatten)]
705    pub extra: BTreeMap<String, Value>,
706}
707
708/// 表示 batch 创建参数。
709#[derive(Debug, Clone, Serialize, Deserialize, Default)]
710pub struct BatchCreateParams {
711    /// 输入文件 ID。
712    #[serde(skip_serializing_if = "Option::is_none")]
713    pub input_file_id: Option<String>,
714    /// 目标接口路径。
715    #[serde(skip_serializing_if = "Option::is_none")]
716    pub endpoint: Option<String>,
717    /// 完成窗口。
718    #[serde(skip_serializing_if = "Option::is_none")]
719    pub completion_window: Option<String>,
720    /// 自定义 metadata。
721    #[serde(default, skip_serializing_if = "metadata_is_empty")]
722    pub metadata: BTreeMap<String, String>,
723    /// 额外字段。
724    #[serde(flatten)]
725    pub extra: BTreeMap<String, Value>,
726}
727
728/// 表示 conversation 对象。
729#[derive(Debug, Clone, Serialize, Deserialize, Default)]
730pub struct Conversation {
731    /// Conversation ID。
732    pub id: String,
733    /// 对象类型。
734    #[serde(default)]
735    pub object: String,
736    /// 名称。
737    pub name: Option<String>,
738    /// 创建时间。
739    pub created_at: Option<u64>,
740    /// 自定义 metadata。
741    #[serde(default)]
742    pub metadata: BTreeMap<String, String>,
743    /// 额外字段。
744    #[serde(flatten)]
745    pub extra: BTreeMap<String, Value>,
746}
747
748/// 表示 conversation item 对象。
749#[derive(Debug, Clone, Serialize, Deserialize, Default)]
750pub struct ConversationItem {
751    /// Item ID。
752    pub id: String,
753    /// 对象类型。
754    #[serde(default)]
755    pub object: String,
756    /// Item 类型。
757    #[serde(rename = "type")]
758    pub item_type: Option<String>,
759    /// 当前状态。
760    pub status: Option<String>,
761    /// 角色。
762    pub role: Option<String>,
763    /// 内容列表。
764    #[serde(default)]
765    pub content: Vec<ConversationContentPart>,
766    /// 自定义 metadata。
767    #[serde(default)]
768    pub metadata: BTreeMap<String, String>,
769    /// 额外字段。
770    #[serde(flatten)]
771    pub extra: BTreeMap<String, Value>,
772}
773
774/// 表示 conversation 创建参数。
775#[derive(Debug, Clone, Serialize, Deserialize, Default)]
776pub struct ConversationCreateParams {
777    /// 名称。
778    #[serde(skip_serializing_if = "Option::is_none")]
779    pub name: Option<String>,
780    /// 初始条目。
781    #[serde(default, skip_serializing_if = "Vec::is_empty")]
782    pub items: Vec<ConversationInputItem>,
783    /// 自定义 metadata。
784    #[serde(default, skip_serializing_if = "metadata_is_empty")]
785    pub metadata: BTreeMap<String, String>,
786    /// 额外字段。
787    #[serde(flatten)]
788    pub extra: BTreeMap<String, Value>,
789}
790
791/// 表示 conversation 更新参数。
792#[derive(Debug, Clone, Serialize, Deserialize, Default)]
793pub struct ConversationUpdateParams {
794    /// 名称。
795    #[serde(skip_serializing_if = "Option::is_none")]
796    pub name: Option<String>,
797    /// 自定义 metadata。
798    #[serde(default, skip_serializing_if = "metadata_is_empty")]
799    pub metadata: BTreeMap<String, String>,
800    /// 额外字段。
801    #[serde(flatten)]
802    pub extra: BTreeMap<String, Value>,
803}
804
805/// 表示 conversation item 创建参数。
806#[derive(Debug, Clone, Serialize, Deserialize, Default)]
807pub struct ConversationItemCreateParams {
808    /// Item 类型。
809    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
810    pub item_type: Option<String>,
811    /// 角色。
812    #[serde(skip_serializing_if = "Option::is_none")]
813    pub role: Option<String>,
814    /// 内容列表。
815    #[serde(default, skip_serializing_if = "Vec::is_empty")]
816    pub content: Vec<ConversationContentPart>,
817    /// 自定义 metadata。
818    #[serde(default, skip_serializing_if = "metadata_is_empty")]
819    pub metadata: BTreeMap<String, String>,
820    /// 额外字段。
821    #[serde(flatten)]
822    pub extra: BTreeMap<String, Value>,
823}
824
825/// 表示 eval 对象。
826#[derive(Debug, Clone, Serialize, Deserialize, Default)]
827pub struct Eval {
828    /// Eval ID。
829    pub id: String,
830    /// 对象类型。
831    #[serde(default)]
832    pub object: String,
833    /// 名称。
834    pub name: Option<String>,
835    /// 当前状态。
836    pub status: Option<String>,
837    /// 创建时间。
838    pub created_at: Option<u64>,
839    /// 自定义 metadata。
840    #[serde(default)]
841    pub metadata: BTreeMap<String, String>,
842    /// 额外字段。
843    #[serde(flatten)]
844    pub extra: BTreeMap<String, Value>,
845}
846
847/// 表示 eval run 对象。
848#[derive(Debug, Clone, Serialize, Deserialize, Default)]
849pub struct EvalRun {
850    /// Run ID。
851    pub id: String,
852    /// 对象类型。
853    #[serde(default)]
854    pub object: String,
855    /// Eval ID。
856    pub eval_id: Option<String>,
857    /// 当前状态。
858    pub status: Option<String>,
859    /// 创建时间。
860    pub created_at: Option<u64>,
861    /// 自定义 metadata。
862    #[serde(default)]
863    pub metadata: BTreeMap<String, String>,
864    /// 额外字段。
865    #[serde(flatten)]
866    pub extra: BTreeMap<String, Value>,
867}
868
869/// 表示 eval run output item。
870#[derive(Debug, Clone, Serialize, Deserialize, Default)]
871pub struct EvalOutputItem {
872    /// Item ID。
873    pub id: String,
874    /// 对象类型。
875    #[serde(default)]
876    pub object: String,
877    /// 当前状态。
878    pub status: Option<String>,
879    /// 输出内容。
880    pub output: Option<EvalOutput>,
881    /// 额外字段。
882    #[serde(flatten)]
883    pub extra: BTreeMap<String, Value>,
884}
885
886/// 表示 eval 创建参数。
887#[derive(Debug, Clone, Serialize, Deserialize, Default)]
888pub struct EvalCreateParams {
889    /// 名称。
890    #[serde(skip_serializing_if = "Option::is_none")]
891    pub name: Option<String>,
892    /// 数据源。
893    #[serde(skip_serializing_if = "Option::is_none")]
894    pub data_source: Option<EvalDataSourceConfig>,
895    /// 测试标准。
896    #[serde(default, skip_serializing_if = "Vec::is_empty")]
897    pub testing_criteria: Vec<EvalTestingCriterion>,
898    /// 自定义 metadata。
899    #[serde(default, skip_serializing_if = "metadata_is_empty")]
900    pub metadata: BTreeMap<String, String>,
901    /// 额外字段。
902    #[serde(flatten)]
903    pub extra: BTreeMap<String, Value>,
904}
905
906/// 表示 eval 更新参数。
907#[derive(Debug, Clone, Serialize, Deserialize, Default)]
908pub struct EvalUpdateParams {
909    /// 名称。
910    #[serde(skip_serializing_if = "Option::is_none")]
911    pub name: Option<String>,
912    /// 数据源。
913    #[serde(skip_serializing_if = "Option::is_none")]
914    pub data_source: Option<EvalDataSourceConfig>,
915    /// 测试标准。
916    #[serde(default, skip_serializing_if = "Vec::is_empty")]
917    pub testing_criteria: Vec<EvalTestingCriterion>,
918    /// 自定义 metadata。
919    #[serde(default, skip_serializing_if = "metadata_is_empty")]
920    pub metadata: BTreeMap<String, String>,
921    /// 额外字段。
922    #[serde(flatten)]
923    pub extra: BTreeMap<String, Value>,
924}
925
926/// 表示 eval run 创建参数。
927#[derive(Debug, Clone, Serialize, Deserialize, Default)]
928pub struct EvalRunCreateParams {
929    /// 输入数据。
930    #[serde(skip_serializing_if = "Option::is_none")]
931    pub input: Option<EvalRunInput>,
932    /// 数据源。
933    #[serde(skip_serializing_if = "Option::is_none")]
934    pub data_source: Option<EvalDataSourceConfig>,
935    /// 自定义 metadata。
936    #[serde(default, skip_serializing_if = "metadata_is_empty")]
937    pub metadata: BTreeMap<String, String>,
938    /// 额外字段。
939    #[serde(flatten)]
940    pub extra: BTreeMap<String, Value>,
941}
942
943/// 表示 container 对象。
944#[derive(Debug, Clone, Serialize, Deserialize, Default)]
945pub struct Container {
946    /// Container ID。
947    pub id: String,
948    /// 对象类型。
949    #[serde(default)]
950    pub object: String,
951    /// 名称。
952    pub name: Option<String>,
953    /// 当前状态。
954    pub status: Option<String>,
955    /// 创建时间。
956    pub created_at: Option<u64>,
957    /// 自定义 metadata。
958    #[serde(default)]
959    pub metadata: BTreeMap<String, String>,
960    /// 额外字段。
961    #[serde(flatten)]
962    pub extra: BTreeMap<String, Value>,
963}
964
965/// 表示 container file 对象。
966#[derive(Debug, Clone, Serialize, Deserialize, Default)]
967pub struct ContainerFile {
968    /// Container file ID。
969    pub id: String,
970    /// 对象类型。
971    #[serde(default)]
972    pub object: String,
973    /// Container ID。
974    pub container_id: Option<String>,
975    /// 底层文件 ID。
976    pub file_id: Option<String>,
977    /// 文件名。
978    pub filename: Option<String>,
979    /// 当前状态。
980    pub status: Option<String>,
981    /// 自定义 metadata。
982    #[serde(default)]
983    pub metadata: BTreeMap<String, String>,
984    /// 额外字段。
985    #[serde(flatten)]
986    pub extra: BTreeMap<String, Value>,
987}
988
989/// 表示 container 创建参数。
990#[derive(Debug, Clone, Serialize, Deserialize, Default)]
991pub struct ContainerCreateParams {
992    /// 名称。
993    #[serde(skip_serializing_if = "Option::is_none")]
994    pub name: Option<String>,
995    /// 过期策略。
996    #[serde(skip_serializing_if = "Option::is_none")]
997    pub expires_after: Option<ContainerExpiresAfter>,
998    /// 自定义 metadata。
999    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1000    pub metadata: BTreeMap<String, String>,
1001    /// 额外字段。
1002    #[serde(flatten)]
1003    pub extra: BTreeMap<String, Value>,
1004}
1005
1006/// 表示 container file 创建参数。
1007#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1008pub struct ContainerFileCreateParams {
1009    /// 关联文件 ID。
1010    #[serde(skip_serializing_if = "Option::is_none")]
1011    pub file_id: Option<String>,
1012    /// 目标路径。
1013    #[serde(skip_serializing_if = "Option::is_none")]
1014    pub path: Option<String>,
1015    /// 自定义 metadata。
1016    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1017    pub metadata: BTreeMap<String, String>,
1018    /// 额外字段。
1019    #[serde(flatten)]
1020    pub extra: BTreeMap<String, Value>,
1021}
1022
1023/// 表示 skill 对象。
1024#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1025pub struct Skill {
1026    /// Skill ID。
1027    pub id: String,
1028    /// 对象类型。
1029    #[serde(default)]
1030    pub object: String,
1031    /// 名称。
1032    pub name: Option<String>,
1033    /// 描述。
1034    pub description: Option<String>,
1035    /// 绑定模型。
1036    pub model: Option<String>,
1037    /// 当前状态。
1038    pub status: Option<String>,
1039    /// 自定义 metadata。
1040    #[serde(default)]
1041    pub metadata: BTreeMap<String, String>,
1042    /// 额外字段。
1043    #[serde(flatten)]
1044    pub extra: BTreeMap<String, Value>,
1045}
1046
1047/// 表示 skill version 对象。
1048#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1049pub struct SkillVersion {
1050    /// Version ID。
1051    pub id: String,
1052    /// 对象类型。
1053    #[serde(default)]
1054    pub object: String,
1055    /// Skill ID。
1056    pub skill_id: Option<String>,
1057    /// 当前状态。
1058    pub status: Option<String>,
1059    /// 自定义 metadata。
1060    #[serde(default)]
1061    pub metadata: BTreeMap<String, String>,
1062    /// 额外字段。
1063    #[serde(flatten)]
1064    pub extra: BTreeMap<String, Value>,
1065}
1066
1067/// 表示 skill 创建参数。
1068#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1069pub struct SkillCreateParams {
1070    /// 名称。
1071    #[serde(skip_serializing_if = "Option::is_none")]
1072    pub name: Option<String>,
1073    /// 描述。
1074    #[serde(skip_serializing_if = "Option::is_none")]
1075    pub description: Option<String>,
1076    /// 绑定模型。
1077    #[serde(skip_serializing_if = "Option::is_none")]
1078    pub model: Option<String>,
1079    /// 指令。
1080    #[serde(skip_serializing_if = "Option::is_none")]
1081    pub instructions: Option<String>,
1082    /// 自定义 metadata。
1083    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1084    pub metadata: BTreeMap<String, String>,
1085    /// 额外字段。
1086    #[serde(flatten)]
1087    pub extra: BTreeMap<String, Value>,
1088}
1089
1090/// 表示 skill 更新参数。
1091#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1092pub struct SkillUpdateParams {
1093    /// 名称。
1094    #[serde(skip_serializing_if = "Option::is_none")]
1095    pub name: Option<String>,
1096    /// 描述。
1097    #[serde(skip_serializing_if = "Option::is_none")]
1098    pub description: Option<String>,
1099    /// 绑定模型。
1100    #[serde(skip_serializing_if = "Option::is_none")]
1101    pub model: Option<String>,
1102    /// 指令。
1103    #[serde(skip_serializing_if = "Option::is_none")]
1104    pub instructions: Option<String>,
1105    /// 自定义 metadata。
1106    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1107    pub metadata: BTreeMap<String, String>,
1108    /// 额外字段。
1109    #[serde(flatten)]
1110    pub extra: BTreeMap<String, Value>,
1111}
1112
1113/// 表示 skill version 创建参数。
1114#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1115pub struct SkillVersionCreateParams {
1116    /// 描述。
1117    #[serde(skip_serializing_if = "Option::is_none")]
1118    pub description: Option<String>,
1119    /// 版本内容。
1120    #[serde(skip_serializing_if = "Option::is_none")]
1121    pub content: Option<SkillVersionContent>,
1122    /// 自定义 metadata。
1123    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1124    pub metadata: BTreeMap<String, String>,
1125    /// 额外字段。
1126    #[serde(flatten)]
1127    pub extra: BTreeMap<String, Value>,
1128}
1129
1130/// 表示 video 对象。
1131#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1132pub struct Video {
1133    /// Video ID。
1134    pub id: String,
1135    /// 对象类型。
1136    #[serde(default)]
1137    pub object: String,
1138    /// 模型 ID。
1139    pub model: Option<String>,
1140    /// Prompt。
1141    pub prompt: Option<String>,
1142    /// 当前状态。
1143    pub status: Option<String>,
1144    /// 创建时间。
1145    pub created_at: Option<u64>,
1146    /// 自定义 metadata。
1147    #[serde(default)]
1148    pub metadata: BTreeMap<String, String>,
1149    /// 额外字段。
1150    #[serde(flatten)]
1151    pub extra: BTreeMap<String, Value>,
1152}
1153
1154/// 表示 video character 对象。
1155#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1156pub struct VideoCharacter {
1157    /// Character ID。
1158    pub id: String,
1159    /// 对象类型。
1160    #[serde(default)]
1161    pub object: String,
1162    /// 名称。
1163    pub name: Option<String>,
1164    /// 当前状态。
1165    pub status: Option<String>,
1166    /// 自定义 metadata。
1167    #[serde(default)]
1168    pub metadata: BTreeMap<String, String>,
1169    /// 额外字段。
1170    #[serde(flatten)]
1171    pub extra: BTreeMap<String, Value>,
1172}
1173
1174/// 表示 video 创建参数。
1175#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1176pub struct VideoCreateParams {
1177    /// 模型 ID。
1178    #[serde(skip_serializing_if = "Option::is_none")]
1179    pub model: Option<String>,
1180    /// Prompt。
1181    #[serde(skip_serializing_if = "Option::is_none")]
1182    pub prompt: Option<String>,
1183    /// 参考图片。
1184    #[serde(skip_serializing_if = "Option::is_none")]
1185    pub image: Option<String>,
1186    /// 目标尺寸。
1187    #[serde(skip_serializing_if = "Option::is_none")]
1188    pub size: Option<String>,
1189    /// 时长。
1190    #[serde(skip_serializing_if = "Option::is_none")]
1191    pub duration: Option<String>,
1192    /// 自定义 metadata。
1193    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1194    pub metadata: BTreeMap<String, String>,
1195    /// 额外字段。
1196    #[serde(flatten)]
1197    pub extra: BTreeMap<String, Value>,
1198}
1199
1200/// 表示 video character 创建参数。
1201#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1202pub struct VideoCharacterCreateParams {
1203    /// 名称。
1204    #[serde(skip_serializing_if = "Option::is_none")]
1205    pub name: Option<String>,
1206    /// 角色图片。
1207    #[serde(skip_serializing_if = "Option::is_none")]
1208    pub image: Option<String>,
1209    /// 自定义 metadata。
1210    #[serde(default, skip_serializing_if = "metadata_is_empty")]
1211    pub metadata: BTreeMap<String, String>,
1212    /// 额外字段。
1213    #[serde(flatten)]
1214    pub extra: BTreeMap<String, Value>,
1215}
1216
1217/// 表示图像生成请求构建器。
1218#[derive(Debug, Clone)]
1219pub struct ImageGenerateRequestBuilder {
1220    state: TypedJsonRequestState<ImageGenerateParams>,
1221}
1222
1223impl ImageGenerateRequestBuilder {
1224    pub(crate) fn new(client: Client) -> Self {
1225        Self {
1226            state: TypedJsonRequestState::new(client, ImageGenerateParams::default()),
1227        }
1228    }
1229
1230    pub fn model(mut self, model: impl Into<String>) -> Self {
1231        self.state.params.model = Some(model.into());
1232        self
1233    }
1234
1235    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
1236        self.state.params.prompt = Some(prompt.into());
1237        self
1238    }
1239
1240    pub fn n(mut self, n: u32) -> Self {
1241        self.state.params.n = Some(n);
1242        self
1243    }
1244
1245    pub fn size(mut self, size: impl Into<String>) -> Self {
1246        self.state.params.size = Some(size.into());
1247        self
1248    }
1249
1250    pub fn quality(mut self, quality: impl Into<String>) -> Self {
1251        self.state.params.quality = Some(quality.into());
1252        self
1253    }
1254
1255    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
1256        self.state.params.response_format = Some(response_format.into());
1257        self
1258    }
1259
1260    pub fn background(mut self, background: impl Into<String>) -> Self {
1261        self.state.params.background = Some(background.into());
1262        self
1263    }
1264
1265    pub fn output_format(mut self, output_format: impl Into<String>) -> Self {
1266        self.state.params.output_format = Some(output_format.into());
1267        self
1268    }
1269
1270    pub fn moderation(mut self, moderation: impl Into<String>) -> Self {
1271        self.state.params.moderation = Some(moderation.into());
1272        self
1273    }
1274
1275    pub fn partial_images(mut self, partial_images: u32) -> Self {
1276        self.state.params.partial_images = Some(partial_images);
1277        self
1278    }
1279
1280    pub fn stream(mut self, stream: bool) -> Self {
1281        self.state.params.stream = Some(stream);
1282        self
1283    }
1284
1285    pub fn user(mut self, user: impl Into<String>) -> Self {
1286        self.state.params.user = Some(user.into());
1287        self
1288    }
1289
1290    pub fn metadata(mut self, metadata: BTreeMap<String, String>) -> Self {
1291        self.state.params.metadata = metadata;
1292        self
1293    }
1294
1295    pub fn params(mut self, params: ImageGenerateParams) -> Self {
1296        self.state.params = params;
1297        self
1298    }
1299
1300    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
1301        self.state = self.state.body_value(body);
1302        self
1303    }
1304
1305    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
1306    where
1307        U: Serialize,
1308    {
1309        self.state = self.state.body_value(value_from(body)?);
1310        Ok(self)
1311    }
1312
1313    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1314        self.state = self.state.extra_header(key, value);
1315        self
1316    }
1317
1318    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1319        self.state = self.state.extra_query(key, value);
1320        self
1321    }
1322
1323    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
1324        self.state = self.state.extra_body(key, value);
1325        self
1326    }
1327
1328    pub fn provider_option(
1329        mut self,
1330        key: impl Into<String>,
1331        value: impl Into<JsonPayload>,
1332    ) -> Self {
1333        self.state = self.state.provider_option(key, value);
1334        self
1335    }
1336
1337    pub fn timeout(mut self, timeout: Duration) -> Self {
1338        self.state = self.state.timeout(timeout);
1339        self
1340    }
1341
1342    pub fn max_retries(mut self, max_retries: u32) -> Self {
1343        self.state = self.state.max_retries(max_retries);
1344        self
1345    }
1346
1347    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1348        self.state = self.state.cancellation_token(token);
1349        self
1350    }
1351
1352    fn build_spec(self) -> Result<(Client, RequestSpec)> {
1353        if self.state.body_override.is_none() {
1354            if self
1355                .state
1356                .params
1357                .model
1358                .as_deref()
1359                .unwrap_or_default()
1360                .is_empty()
1361            {
1362                return Err(Error::MissingRequiredField { field: "model" });
1363            }
1364            if self
1365                .state
1366                .params
1367                .prompt
1368                .as_deref()
1369                .unwrap_or_default()
1370                .is_empty()
1371            {
1372                return Err(Error::MissingRequiredField { field: "prompt" });
1373            }
1374        }
1375        self.state
1376            .build_spec("images.generate", "/images/generations")
1377    }
1378
1379    pub async fn send(self) -> Result<ImageGenerationResponse> {
1380        Ok(self.send_with_meta().await?.data)
1381    }
1382
1383    pub async fn send_with_meta(self) -> Result<ApiResponse<ImageGenerationResponse>> {
1384        let (client, spec) = self.build_spec()?;
1385        client.execute_json(spec).await
1386    }
1387
1388    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
1389        let (client, spec) = self.build_spec()?;
1390        client.execute_raw_http(spec).await
1391    }
1392
1393    pub async fn send_sse(mut self) -> Result<SseStream<Value>> {
1394        self.state.params.stream = Some(true);
1395        let (client, mut spec) = self.build_spec()?;
1396        spec.options.insert_header("accept", "text/event-stream");
1397        client.execute_sse(spec).await
1398    }
1399
1400    pub async fn send_raw_sse(mut self) -> Result<RawSseStream> {
1401        self.state.params.stream = Some(true);
1402        let (client, mut spec) = self.build_spec()?;
1403        spec.options.insert_header("accept", "text/event-stream");
1404        client.execute_raw_sse(spec).await
1405    }
1406}
1407
1408/// 表示语音合成请求构建器。
1409#[derive(Debug, Clone)]
1410pub struct AudioSpeechRequestBuilder {
1411    inner: BytesRequestBuilder,
1412}
1413
1414impl AudioSpeechRequestBuilder {
1415    pub(crate) fn new(client: Client) -> Self {
1416        Self {
1417            inner: BytesRequestBuilder::new(
1418                client,
1419                "audio.speech.create",
1420                Method::POST,
1421                "/audio/speech",
1422            ),
1423        }
1424    }
1425
1426    pub(crate) fn stream(client: Client) -> Self {
1427        Self::new(client).extra_body("stream_format", Value::String("sse".into()))
1428    }
1429
1430    pub fn model(mut self, model: impl Into<String>) -> Self {
1431        self.inner = self.inner.extra_body("model", Value::String(model.into()));
1432        self
1433    }
1434
1435    pub fn voice(mut self, voice: impl Into<String>) -> Self {
1436        self.inner = self.inner.extra_body("voice", Value::String(voice.into()));
1437        self
1438    }
1439
1440    pub fn input(mut self, input: impl Into<String>) -> Self {
1441        self.inner = self.inner.extra_body("input", Value::String(input.into()));
1442        self
1443    }
1444
1445    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
1446        self.inner = self
1447            .inner
1448            .extra_body("instructions", Value::String(instructions.into()));
1449        self
1450    }
1451
1452    pub fn audio_format(mut self, format: impl Into<String>) -> Self {
1453        self.inner = self
1454            .inner
1455            .extra_body("format", Value::String(format.into()));
1456        self
1457    }
1458
1459    pub fn speed(mut self, speed: f32) -> Self {
1460        self.inner = self.inner.extra_body("speed", Value::from(speed));
1461        self
1462    }
1463
1464    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
1465        self.inner = self.inner.body_value(body);
1466        self
1467    }
1468
1469    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
1470    where
1471        U: Serialize,
1472    {
1473        self.inner = self.inner.json_body(body)?;
1474        Ok(self)
1475    }
1476
1477    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1478        self.inner = self.inner.extra_header(key, value);
1479        self
1480    }
1481
1482    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1483        self.inner = self.inner.extra_query(key, value);
1484        self
1485    }
1486
1487    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
1488        self.inner = self.inner.extra_body(key, value);
1489        self
1490    }
1491
1492    pub fn provider_option(
1493        mut self,
1494        key: impl Into<String>,
1495        value: impl Into<JsonPayload>,
1496    ) -> Self {
1497        self.inner = self.inner.provider_option(key, value);
1498        self
1499    }
1500
1501    pub fn timeout(mut self, timeout: Duration) -> Self {
1502        self.inner = self.inner.timeout(timeout);
1503        self
1504    }
1505
1506    pub fn max_retries(mut self, max_retries: u32) -> Self {
1507        self.inner = self.inner.max_retries(max_retries);
1508        self
1509    }
1510
1511    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1512        self.inner = self.inner.cancellation_token(token);
1513        self
1514    }
1515
1516    pub async fn send(self) -> Result<Bytes> {
1517        self.inner.send().await
1518    }
1519
1520    pub async fn send_with_meta(self) -> Result<ApiResponse<Bytes>> {
1521        self.inner.send_with_meta().await
1522    }
1523
1524    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
1525        self.inner.send_raw().await
1526    }
1527
1528    pub async fn send_raw_sse(self) -> Result<RawSseStream> {
1529        self.inner.send_raw_sse().await
1530    }
1531
1532    pub async fn send_sse(self) -> Result<SseStream<Value>> {
1533        self.inner.send_sse().await
1534    }
1535}
1536
1537/// 表示音频转写请求构建器。
1538#[derive(Debug, Clone)]
1539pub struct AudioTranscriptionRequestBuilder {
1540    inner: JsonRequestBuilder<AudioTranscription>,
1541}
1542
1543impl AudioTranscriptionRequestBuilder {
1544    pub(crate) fn new(client: Client, stream: bool) -> Self {
1545        let inner = JsonRequestBuilder::new(
1546            client,
1547            "audio.transcriptions.create",
1548            Method::POST,
1549            "/audio/transcriptions",
1550        );
1551        Self {
1552            inner: if stream {
1553                inner.extra_body("stream", Value::Bool(true))
1554            } else {
1555                inner
1556            },
1557        }
1558    }
1559
1560    pub fn model(mut self, model: impl Into<String>) -> Self {
1561        self.inner = self.inner.multipart_text("model", model);
1562        self
1563    }
1564
1565    pub fn file(mut self, file: UploadSource) -> Self {
1566        self.inner = self.inner.multipart_file("file", file);
1567        self
1568    }
1569
1570    pub fn language(mut self, language: impl Into<String>) -> Self {
1571        self.inner = self.inner.multipart_text("language", language);
1572        self
1573    }
1574
1575    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
1576        self.inner = self.inner.multipart_text("prompt", prompt);
1577        self
1578    }
1579
1580    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
1581        self.inner = self
1582            .inner
1583            .multipart_text("response_format", response_format);
1584        self
1585    }
1586
1587    pub fn temperature(mut self, temperature: f32) -> Self {
1588        self.inner = self
1589            .inner
1590            .multipart_text("temperature", temperature.to_string());
1591        self
1592    }
1593
1594    pub fn timestamp_granularity(mut self, granularity: impl Into<String>) -> Self {
1595        self.inner = self
1596            .inner
1597            .multipart_text("timestamp_granularities[]", granularity);
1598        self
1599    }
1600
1601    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
1602        self.inner = self.inner.body_value(body);
1603        self
1604    }
1605
1606    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
1607    where
1608        U: Serialize,
1609    {
1610        self.inner = self.inner.json_body(body)?;
1611        Ok(self)
1612    }
1613
1614    pub fn multipart_text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1615        self.inner = self.inner.multipart_text(name, value);
1616        self
1617    }
1618
1619    pub fn multipart_file(mut self, name: impl Into<String>, file: UploadSource) -> Self {
1620        self.inner = self.inner.multipart_file(name, file);
1621        self
1622    }
1623
1624    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1625        self.inner = self.inner.extra_header(key, value);
1626        self
1627    }
1628
1629    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1630        self.inner = self.inner.extra_query(key, value);
1631        self
1632    }
1633
1634    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
1635        self.inner = self.inner.extra_body(key, value);
1636        self
1637    }
1638
1639    pub fn provider_option(
1640        mut self,
1641        key: impl Into<String>,
1642        value: impl Into<JsonPayload>,
1643    ) -> Self {
1644        self.inner = self.inner.provider_option(key, value);
1645        self
1646    }
1647
1648    pub fn timeout(mut self, timeout: Duration) -> Self {
1649        self.inner = self.inner.timeout(timeout);
1650        self
1651    }
1652
1653    pub fn max_retries(mut self, max_retries: u32) -> Self {
1654        self.inner = self.inner.max_retries(max_retries);
1655        self
1656    }
1657
1658    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1659        self.inner = self.inner.cancellation_token(token);
1660        self
1661    }
1662
1663    pub async fn send(self) -> Result<AudioTranscription> {
1664        self.inner.send().await
1665    }
1666
1667    pub async fn send_with_meta(self) -> Result<ApiResponse<AudioTranscription>> {
1668        self.inner.send_with_meta().await
1669    }
1670
1671    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
1672        self.inner.send_raw().await
1673    }
1674
1675    pub async fn send_raw_sse(self) -> Result<RawSseStream> {
1676        let client = self.inner.client.clone();
1677        let mut spec = self.inner.into_spec();
1678        spec.options.insert_header("accept", "text/event-stream");
1679        client.execute_raw_sse(spec).await
1680    }
1681
1682    pub async fn send_sse(self) -> Result<SseStream<Value>> {
1683        let client = self.inner.client.clone();
1684        let mut spec = self.inner.into_spec();
1685        spec.options.insert_header("accept", "text/event-stream");
1686        client.execute_sse(spec).await
1687    }
1688}
1689
1690/// 表示音频翻译请求构建器。
1691#[derive(Debug, Clone)]
1692pub struct AudioTranslationRequestBuilder {
1693    inner: JsonRequestBuilder<AudioTranslation>,
1694}
1695
1696impl AudioTranslationRequestBuilder {
1697    pub(crate) fn new(client: Client) -> Self {
1698        Self {
1699            inner: JsonRequestBuilder::new(
1700                client,
1701                "audio.translations.create",
1702                Method::POST,
1703                "/audio/translations",
1704            ),
1705        }
1706    }
1707
1708    pub fn model(mut self, model: impl Into<String>) -> Self {
1709        self.inner = self.inner.multipart_text("model", model);
1710        self
1711    }
1712
1713    pub fn file(mut self, file: UploadSource) -> Self {
1714        self.inner = self.inner.multipart_file("file", file);
1715        self
1716    }
1717
1718    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
1719        self.inner = self.inner.multipart_text("prompt", prompt);
1720        self
1721    }
1722
1723    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
1724        self.inner = self
1725            .inner
1726            .multipart_text("response_format", response_format);
1727        self
1728    }
1729
1730    pub fn temperature(mut self, temperature: f32) -> Self {
1731        self.inner = self
1732            .inner
1733            .multipart_text("temperature", temperature.to_string());
1734        self
1735    }
1736
1737    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
1738        self.inner = self.inner.body_value(body);
1739        self
1740    }
1741
1742    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
1743    where
1744        U: Serialize,
1745    {
1746        self.inner = self.inner.json_body(body)?;
1747        Ok(self)
1748    }
1749
1750    pub fn multipart_text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1751        self.inner = self.inner.multipart_text(name, value);
1752        self
1753    }
1754
1755    pub fn multipart_file(mut self, name: impl Into<String>, file: UploadSource) -> Self {
1756        self.inner = self.inner.multipart_file(name, file);
1757        self
1758    }
1759
1760    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1761        self.inner = self.inner.extra_header(key, value);
1762        self
1763    }
1764
1765    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1766        self.inner = self.inner.extra_query(key, value);
1767        self
1768    }
1769
1770    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
1771        self.inner = self.inner.extra_body(key, value);
1772        self
1773    }
1774
1775    pub fn provider_option(
1776        mut self,
1777        key: impl Into<String>,
1778        value: impl Into<JsonPayload>,
1779    ) -> Self {
1780        self.inner = self.inner.provider_option(key, value);
1781        self
1782    }
1783
1784    pub fn timeout(mut self, timeout: Duration) -> Self {
1785        self.inner = self.inner.timeout(timeout);
1786        self
1787    }
1788
1789    pub fn max_retries(mut self, max_retries: u32) -> Self {
1790        self.inner = self.inner.max_retries(max_retries);
1791        self
1792    }
1793
1794    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1795        self.inner = self.inner.cancellation_token(token);
1796        self
1797    }
1798
1799    pub async fn send(self) -> Result<AudioTranslation> {
1800        self.inner.send().await
1801    }
1802
1803    pub async fn send_with_meta(self) -> Result<ApiResponse<AudioTranslation>> {
1804        self.inner.send_with_meta().await
1805    }
1806
1807    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
1808        self.inner.send_raw().await
1809    }
1810}
1811
1812/// 表示 fine-tuning job 创建构建器。
1813#[derive(Debug, Clone)]
1814pub struct FineTuningJobCreateRequestBuilder {
1815    state: TypedJsonRequestState<FineTuningJobCreateParams>,
1816}
1817
1818impl FineTuningJobCreateRequestBuilder {
1819    pub(crate) fn new(client: Client) -> Self {
1820        Self {
1821            state: TypedJsonRequestState::new(client, FineTuningJobCreateParams::default()),
1822        }
1823    }
1824
1825    pub fn model(mut self, model: impl Into<String>) -> Self {
1826        self.state.params.model = Some(model.into());
1827        self
1828    }
1829
1830    pub fn training_file(mut self, training_file: impl Into<String>) -> Self {
1831        self.state.params.training_file = Some(training_file.into());
1832        self
1833    }
1834
1835    pub fn validation_file(mut self, validation_file: impl Into<String>) -> Self {
1836        self.state.params.validation_file = Some(validation_file.into());
1837        self
1838    }
1839
1840    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
1841        self.state.params.suffix = Some(suffix.into());
1842        self
1843    }
1844
1845    pub fn seed(mut self, seed: u64) -> Self {
1846        self.state.params.seed = Some(seed);
1847        self
1848    }
1849
1850    pub fn hyperparameters(
1851        mut self,
1852        hyperparameters: impl Into<FineTuningJobHyperparameters>,
1853    ) -> Self {
1854        self.state.params.hyperparameters = Some(hyperparameters.into());
1855        self
1856    }
1857
1858    pub fn integration(mut self, integration: impl Into<FineTuningJobIntegration>) -> Self {
1859        self.state.params.integrations.push(integration.into());
1860        self
1861    }
1862
1863    pub fn metadata(mut self, metadata: BTreeMap<String, String>) -> Self {
1864        self.state.params.metadata = metadata;
1865        self
1866    }
1867
1868    pub fn params(mut self, params: FineTuningJobCreateParams) -> Self {
1869        self.state.params = params;
1870        self
1871    }
1872
1873    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
1874        self.state = self.state.body_value(body);
1875        self
1876    }
1877
1878    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
1879    where
1880        U: Serialize,
1881    {
1882        self.state = self.state.body_value(value_from(body)?);
1883        Ok(self)
1884    }
1885
1886    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1887        self.state = self.state.extra_header(key, value);
1888        self
1889    }
1890
1891    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1892        self.state = self.state.extra_query(key, value);
1893        self
1894    }
1895
1896    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
1897        self.state = self.state.extra_body(key, value);
1898        self
1899    }
1900
1901    pub fn provider_option(
1902        mut self,
1903        key: impl Into<String>,
1904        value: impl Into<JsonPayload>,
1905    ) -> Self {
1906        self.state = self.state.provider_option(key, value);
1907        self
1908    }
1909
1910    pub fn timeout(mut self, timeout: Duration) -> Self {
1911        self.state = self.state.timeout(timeout);
1912        self
1913    }
1914
1915    pub fn max_retries(mut self, max_retries: u32) -> Self {
1916        self.state = self.state.max_retries(max_retries);
1917        self
1918    }
1919
1920    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1921        self.state = self.state.cancellation_token(token);
1922        self
1923    }
1924
1925    fn build_spec(self) -> Result<(Client, RequestSpec)> {
1926        if self.state.body_override.is_none() {
1927            if self
1928                .state
1929                .params
1930                .model
1931                .as_deref()
1932                .unwrap_or_default()
1933                .is_empty()
1934            {
1935                return Err(Error::MissingRequiredField { field: "model" });
1936            }
1937            if self
1938                .state
1939                .params
1940                .training_file
1941                .as_deref()
1942                .unwrap_or_default()
1943                .is_empty()
1944            {
1945                return Err(Error::MissingRequiredField {
1946                    field: "training_file",
1947                });
1948            }
1949        }
1950        self.state
1951            .build_spec("fine_tuning.jobs.create", "/fine_tuning/jobs")
1952    }
1953
1954    pub async fn send(self) -> Result<FineTuningJob> {
1955        Ok(self.send_with_meta().await?.data)
1956    }
1957
1958    pub async fn send_with_meta(self) -> Result<ApiResponse<FineTuningJob>> {
1959        let (client, spec) = self.build_spec()?;
1960        client.execute_json(spec).await
1961    }
1962
1963    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
1964        let (client, spec) = self.build_spec()?;
1965        client.execute_raw_http(spec).await
1966    }
1967}
1968
1969/// 表示 batch 创建构建器。
1970#[derive(Debug, Clone)]
1971pub struct BatchCreateRequestBuilder {
1972    state: TypedJsonRequestState<BatchCreateParams>,
1973}
1974
1975impl BatchCreateRequestBuilder {
1976    pub(crate) fn new(client: Client) -> Self {
1977        Self {
1978            state: TypedJsonRequestState::new(client, BatchCreateParams::default()),
1979        }
1980    }
1981
1982    pub fn input_file_id(mut self, input_file_id: impl Into<String>) -> Self {
1983        self.state.params.input_file_id = Some(input_file_id.into());
1984        self
1985    }
1986
1987    pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
1988        self.state.params.endpoint = Some(endpoint.into());
1989        self
1990    }
1991
1992    pub fn completion_window(mut self, completion_window: impl Into<String>) -> Self {
1993        self.state.params.completion_window = Some(completion_window.into());
1994        self
1995    }
1996
1997    pub fn metadata(mut self, metadata: BTreeMap<String, String>) -> Self {
1998        self.state.params.metadata = metadata;
1999        self
2000    }
2001
2002    pub fn params(mut self, params: BatchCreateParams) -> Self {
2003        self.state.params = params;
2004        self
2005    }
2006
2007    pub fn body_value(mut self, body: impl Into<JsonPayload>) -> Self {
2008        self.state = self.state.body_value(body);
2009        self
2010    }
2011
2012    pub fn json_body<U>(mut self, body: &U) -> Result<Self>
2013    where
2014        U: Serialize,
2015    {
2016        self.state = self.state.body_value(value_from(body)?);
2017        Ok(self)
2018    }
2019
2020    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
2021        self.state = self.state.extra_header(key, value);
2022        self
2023    }
2024
2025    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
2026        self.state = self.state.extra_query(key, value);
2027        self
2028    }
2029
2030    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
2031        self.state = self.state.extra_body(key, value);
2032        self
2033    }
2034
2035    pub fn provider_option(
2036        mut self,
2037        key: impl Into<String>,
2038        value: impl Into<JsonPayload>,
2039    ) -> Self {
2040        self.state = self.state.provider_option(key, value);
2041        self
2042    }
2043
2044    pub fn timeout(mut self, timeout: Duration) -> Self {
2045        self.state = self.state.timeout(timeout);
2046        self
2047    }
2048
2049    pub fn max_retries(mut self, max_retries: u32) -> Self {
2050        self.state = self.state.max_retries(max_retries);
2051        self
2052    }
2053
2054    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
2055        self.state = self.state.cancellation_token(token);
2056        self
2057    }
2058
2059    fn build_spec(self) -> Result<(Client, RequestSpec)> {
2060        if self.state.body_override.is_none() {
2061            if self
2062                .state
2063                .params
2064                .input_file_id
2065                .as_deref()
2066                .unwrap_or_default()
2067                .is_empty()
2068            {
2069                return Err(Error::MissingRequiredField {
2070                    field: "input_file_id",
2071                });
2072            }
2073            if self
2074                .state
2075                .params
2076                .endpoint
2077                .as_deref()
2078                .unwrap_or_default()
2079                .is_empty()
2080            {
2081                return Err(Error::MissingRequiredField { field: "endpoint" });
2082            }
2083            if self
2084                .state
2085                .params
2086                .completion_window
2087                .as_deref()
2088                .unwrap_or_default()
2089                .is_empty()
2090            {
2091                return Err(Error::MissingRequiredField {
2092                    field: "completion_window",
2093                });
2094            }
2095        }
2096        let endpoint = endpoints::batches::BATCHES_CREATE;
2097        self.state.build_spec(endpoint.id, endpoint.template)
2098    }
2099
2100    pub async fn send(self) -> Result<Batch> {
2101        Ok(self.send_with_meta().await?.data)
2102    }
2103
2104    pub async fn send_with_meta(self) -> Result<ApiResponse<Batch>> {
2105        let (client, spec) = self.build_spec()?;
2106        client.execute_json(spec).await
2107    }
2108
2109    pub async fn send_raw(self) -> Result<http::Response<Bytes>> {
2110        let (client, spec) = self.build_spec()?;
2111        client.execute_raw_http(spec).await
2112    }
2113}