Skip to main content

openai_core/resources/
mod.rs

1//! 资源命名空间、公开类型与请求构建器。
2
3mod audio;
4mod batches;
5mod beta;
6mod chat;
7mod common;
8mod containers;
9mod conversations;
10mod core;
11mod evals;
12mod files;
13mod fine_tuning;
14mod images;
15mod longtail;
16mod responses;
17mod skills;
18mod uploads;
19mod vector_stores;
20mod videos;
21mod webhooks;
22
23use std::collections::BTreeMap;
24
25use serde::{Deserialize, Serialize};
26use serde_json::Value;
27
28use crate::Client;
29use crate::error::{Error, Result};
30#[cfg(feature = "tool-runner")]
31use crate::helpers::ToolDefinition;
32use crate::json_payload::JsonPayload;
33
34pub use beta::{
35    BetaAssistant, BetaAssistantTool, BetaRealtimeSession, BetaRealtimeTranscriptionSession,
36    BetaThread, BetaThreadMessage, BetaThreadMessageContent, BetaThreadRun,
37    BetaThreadRunIncompleteDetails, BetaThreadRunLastError, BetaThreadRunRequiredAction,
38    BetaThreadRunRequiredActionFunction, BetaThreadRunRequiredActionFunctionToolCall,
39    BetaThreadRunRequiredActionSubmitToolOutputs, BetaThreadRunStep, BetaThreadRunStepDetails,
40    BetaThreadRunTool, BetaThreadRunUsage, BetaThreadToolResources, ChatKitConfiguration,
41    ChatKitRateLimits, ChatKitSession, ChatKitThread, ChatKitThreadContent, ChatKitThreadItem,
42    ChatKitThreadStatus, ChatKitWorkflow,
43};
44#[cfg(feature = "structured-output")]
45pub use chat::ChatCompletionParseRequestBuilder;
46pub use chat::{
47    AssistantStreamRequestBuilder, ChatCompletionCreateRequestBuilder, ChatCompletionStoreMessage,
48    ChatCompletionStreamRequestBuilder,
49};
50#[cfg(feature = "tool-runner")]
51pub use chat::{
52    ChatCompletionRunToolsRequestBuilder, ChatCompletionRunner, ChatCompletionStreamingRunner,
53    ChatCompletionToolResult,
54};
55pub use common::{
56    BytesRequestBuilder, JsonRequestBuilder, ListRequestBuilder, NoContentRequestBuilder,
57};
58pub(crate) use common::{
59    TypedJsonRequestState, encode_path_segment, metadata_is_empty, value_from,
60};
61pub use core::{
62    Completion, CompletionChoice, CompletionLogProbs, CompletionUsage,
63    CompletionUsageCompletionTokensDetails, CompletionUsagePromptTokensDetails,
64    ModerationCreateResponse, ModerationResult,
65};
66pub use fine_tuning::{
67    GraderModel, GraderModelCatalog, GraderRunErrors, GraderRunMetadata, GraderRunResponse,
68    GraderValidateResponse,
69};
70pub use longtail::{
71    AudioSpeechCreateParams, AudioSpeechRequestBuilder, AudioTranscription,
72    AudioTranscriptionRequestBuilder, AudioTranscriptionSegment, AudioTranscriptionSegmentId,
73    AudioTranscriptionWord, AudioTranslation, AudioTranslationRequestBuilder, Batch,
74    BatchCreateParams, BatchCreateRequestBuilder, BatchError, BatchErrors, BatchRequestCounts,
75    BatchUsage, BatchUsageInputTokensDetails, BatchUsageOutputTokensDetails, Container,
76    ContainerCreateParams, ContainerExpiresAfter, ContainerFile, ContainerFileCreateParams,
77    Conversation, ConversationContentPart, ConversationCreateParams, ConversationInputItem,
78    ConversationItem, ConversationItemCreateParams, ConversationUpdateParams, Eval,
79    EvalCreateParams, EvalDataSourceConfig, EvalOutput, EvalOutputItem, EvalRun,
80    EvalRunCreateParams, EvalRunInput, EvalTestingCriterion, EvalUpdateParams,
81    FineTuningCheckpoint, FineTuningCheckpointPermission, FineTuningHyperparameterValue,
82    FineTuningJob, FineTuningJobCreateParams, FineTuningJobCreateRequestBuilder,
83    FineTuningJobError, FineTuningJobEvent, FineTuningJobHyperparameters, FineTuningJobIntegration,
84    FineTuningMetrics, FineTuningWandbIntegration, ImageData, ImageGenerateParams,
85    ImageGenerateRequestBuilder, ImageGenerationResponse, Skill, SkillCreateParams,
86    SkillUpdateParams, SkillVersion, SkillVersionContent, SkillVersionCreateParams, Video,
87    VideoCharacter, VideoCharacterCreateParams, VideoCreateParams,
88};
89#[cfg(feature = "realtime")]
90pub use responses::RealtimeSocketRequestBuilder;
91#[cfg(feature = "structured-output")]
92pub use responses::ResponseParseRequestBuilder;
93#[cfg(feature = "responses-ws")]
94pub use responses::ResponsesSocketRequestBuilder;
95pub use responses::{
96    RealtimeClientSecretCreateResponse, RealtimeSessionClientSecret, ResponseCreateRequestBuilder,
97    ResponseStreamRequestBuilder,
98};
99pub use uploads::UploadPart;
100pub use vector_stores::{
101    VectorStore, VectorStoreAttributeValue, VectorStoreAttributes, VectorStoreExpiresAfter,
102    VectorStoreFile, VectorStoreFileBatch, VectorStoreFileChunkingStrategy, VectorStoreFileContent,
103    VectorStoreFileCounts, VectorStoreFileLastError, VectorStoreMetadata, VectorStoreSearchContent,
104    VectorStoreSearchResponse, VectorStoreSearchResult, VectorStoreStaticFileChunkingStrategy,
105};
106
107macro_rules! json_payload_wrapper {
108    ($(#[$meta:meta])* $name:ident) => {
109        $(#[$meta])*
110        #[derive(Debug, Clone, Serialize, Deserialize)]
111        #[serde(transparent)]
112        pub struct $name(Value);
113
114        impl Default for $name {
115            fn default() -> Self {
116                Self(Value::Null)
117            }
118        }
119
120        impl From<Value> for $name {
121            fn from(value: Value) -> Self {
122                Self(value)
123            }
124        }
125
126        impl From<$name> for Value {
127            fn from(value: $name) -> Self {
128                value.0
129            }
130        }
131
132        impl $name {
133            /// 返回未经解释的原始 JSON 值。
134            pub fn as_raw(&self) -> &Value {
135                &self.0
136            }
137
138            /// 消费该包装器并返回原始 JSON 值。
139            pub fn into_raw(self) -> Value {
140                self.0
141            }
142
143            /// 返回载荷中的 `type` 字段,若存在且为字符串。
144            pub fn kind(&self) -> Option<&str> {
145                self.0.get("type").and_then(Value::as_str)
146            }
147        }
148    };
149}
150
151macro_rules! handle {
152    ($(#[$meta:meta])* $name:ident) => {
153        $(#[$meta])*
154        #[derive(Debug, Clone)]
155        pub struct $name {
156            client: Client,
157        }
158
159        impl $name {
160            pub(crate) fn new(client: Client) -> Self {
161                Self { client }
162            }
163        }
164    };
165}
166
167/// 表示常见的删除结果。
168#[derive(Debug, Clone, Serialize, Deserialize, Default)]
169pub struct DeleteResponse {
170    /// 被删除对象的 ID。
171    pub id: Option<String>,
172    /// 是否删除成功。
173    #[serde(default)]
174    pub deleted: bool,
175    /// 对象类型。
176    pub object: Option<String>,
177    /// 额外字段。
178    #[serde(flatten)]
179    pub extra: BTreeMap<String, Value>,
180}
181
182/// 表示模型对象。
183#[derive(Debug, Clone, Serialize, Deserialize, Default)]
184pub struct Model {
185    /// 模型 ID。
186    pub id: String,
187    /// 对象类型。
188    #[serde(default)]
189    pub object: String,
190    /// 模型所有者。
191    pub owned_by: Option<String>,
192    /// 额外字段。
193    #[serde(flatten)]
194    pub extra: BTreeMap<String, Value>,
195}
196
197/// 表示文件对象。
198#[derive(Debug, Clone, Serialize, Deserialize, Default)]
199pub struct FileObject {
200    /// 文件 ID。
201    pub id: String,
202    /// 对象类型。
203    #[serde(default)]
204    pub object: String,
205    /// 文件名。
206    pub filename: Option<String>,
207    /// 文件用途。
208    pub purpose: Option<String>,
209    /// 文件大小。
210    pub bytes: Option<u64>,
211    /// 额外字段。
212    #[serde(flatten)]
213    pub extra: BTreeMap<String, Value>,
214}
215
216/// 表示上传对象。
217#[derive(Debug, Clone, Serialize, Deserialize, Default)]
218pub struct UploadObject {
219    /// 上传 ID。
220    pub id: String,
221    /// 对象类型。
222    #[serde(default)]
223    pub object: String,
224    /// 上传状态。
225    pub status: Option<String>,
226    /// 额外字段。
227    #[serde(flatten)]
228    pub extra: BTreeMap<String, Value>,
229}
230
231/// 表示 Embeddings 接口的返回值。
232#[derive(Debug, Clone, Serialize, Deserialize, Default)]
233pub struct EmbeddingResponse {
234    /// 对象类型。
235    #[serde(default)]
236    pub object: String,
237    /// 向量数据。
238    #[serde(default)]
239    pub data: Vec<EmbeddingData>,
240    /// 使用统计。
241    pub usage: Option<EmbeddingUsage>,
242    /// 额外字段。
243    #[serde(flatten)]
244    pub extra: BTreeMap<String, Value>,
245}
246
247/// 表示单个 embedding 向量项。
248#[derive(Debug, Clone, Serialize, Deserialize, Default)]
249pub struct EmbeddingData {
250    /// embedding 向量。
251    #[serde(default)]
252    pub embedding: Vec<f64>,
253    /// 向量索引。
254    pub index: Option<u32>,
255    /// 对象类型。
256    #[serde(default)]
257    pub object: String,
258    /// 额外字段。
259    #[serde(flatten)]
260    pub extra: BTreeMap<String, Value>,
261}
262
263/// 表示 embeddings 的用量统计。
264#[derive(Debug, Clone, Serialize, Deserialize, Default)]
265pub struct EmbeddingUsage {
266    /// prompt token 数。
267    #[serde(default)]
268    pub prompt_tokens: u64,
269    /// 总 token 数。
270    #[serde(default)]
271    pub total_tokens: u64,
272    /// 额外字段。
273    #[serde(flatten)]
274    pub extra: BTreeMap<String, Value>,
275}
276
277/// 表示模型计数结果。
278#[derive(Debug, Clone, Serialize, Deserialize, Default)]
279pub struct InputTokenCount {
280    /// 总 token 数量。
281    pub total_tokens: u64,
282    /// 额外字段。
283    #[serde(flatten)]
284    pub extra: BTreeMap<String, Value>,
285}
286
287json_payload_wrapper!(
288    /// 表示已存储 chat completion 的 content part。
289    ChatCompletionStoreContentPart
290);
291json_payload_wrapper!(
292    /// 表示聊天消息中的 reasoning detail。
293    ChatReasoningDetail
294);
295json_payload_wrapper!(
296    /// 表示 chat 请求中的 tool_choice 载荷。
297    ChatToolChoice
298);
299json_payload_wrapper!(
300    /// 表示 responses 请求的输入载荷。
301    ResponseInputPayload
302);
303json_payload_wrapper!(
304    /// 表示 responses 请求中的单个输入项。
305    ResponseInputItemPayload
306);
307json_payload_wrapper!(
308    /// 表示 realtime client secret 返回中的 session 配置。
309    RealtimeSessionPayload
310);
311json_payload_wrapper!(
312    /// 表示 responses 输出中的未知原始输出项。
313    ResponseOutputItemRaw
314);
315json_payload_wrapper!(
316    /// 表示 responses message 中的未知原始内容片段。
317    ResponseOutputContentPartRaw
318);
319
320/// 表示 chat tool_choice 的字符串模式。
321#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
322#[serde(rename_all = "snake_case")]
323pub enum ChatToolChoiceMode {
324    /// 不允许工具调用。
325    None,
326    /// 允许模型自动选择。
327    Auto,
328    /// 要求模型必须调用工具。
329    Required,
330}
331
332impl From<ChatToolChoiceMode> for ChatToolChoice {
333    fn from(mode: ChatToolChoiceMode) -> Self {
334        let value = match mode {
335            ChatToolChoiceMode::None => Value::String("none".into()),
336            ChatToolChoiceMode::Auto => Value::String("auto".into()),
337            ChatToolChoiceMode::Required => Value::String("required".into()),
338        };
339        Self::from(value)
340    }
341}
342
343impl From<String> for ResponseInputPayload {
344    fn from(value: String) -> Self {
345        Self::from(Value::String(value))
346    }
347}
348
349impl From<&str> for ResponseInputPayload {
350    fn from(value: &str) -> Self {
351        Self::from(Value::String(value.into()))
352    }
353}
354
355impl From<Vec<ResponseInputItemPayload>> for ResponseInputPayload {
356    fn from(items: Vec<ResponseInputItemPayload>) -> Self {
357        Self::from(Value::Array(items.into_iter().map(Value::from).collect()))
358    }
359}
360
361impl ChatToolChoice {
362    /// 生成 `none` 模式。
363    pub fn none() -> Self {
364        ChatToolChoiceMode::None.into()
365    }
366
367    /// 生成 `auto` 模式。
368    pub fn auto() -> Self {
369        ChatToolChoiceMode::Auto.into()
370    }
371
372    /// 生成 `required` 模式。
373    pub fn required() -> Self {
374        ChatToolChoiceMode::Required.into()
375    }
376
377    /// 强制调用指定函数工具。
378    pub fn function(name: impl Into<String>) -> Self {
379        serde_json::json!({
380            "type": "function",
381            "function": {
382                "name": name.into(),
383            },
384        })
385        .into()
386    }
387
388    /// 强制调用指定自定义工具。
389    pub fn custom(name: impl Into<String>) -> Self {
390        serde_json::json!({
391            "type": "custom",
392            "custom": {
393                "name": name.into(),
394            },
395        })
396        .into()
397    }
398
399    /// 当 tool_choice 为字符串模式时返回该模式。
400    pub fn mode_name(&self) -> Option<&str> {
401        self.0.as_str()
402    }
403}
404
405/// 表示一个工具函数调用。
406#[derive(Debug, Clone, Serialize, Deserialize, Default)]
407pub struct ChatCompletionFunctionCall {
408    /// 工具名称。
409    pub name: String,
410    /// 参数 JSON 字符串。
411    #[serde(default)]
412    pub arguments: String,
413}
414
415/// 表示工具调用项。
416#[derive(Debug, Clone, Serialize, Deserialize, Default)]
417pub struct ChatCompletionToolCall {
418    /// 工具调用 ID。
419    pub id: String,
420    /// 调用类型。
421    #[serde(rename = "type", default = "default_function_type")]
422    pub call_type: String,
423    /// 函数调用内容。
424    pub function: ChatCompletionFunctionCall,
425    /// 额外字段。
426    #[serde(flatten)]
427    pub extra: BTreeMap<String, Value>,
428}
429
430/// 表示 token 的 top logprob。
431#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
432pub struct ChatCompletionTokenTopLogprob {
433    /// token 内容。
434    #[serde(default)]
435    pub token: String,
436    /// UTF-8 bytes。
437    pub bytes: Option<Vec<u8>>,
438    /// token 对应的 logprob。
439    #[serde(default)]
440    pub logprob: f64,
441    /// 额外字段。
442    #[serde(flatten)]
443    pub extra: BTreeMap<String, Value>,
444}
445
446/// 表示单个 token 的 logprob 信息。
447#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
448pub struct ChatCompletionTokenLogprob {
449    /// token 内容。
450    #[serde(default)]
451    pub token: String,
452    /// UTF-8 bytes。
453    pub bytes: Option<Vec<u8>>,
454    /// token 对应的 logprob。
455    #[serde(default)]
456    pub logprob: f64,
457    /// top logprobs。
458    #[serde(default)]
459    pub top_logprobs: Vec<ChatCompletionTokenTopLogprob>,
460    /// 额外字段。
461    #[serde(flatten)]
462    pub extra: BTreeMap<String, Value>,
463}
464
465/// 表示 chat completion choice 的 token logprobs。
466#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
467pub struct ChatCompletionChoiceLogprobs {
468    /// 内容 token 的 logprobs。
469    #[serde(default, skip_serializing_if = "Vec::is_empty")]
470    pub content: Vec<ChatCompletionTokenLogprob>,
471    /// refusal token 的 logprobs。
472    #[serde(default, skip_serializing_if = "Vec::is_empty")]
473    pub refusal: Vec<ChatCompletionTokenLogprob>,
474    /// 额外字段。
475    #[serde(flatten)]
476    pub extra: BTreeMap<String, Value>,
477}
478
479impl ChatCompletionChoiceLogprobs {
480    /// 按字段名返回对应的 token logprobs 列表。
481    pub fn values(&self, field_name: &str) -> Option<&[ChatCompletionTokenLogprob]> {
482        match field_name {
483            "content" if !self.content.is_empty() => Some(&self.content),
484            "refusal" if !self.refusal.is_empty() => Some(&self.refusal),
485            _ => None,
486        }
487    }
488}
489
490/// 表示流式函数调用增量。
491#[derive(Debug, Clone, Serialize, Deserialize, Default)]
492pub struct ChatCompletionFunctionCallDelta {
493    /// 函数名称增量。
494    pub name: Option<String>,
495    /// 参数增量。
496    pub arguments: Option<String>,
497}
498
499/// 表示流式工具调用增量。
500#[derive(Debug, Clone, Serialize, Deserialize, Default)]
501pub struct ChatCompletionToolCallDelta {
502    /// 增量对应索引。
503    pub index: Option<u32>,
504    /// 工具调用 ID。
505    pub id: Option<String>,
506    /// 调用类型。
507    #[serde(rename = "type")]
508    pub call_type: Option<String>,
509    /// 函数调用增量。
510    pub function: Option<ChatCompletionFunctionCallDelta>,
511}
512
513/// 表示聊天消息。
514#[derive(Debug, Clone, Serialize, Deserialize, Default)]
515pub struct ChatCompletionMessage {
516    /// 角色。
517    pub role: String,
518    /// 文本内容。
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub content: Option<String>,
521    /// 可选名称。
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub name: Option<String>,
524    /// 工具调用关联 ID。
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub tool_call_id: Option<String>,
527    /// 工具调用集合。
528    #[serde(default, skip_serializing_if = "Vec::is_empty")]
529    pub tool_calls: Vec<ChatCompletionToolCall>,
530    /// 拒绝回答文本。
531    #[serde(skip_serializing_if = "Option::is_none")]
532    pub refusal: Option<String>,
533    /// 推理内容。
534    #[serde(skip_serializing_if = "Option::is_none")]
535    pub reasoning_content: Option<String>,
536    /// 推理细节。
537    #[serde(default, skip_serializing_if = "Vec::is_empty")]
538    pub reasoning_details: Vec<ChatReasoningDetail>,
539    /// 额外字段。
540    #[serde(flatten)]
541    pub extra: BTreeMap<String, Value>,
542}
543
544impl ChatCompletionMessage {
545    /// 创建 system 消息。
546    pub fn system(content: impl Into<String>) -> Self {
547        Self {
548            role: "system".into(),
549            content: Some(content.into()),
550            ..Self::default()
551        }
552    }
553
554    /// 创建 user 消息。
555    pub fn user(content: impl Into<String>) -> Self {
556        Self {
557            role: "user".into(),
558            content: Some(content.into()),
559            ..Self::default()
560        }
561    }
562
563    /// 创建 assistant 消息。
564    pub fn assistant(content: impl Into<String>) -> Self {
565        Self {
566            role: "assistant".into(),
567            content: Some(content.into()),
568            ..Self::default()
569        }
570    }
571
572    /// 创建 tool 消息。
573    pub fn tool(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
574        Self {
575            role: "tool".into(),
576            content: Some(content.into()),
577            tool_call_id: Some(tool_call_id.into()),
578            ..Self::default()
579        }
580    }
581
582    /// 尝试把消息文本解析为结构化对象。
583    ///
584    /// # Errors
585    ///
586    /// 当文本存在但 JSON 解析失败时返回错误。
587    pub fn parse_content<T>(&self) -> Result<Option<T>>
588    where
589        T: serde::de::DeserializeOwned,
590    {
591        self.content
592            .as_deref()
593            .map(parse_jsonish_payload)
594            .transpose()
595    }
596
597    /// 尝试解析首个工具调用的参数。
598    ///
599    /// # Errors
600    ///
601    /// 当工具参数不是合法 JSON 时返回错误。
602    pub fn parse_tool_arguments<T>(&self) -> Result<Option<T>>
603    where
604        T: serde::de::DeserializeOwned,
605    {
606        self.tool_calls
607            .first()
608            .map(|tool_call| parse_json_arguments(&tool_call.function.arguments))
609            .transpose()
610    }
611
612    /// 尝试解析指定工具调用的参数。
613    ///
614    /// # Errors
615    ///
616    /// 当工具参数不是合法 JSON 时返回错误。
617    pub fn parse_tool_arguments_by_id<T>(&self, tool_call_id: &str) -> Result<Option<T>>
618    where
619        T: serde::de::DeserializeOwned,
620    {
621        self.tool_calls
622            .iter()
623            .find(|tool_call| tool_call.id == tool_call_id)
624            .map(|tool_call| parse_json_arguments(&tool_call.function.arguments))
625            .transpose()
626    }
627}
628
629/// 表示聊天补全中的单个候选项。
630#[derive(Debug, Clone, Serialize, Deserialize, Default)]
631pub struct ChatCompletionChoice {
632    /// 候选项索引。
633    pub index: u32,
634    /// 结束原因。
635    pub finish_reason: Option<String>,
636    /// 返回消息。
637    pub message: ChatCompletionMessage,
638    /// token 级 logprobs。
639    pub logprobs: Option<ChatCompletionChoiceLogprobs>,
640    /// 额外字段。
641    #[serde(flatten)]
642    pub extra: BTreeMap<String, Value>,
643}
644
645/// 表示聊天补全结果。
646#[derive(Debug, Clone, Serialize, Deserialize, Default)]
647pub struct ChatCompletion {
648    /// 补全 ID。
649    pub id: String,
650    /// 对象类型。
651    #[serde(default)]
652    pub object: String,
653    /// 创建时间。
654    pub created: Option<i64>,
655    /// 模型 ID。
656    #[serde(default)]
657    pub model: String,
658    /// 候选项集合。
659    #[serde(default)]
660    pub choices: Vec<ChatCompletionChoice>,
661    /// 使用统计。
662    pub usage: Option<CompletionUsage>,
663    /// 额外字段。
664    #[serde(flatten)]
665    pub extra: BTreeMap<String, Value>,
666}
667
668impl ChatCompletion {
669    /// 校验返回结果没有因为长度或内容过滤而失去可解析语义。
670    ///
671    /// # Errors
672    ///
673    /// 当任一 choice 的 `finish_reason` 为 `length` 或 `content_filter` 时返回错误。
674    pub fn ensure_not_truncated(&self) -> Result<&Self> {
675        for choice in &self.choices {
676            match choice.finish_reason.as_deref() {
677                Some("length") => return Err(crate::LengthFinishReasonError.into()),
678                Some("content_filter") => return Err(crate::ContentFilterFinishReasonError.into()),
679                _ => {}
680            }
681        }
682        Ok(self)
683    }
684}
685
686/// 表示流式增量。
687#[derive(Debug, Clone, Serialize, Deserialize, Default)]
688pub struct ChatCompletionChunkDelta {
689    /// 角色增量。
690    pub role: Option<String>,
691    /// 文本内容增量。
692    pub content: Option<String>,
693    /// 拒绝回答文本增量。
694    pub refusal: Option<String>,
695    /// 推理内容增量。
696    pub reasoning_content: Option<String>,
697    /// 推理细节增量。
698    #[serde(default)]
699    pub reasoning_details: Vec<ChatReasoningDetail>,
700    /// 工具调用增量。
701    #[serde(default)]
702    pub tool_calls: Vec<ChatCompletionToolCallDelta>,
703    /// 额外字段。
704    #[serde(flatten)]
705    pub extra: BTreeMap<String, Value>,
706}
707
708/// 表示流式候选项。
709#[derive(Debug, Clone, Serialize, Deserialize, Default)]
710pub struct ChatCompletionChunkChoice {
711    /// 候选索引。
712    pub index: u32,
713    /// 增量载荷。
714    pub delta: ChatCompletionChunkDelta,
715    /// 结束原因。
716    pub finish_reason: Option<String>,
717    /// token 级 logprobs 增量。
718    pub logprobs: Option<ChatCompletionChoiceLogprobs>,
719    /// 额外字段。
720    #[serde(flatten)]
721    pub extra: BTreeMap<String, Value>,
722}
723
724/// 表示聊天文本增量事件。
725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
726pub struct ChatContentDeltaEvent {
727    /// 候选索引。
728    pub choice_index: u32,
729    /// 文本增量。
730    pub delta: String,
731}
732
733/// 表示聊天拒绝回答增量事件。
734#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
735pub struct ChatRefusalDeltaEvent {
736    /// 候选索引。
737    pub choice_index: u32,
738    /// 拒绝文本增量。
739    pub delta: String,
740}
741
742/// 表示工具参数增量事件。
743#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
744pub struct ChatToolArgumentsDeltaEvent {
745    /// 候选索引。
746    pub choice_index: u32,
747    /// 工具调用索引。
748    pub tool_call_index: u32,
749    /// 工具名称增量。
750    pub name: Option<String>,
751    /// 参数增量。
752    pub delta: String,
753}
754
755/// 表示 token logprobs 增量事件。
756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
757pub struct ChatLogProbsDeltaEvent {
758    /// 候选索引。
759    pub choice_index: u32,
760    /// logprobs 明细。
761    pub values: Vec<ChatCompletionTokenLogprob>,
762}
763
764/// 表示聊天补全 SSE 分片。
765#[derive(Debug, Clone, Serialize, Deserialize, Default)]
766pub struct ChatCompletionChunk {
767    /// 分片所属补全 ID。
768    pub id: String,
769    /// 对象类型。
770    #[serde(default)]
771    pub object: String,
772    /// 创建时间。
773    pub created: Option<i64>,
774    /// 模型 ID。
775    #[serde(default)]
776    pub model: String,
777    /// 候选项集合。
778    #[serde(default)]
779    pub choices: Vec<ChatCompletionChunkChoice>,
780    /// 额外字段。
781    #[serde(flatten)]
782    pub extra: BTreeMap<String, Value>,
783}
784
785impl ChatCompletionChunk {
786    /// 提取所有文本内容增量。
787    pub fn content_deltas(&self) -> Vec<ChatContentDeltaEvent> {
788        self.choices
789            .iter()
790            .filter_map(|choice| {
791                choice
792                    .delta
793                    .content
794                    .as_ref()
795                    .map(|delta| ChatContentDeltaEvent {
796                        choice_index: choice.index,
797                        delta: delta.clone(),
798                    })
799            })
800            .collect()
801    }
802
803    /// 提取所有拒绝回答增量。
804    pub fn refusal_deltas(&self) -> Vec<ChatRefusalDeltaEvent> {
805        self.choices
806            .iter()
807            .filter_map(|choice| {
808                choice
809                    .delta
810                    .refusal
811                    .as_ref()
812                    .map(|delta| ChatRefusalDeltaEvent {
813                        choice_index: choice.index,
814                        delta: delta.clone(),
815                    })
816            })
817            .collect()
818    }
819
820    /// 提取所有工具参数增量。
821    pub fn tool_argument_deltas(&self) -> Vec<ChatToolArgumentsDeltaEvent> {
822        self.choices
823            .iter()
824            .flat_map(|choice| {
825                choice.delta.tool_calls.iter().filter_map(|tool_call| {
826                    let delta = tool_call.function.as_ref()?.arguments.clone()?;
827                    Some(ChatToolArgumentsDeltaEvent {
828                        choice_index: choice.index,
829                        tool_call_index: tool_call.index.unwrap_or_default(),
830                        name: tool_call
831                            .function
832                            .as_ref()
833                            .and_then(|function| function.name.clone()),
834                        delta,
835                    })
836                })
837            })
838            .collect()
839    }
840
841    /// 提取内容 token 的 logprobs 增量。
842    pub fn logprobs_content_deltas(&self) -> Vec<ChatLogProbsDeltaEvent> {
843        extract_logprobs(self, "content")
844    }
845
846    /// 提取拒绝回答 token 的 logprobs 增量。
847    pub fn logprobs_refusal_deltas(&self) -> Vec<ChatLogProbsDeltaEvent> {
848        extract_logprobs(self, "refusal")
849    }
850}
851
852fn extract_logprobs(chunk: &ChatCompletionChunk, field_name: &str) -> Vec<ChatLogProbsDeltaEvent> {
853    chunk
854        .choices
855        .iter()
856        .filter_map(|choice| {
857            let values = choice
858                .logprobs
859                .as_ref()
860                .and_then(|logprobs| logprobs.values(field_name))?
861                .to_vec();
862            Some(ChatLogProbsDeltaEvent {
863                choice_index: choice.index,
864                values,
865            })
866        })
867        .collect()
868}
869
870/// 表示聊天工具定义。
871#[derive(Debug, Clone, Serialize, Deserialize)]
872pub struct ChatToolDefinition {
873    /// 工具类型,当前固定为 `function`。
874    #[serde(rename = "type")]
875    pub tool_type: String,
876    /// 函数定义。
877    pub function: ChatToolFunction,
878}
879
880impl ChatToolDefinition {
881    #[cfg(feature = "tool-runner")]
882    fn from_tool(tool: &ToolDefinition) -> Self {
883        Self {
884            tool_type: "function".into(),
885            function: ChatToolFunction {
886                name: tool.name.clone(),
887                description: tool.description.clone(),
888                parameters: tool.parameters.clone(),
889            },
890        }
891    }
892
893    /// 转换为 Responses API 所需的扁平工具定义格式。
894    fn as_response_tool_value(&self) -> Value {
895        serde_json::json!({
896            "type": self.tool_type,
897            "name": self.function.name,
898            "description": self.function.description,
899            "parameters": self.function.parameters,
900        })
901    }
902}
903
904/// 表示聊天工具函数定义。
905#[derive(Debug, Clone, Serialize, Deserialize)]
906pub struct ChatToolFunction {
907    /// 函数名。
908    pub name: String,
909    /// 函数描述。
910    pub description: Option<String>,
911    /// 参数 Schema。
912    pub parameters: JsonPayload,
913}
914
915/// 表示聊天补全请求参数。
916#[derive(Debug, Clone, Serialize, Deserialize, Default)]
917pub struct ChatCompletionCreateParams {
918    /// 模型 ID。
919    #[serde(skip_serializing_if = "Option::is_none")]
920    pub model: Option<String>,
921    /// 历史消息。
922    #[serde(default, skip_serializing_if = "Vec::is_empty")]
923    pub messages: Vec<ChatCompletionMessage>,
924    /// 温度。
925    #[serde(skip_serializing_if = "Option::is_none")]
926    pub temperature: Option<f32>,
927    /// 候选数量。
928    #[serde(skip_serializing_if = "Option::is_none")]
929    pub n: Option<u32>,
930    /// 最大 token 数。
931    #[serde(skip_serializing_if = "Option::is_none")]
932    pub max_tokens: Option<u32>,
933    /// 工具定义。
934    #[serde(default, skip_serializing_if = "Vec::is_empty")]
935    pub tools: Vec<ChatToolDefinition>,
936    /// 工具选择策略。
937    #[serde(skip_serializing_if = "Option::is_none")]
938    pub tool_choice: Option<ChatToolChoice>,
939    /// 流式开关。
940    #[serde(skip_serializing_if = "Option::is_none")]
941    pub stream: Option<bool>,
942}
943
944/// 表示 Responses 对象。
945#[derive(Debug, Clone, Serialize, Deserialize, Default)]
946pub struct Response {
947    /// 响应 ID。
948    pub id: String,
949    /// 创建时间。
950    pub created_at: Option<u64>,
951    /// 对象类型。
952    #[serde(default)]
953    pub object: String,
954    /// 模型 ID。
955    pub model: Option<String>,
956    /// 状态。
957    pub status: Option<String>,
958    /// 错误信息。
959    pub error: Option<ResponseError>,
960    /// 不完整原因。
961    pub incomplete_details: Option<ResponseIncompleteDetails>,
962    /// 元数据。
963    pub metadata: Option<BTreeMap<String, String>>,
964    /// 输出项。
965    #[serde(default)]
966    pub output: Vec<ResponseOutputItem>,
967    /// 用量统计。
968    pub usage: Option<ResponseUsage>,
969    /// 额外字段。
970    #[serde(flatten)]
971    pub extra: BTreeMap<String, Value>,
972}
973
974impl Response {
975    /// 尝试提取最终文本输出。
976    pub fn output_text(&self) -> Option<String> {
977        for item in &self.output {
978            if let Some(text) = item.output_text() {
979                return Some(text.to_owned());
980            }
981        }
982
983        self.extra
984            .get("output_text")
985            .and_then(Value::as_str)
986            .map(str::to_owned)
987    }
988}
989
990/// 表示 responses 顶层错误。
991#[derive(Debug, Clone, Serialize, Deserialize, Default)]
992pub struct ResponseError {
993    /// 错误码。
994    pub code: Option<String>,
995    /// 错误消息。
996    pub message: Option<String>,
997    /// 额外字段。
998    #[serde(flatten)]
999    pub extra: BTreeMap<String, Value>,
1000}
1001
1002/// 表示 responses 不完整原因。
1003#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1004pub struct ResponseIncompleteDetails {
1005    /// 不完整原因。
1006    pub reason: Option<String>,
1007    /// 额外字段。
1008    #[serde(flatten)]
1009    pub extra: BTreeMap<String, Value>,
1010}
1011
1012/// 表示 responses 用量明细。
1013#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1014pub struct ResponseUsage {
1015    /// 输入 token 数。
1016    #[serde(default)]
1017    pub input_tokens: u64,
1018    /// 输入 token 明细。
1019    pub input_tokens_details: Option<ResponseInputTokensDetails>,
1020    /// 输出 token 数。
1021    #[serde(default)]
1022    pub output_tokens: u64,
1023    /// 输出 token 明细。
1024    pub output_tokens_details: Option<ResponseOutputTokensDetails>,
1025    /// 总 token 数。
1026    #[serde(default)]
1027    pub total_tokens: u64,
1028    /// 额外字段。
1029    #[serde(flatten)]
1030    pub extra: BTreeMap<String, Value>,
1031}
1032
1033/// 表示 responses 输入 token 明细。
1034#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1035pub struct ResponseInputTokensDetails {
1036    /// cache 命中 token 数。
1037    pub cached_tokens: Option<u64>,
1038    /// 额外字段。
1039    #[serde(flatten)]
1040    pub extra: BTreeMap<String, Value>,
1041}
1042
1043/// 表示 responses 输出 token 明细。
1044#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1045pub struct ResponseOutputTokensDetails {
1046    /// reasoning token 数。
1047    pub reasoning_tokens: Option<u64>,
1048    /// 额外字段。
1049    #[serde(flatten)]
1050    pub extra: BTreeMap<String, Value>,
1051}
1052
1053/// 表示响应输出项。
1054#[derive(Debug, Clone, Serialize, Deserialize)]
1055#[serde(untagged)]
1056pub enum ResponseOutputItem {
1057    /// 已知输出项。
1058    Known(KnownResponseOutputItem),
1059    /// 向前兼容保留的原始项。
1060    Raw(ResponseOutputItemRaw),
1061}
1062
1063impl Default for ResponseOutputItem {
1064    fn default() -> Self {
1065        Self::Raw(ResponseOutputItemRaw::default())
1066    }
1067}
1068
1069impl ResponseOutputItem {
1070    /// 返回消息输出项。
1071    pub fn as_message(&self) -> Option<&ResponseOutputMessage> {
1072        match self {
1073            Self::Known(KnownResponseOutputItem::Message(message)) => Some(message),
1074            _ => None,
1075        }
1076    }
1077
1078    /// 返回函数调用输出项。
1079    pub fn as_function_call(&self) -> Option<&ResponseFunctionToolCall> {
1080        match self {
1081            Self::Known(KnownResponseOutputItem::FunctionCall(call)) => Some(call),
1082            _ => None,
1083        }
1084    }
1085
1086    /// 返回原始 JSON 项。
1087    pub fn as_raw(&self) -> Option<&Value> {
1088        match self {
1089            Self::Raw(value) => Some(value.as_raw()),
1090            _ => None,
1091        }
1092    }
1093
1094    /// 提取输出文本。
1095    pub fn output_text(&self) -> Option<&str> {
1096        match self {
1097            Self::Known(KnownResponseOutputItem::OutputText(text)) => Some(text.text.as_str()),
1098            Self::Known(KnownResponseOutputItem::Message(message)) => message
1099                .content
1100                .iter()
1101                .find_map(ResponseOutputContentPart::text),
1102            Self::Raw(value) => {
1103                let value = value.as_raw();
1104                if let Some(text) = value.get("text").and_then(Value::as_str) {
1105                    return Some(text);
1106                }
1107                value
1108                    .get("content")
1109                    .and_then(Value::as_array)
1110                    .and_then(|content| {
1111                        content
1112                            .iter()
1113                            .find_map(|item| item.get("text").and_then(Value::as_str))
1114                    })
1115            }
1116            _ => None,
1117        }
1118    }
1119}
1120
1121/// 已知的响应输出项类型。
1122#[derive(Debug, Clone, Serialize, Deserialize)]
1123#[serde(tag = "type", rename_all = "snake_case")]
1124pub enum KnownResponseOutputItem {
1125    /// assistant message。
1126    Message(ResponseOutputMessage),
1127    /// function call。
1128    FunctionCall(ResponseFunctionToolCall),
1129    /// 某些兼容 Provider 直接把 `output_text` 作为顶层输出项返回。
1130    OutputText(ResponseOutputText),
1131    /// 某些兼容 Provider 直接把 `refusal` 作为顶层输出项返回。
1132    Refusal(ResponseOutputRefusal),
1133}
1134
1135/// 表示 assistant message 输出。
1136#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1137pub struct ResponseOutputMessage {
1138    /// message ID。
1139    pub id: String,
1140    /// 内容片段。
1141    #[serde(default)]
1142    pub content: Vec<ResponseOutputContentPart>,
1143    /// 角色。
1144    pub role: Option<String>,
1145    /// 状态。
1146    pub status: Option<String>,
1147    /// assistant phase。
1148    pub phase: Option<String>,
1149    /// 额外字段。
1150    #[serde(flatten)]
1151    pub extra: BTreeMap<String, Value>,
1152}
1153
1154/// 表示函数工具调用输出项。
1155#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1156pub struct ResponseFunctionToolCall {
1157    /// 输出项 ID。
1158    pub id: String,
1159    /// tool call ID。
1160    pub call_id: Option<String>,
1161    /// 工具名称。
1162    pub name: Option<String>,
1163    /// 参数 JSON 字符串。
1164    #[serde(default)]
1165    pub arguments: String,
1166    /// 状态。
1167    pub status: Option<String>,
1168    /// 额外字段。
1169    #[serde(flatten)]
1170    pub extra: BTreeMap<String, Value>,
1171}
1172
1173/// 表示 message 中的内容片段。
1174#[derive(Debug, Clone, Serialize, Deserialize)]
1175#[serde(untagged)]
1176pub enum ResponseOutputContentPart {
1177    /// 已知内容片段。
1178    Known(KnownResponseOutputContentPart),
1179    /// 向前兼容保留的原始片段。
1180    Raw(ResponseOutputContentPartRaw),
1181}
1182
1183impl Default for ResponseOutputContentPart {
1184    fn default() -> Self {
1185        Self::Raw(ResponseOutputContentPartRaw::default())
1186    }
1187}
1188
1189impl ResponseOutputContentPart {
1190    /// 返回 output_text 内容片段。
1191    pub fn as_output_text(&self) -> Option<&ResponseOutputText> {
1192        match self {
1193            Self::Known(KnownResponseOutputContentPart::OutputText(text)) => Some(text),
1194            _ => None,
1195        }
1196    }
1197
1198    /// 提取文本内容。
1199    pub fn text(&self) -> Option<&str> {
1200        match self {
1201            Self::Known(KnownResponseOutputContentPart::OutputText(text)) => {
1202                Some(text.text.as_str())
1203            }
1204            Self::Raw(value) => value.as_raw().get("text").and_then(Value::as_str),
1205            _ => None,
1206        }
1207    }
1208}
1209
1210/// 已知的 message 内容片段。
1211#[derive(Debug, Clone, Serialize, Deserialize)]
1212#[serde(tag = "type", rename_all = "snake_case")]
1213pub enum KnownResponseOutputContentPart {
1214    /// 输出文本。
1215    OutputText(ResponseOutputText),
1216    /// 拒绝回答。
1217    Refusal(ResponseOutputRefusal),
1218}
1219
1220/// 表示 output_text 注解中的文件引用。
1221#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1222pub struct ResponseOutputTextFileCitation {
1223    /// 文件 ID。
1224    pub file_id: String,
1225    /// 文件名。
1226    pub filename: String,
1227    /// 文件索引。
1228    pub index: u64,
1229    /// 额外字段。
1230    #[serde(flatten)]
1231    pub extra: BTreeMap<String, Value>,
1232}
1233
1234/// 表示 output_text 注解中的 URL 引用。
1235#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1236pub struct ResponseOutputTextUrlCitation {
1237    /// 引用结束位置。
1238    pub end_index: u64,
1239    /// 引用起始位置。
1240    pub start_index: u64,
1241    /// 标题。
1242    pub title: String,
1243    /// URL。
1244    pub url: String,
1245    /// 额外字段。
1246    #[serde(flatten)]
1247    pub extra: BTreeMap<String, Value>,
1248}
1249
1250/// 表示 output_text 注解中的容器文件引用。
1251#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1252pub struct ResponseOutputTextContainerFileCitation {
1253    /// 容器 ID。
1254    pub container_id: String,
1255    /// 引用结束位置。
1256    pub end_index: u64,
1257    /// 文件 ID。
1258    pub file_id: String,
1259    /// 文件名。
1260    pub filename: String,
1261    /// 引用起始位置。
1262    pub start_index: u64,
1263    /// 额外字段。
1264    #[serde(flatten)]
1265    pub extra: BTreeMap<String, Value>,
1266}
1267
1268/// 表示 output_text 注解中的文件路径。
1269#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
1270pub struct ResponseOutputTextFilePath {
1271    /// 文件 ID。
1272    pub file_id: String,
1273    /// 文件索引。
1274    pub index: u64,
1275    /// 额外字段。
1276    #[serde(flatten)]
1277    pub extra: BTreeMap<String, Value>,
1278}
1279
1280/// 已知的 output_text 注解类型。
1281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1282#[serde(tag = "type", rename_all = "snake_case")]
1283pub enum KnownResponseOutputTextAnnotation {
1284    /// 文件引用。
1285    FileCitation(ResponseOutputTextFileCitation),
1286    /// URL 引用。
1287    UrlCitation(ResponseOutputTextUrlCitation),
1288    /// 容器文件引用。
1289    ContainerFileCitation(ResponseOutputTextContainerFileCitation),
1290    /// 文件路径。
1291    FilePath(ResponseOutputTextFilePath),
1292}
1293
1294/// 向前兼容保留的未知 output_text 注解。
1295#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
1296pub struct ResponseOutputTextAnnotationUnknown {
1297    /// 注解类型。
1298    #[serde(rename = "type")]
1299    pub annotation_type: Option<String>,
1300    /// 额外字段。
1301    #[serde(flatten)]
1302    pub extra: BTreeMap<String, Value>,
1303}
1304
1305/// 表示 output_text 注解。
1306#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1307#[serde(untagged)]
1308pub enum ResponseOutputTextAnnotation {
1309    /// 已知注解。
1310    Known(KnownResponseOutputTextAnnotation),
1311    /// 未知注解。
1312    Unknown(ResponseOutputTextAnnotationUnknown),
1313}
1314
1315impl Default for ResponseOutputTextAnnotation {
1316    fn default() -> Self {
1317        Self::Unknown(ResponseOutputTextAnnotationUnknown::default())
1318    }
1319}
1320
1321impl ResponseOutputTextAnnotation {
1322    /// 返回注解类型。
1323    pub fn kind(&self) -> Option<&str> {
1324        match self {
1325            Self::Known(KnownResponseOutputTextAnnotation::FileCitation(_)) => {
1326                Some("file_citation")
1327            }
1328            Self::Known(KnownResponseOutputTextAnnotation::UrlCitation(_)) => Some("url_citation"),
1329            Self::Known(KnownResponseOutputTextAnnotation::ContainerFileCitation(_)) => {
1330                Some("container_file_citation")
1331            }
1332            Self::Known(KnownResponseOutputTextAnnotation::FilePath(_)) => Some("file_path"),
1333            Self::Unknown(annotation) => annotation.annotation_type.as_deref(),
1334        }
1335    }
1336}
1337
1338/// 表示 output_text 的 top logprob。
1339#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
1340pub struct ResponseOutputTextTopLogprob {
1341    /// token 内容。
1342    #[serde(default)]
1343    pub token: String,
1344    /// UTF-8 bytes。
1345    #[serde(default)]
1346    pub bytes: Vec<u8>,
1347    /// token 对应的 logprob。
1348    #[serde(default)]
1349    pub logprob: f64,
1350    /// 额外字段。
1351    #[serde(flatten)]
1352    pub extra: BTreeMap<String, Value>,
1353}
1354
1355/// 表示 output_text 的单个 token logprob。
1356#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
1357pub struct ResponseOutputTextLogprob {
1358    /// token 内容。
1359    #[serde(default)]
1360    pub token: String,
1361    /// UTF-8 bytes。
1362    #[serde(default)]
1363    pub bytes: Vec<u8>,
1364    /// token 对应的 logprob。
1365    #[serde(default)]
1366    pub logprob: f64,
1367    /// top logprobs。
1368    #[serde(default)]
1369    pub top_logprobs: Vec<ResponseOutputTextTopLogprob>,
1370    /// 额外字段。
1371    #[serde(flatten)]
1372    pub extra: BTreeMap<String, Value>,
1373}
1374
1375/// 表示输出文本片段。
1376#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1377pub struct ResponseOutputText {
1378    /// 注解。
1379    #[serde(default)]
1380    pub annotations: Vec<ResponseOutputTextAnnotation>,
1381    /// 文本。
1382    #[serde(default)]
1383    pub text: String,
1384    /// token 级 logprobs。
1385    pub logprobs: Option<Vec<ResponseOutputTextLogprob>>,
1386    /// 额外字段。
1387    #[serde(flatten)]
1388    pub extra: BTreeMap<String, Value>,
1389}
1390
1391/// 表示拒绝回答片段。
1392#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1393pub struct ResponseOutputRefusal {
1394    /// 拒绝原因。
1395    #[serde(default)]
1396    pub refusal: String,
1397    /// 额外字段。
1398    #[serde(flatten)]
1399    pub extra: BTreeMap<String, Value>,
1400}
1401
1402/// 表示 Responses 创建参数。
1403#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1404pub struct ResponseCreateParams {
1405    /// 模型 ID。
1406    #[serde(skip_serializing_if = "Option::is_none")]
1407    pub model: Option<String>,
1408    /// 输入载荷。
1409    #[serde(skip_serializing_if = "Option::is_none")]
1410    pub input: Option<ResponseInputPayload>,
1411    /// 温度。
1412    #[serde(skip_serializing_if = "Option::is_none")]
1413    pub temperature: Option<f32>,
1414    /// 工具定义。
1415    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1416    pub tools: Vec<ChatToolDefinition>,
1417    /// 是否启用流式。
1418    #[serde(skip_serializing_if = "Option::is_none")]
1419    pub stream: Option<bool>,
1420}
1421
1422fn default_function_type() -> String {
1423    "function".into()
1424}
1425
1426fn parse_jsonish_payload<T>(payload: &str) -> Result<T>
1427where
1428    T: serde::de::DeserializeOwned,
1429{
1430    let trimmed = payload.trim();
1431    let normalized = trimmed
1432        .strip_prefix("```json")
1433        .or_else(|| trimmed.strip_prefix("```"))
1434        .map(|value| value.trim())
1435        .and_then(|value| value.strip_suffix("```"))
1436        .map_or(trimmed, str::trim);
1437    serde_json::from_str(normalized).map_err(|error| {
1438        Error::Serialization(crate::SerializationError::new(format!(
1439            "结构化 JSON 解析失败: {error}"
1440        )))
1441    })
1442}
1443
1444fn parse_json_arguments<T>(arguments: &str) -> Result<T>
1445where
1446    T: serde::de::DeserializeOwned,
1447{
1448    serde_json::from_str(arguments).map_err(|error| {
1449        Error::Serialization(crate::SerializationError::new(format!(
1450            "工具参数 JSON 解析失败: {error}"
1451        )))
1452    })
1453}
1454
1455handle!(
1456    /// 顶层 completions 资源。
1457    CompletionsResource
1458);
1459handle!(
1460    /// 聊天资源命名空间。
1461    ChatResource
1462);
1463handle!(
1464    /// 聊天补全资源。
1465    ChatCompletionsResource
1466);
1467handle!(
1468    /// 聊天补全消息子资源。
1469    ChatCompletionMessagesResource
1470);
1471handle!(
1472    /// Embeddings 资源。
1473    EmbeddingsResource
1474);
1475handle!(
1476    /// Files 资源。
1477    FilesResource
1478);
1479handle!(
1480    /// Images 资源。
1481    ImagesResource
1482);
1483handle!(
1484    /// Audio 资源命名空间。
1485    AudioResource
1486);
1487handle!(
1488    /// Audio Speech 资源。
1489    AudioSpeechResource
1490);
1491handle!(
1492    /// Audio Transcriptions 资源。
1493    AudioTranscriptionsResource
1494);
1495handle!(
1496    /// Audio Translations 资源。
1497    AudioTranslationsResource
1498);
1499handle!(
1500    /// Moderations 资源。
1501    ModerationsResource
1502);
1503handle!(
1504    /// Models 资源。
1505    ModelsResource
1506);
1507handle!(
1508    /// Fine-tuning 资源命名空间。
1509    FineTuningResource
1510);
1511handle!(
1512    /// Fine-tuning Jobs 资源。
1513    FineTuningJobsResource
1514);
1515handle!(
1516    /// Fine-tuning Checkpoints 资源。
1517    FineTuningJobCheckpointsResource
1518);
1519handle!(
1520    /// Fine-tuning 权限资源。
1521    FineTuningCheckpointPermissionsResource
1522);
1523handle!(
1524    /// Fine-tuning Alpha 命名空间。
1525    FineTuningAlphaResource
1526);
1527handle!(
1528    /// Fine-tuning Alpha Graders 资源。
1529    FineTuningAlphaGradersResource
1530);
1531handle!(
1532    /// Graders 资源命名空间。
1533    GradersResource
1534);
1535handle!(
1536    /// Vector Stores 资源。
1537    VectorStoresResource
1538);
1539handle!(
1540    /// Vector Store Files 资源。
1541    VectorStoreFilesResource
1542);
1543handle!(
1544    /// Vector Store File Batches 资源。
1545    VectorStoreFileBatchesResource
1546);
1547handle!(
1548    /// Batches 资源。
1549    BatchesResource
1550);
1551handle!(
1552    /// Uploads 资源。
1553    UploadsResource
1554);
1555handle!(
1556    /// Uploads Parts 资源。
1557    UploadPartsResource
1558);
1559handle!(
1560    /// Responses 资源。
1561    ResponsesResource
1562);
1563handle!(
1564    /// Responses Input Items 资源。
1565    ResponseInputItemsResource
1566);
1567handle!(
1568    /// Responses Input Tokens 资源。
1569    ResponseInputTokensResource
1570);
1571handle!(
1572    /// Realtime 资源命名空间。
1573    RealtimeResource
1574);
1575handle!(
1576    /// Realtime Client Secrets 资源。
1577    RealtimeClientSecretsResource
1578);
1579handle!(
1580    /// Realtime Calls 资源。
1581    RealtimeCallsResource
1582);
1583handle!(
1584    /// Conversations 资源。
1585    ConversationsResource
1586);
1587handle!(
1588    /// Conversation Items 资源。
1589    ConversationItemsResource
1590);
1591handle!(
1592    /// Evals 资源。
1593    EvalsResource
1594);
1595handle!(
1596    /// Eval Runs 资源。
1597    EvalRunsResource
1598);
1599handle!(
1600    /// Eval Run Output Items 资源。
1601    EvalRunOutputItemsResource
1602);
1603handle!(
1604    /// Containers 资源。
1605    ContainersResource
1606);
1607handle!(
1608    /// Container Files 资源。
1609    ContainerFilesResource
1610);
1611handle!(
1612    /// Container File Content 资源。
1613    ContainerFilesContentResource
1614);
1615handle!(
1616    /// Skills 资源。
1617    SkillsResource
1618);
1619handle!(
1620    /// Skills Content 资源。
1621    SkillsContentResource
1622);
1623handle!(
1624    /// Skills Versions 资源。
1625    SkillVersionsResource
1626);
1627handle!(
1628    /// Skills Versions Content 资源。
1629    SkillVersionsContentResource
1630);
1631handle!(
1632    /// Videos 资源。
1633    VideosResource
1634);
1635handle!(
1636    /// Webhooks 资源。
1637    WebhooksResource
1638);
1639handle!(
1640    /// Beta 资源命名空间。
1641    BetaResource
1642);
1643handle!(
1644    /// Beta Assistants 资源。
1645    BetaAssistantsResource
1646);
1647handle!(
1648    /// Beta Threads 资源。
1649    BetaThreadsResource
1650);
1651handle!(
1652    /// Beta Thread Messages 资源。
1653    BetaThreadMessagesResource
1654);
1655handle!(
1656    /// Beta Thread Runs 资源。
1657    BetaThreadRunsResource
1658);
1659handle!(
1660    /// Beta Thread Run Steps 资源。
1661    BetaThreadRunStepsResource
1662);
1663handle!(
1664    /// Beta ChatKit 命名空间。
1665    BetaChatkitResource
1666);
1667handle!(
1668    /// Beta ChatKit Sessions 资源。
1669    BetaChatkitSessionsResource
1670);
1671handle!(
1672    /// Beta ChatKit Threads 资源。
1673    BetaChatkitThreadsResource
1674);
1675handle!(
1676    /// Beta Realtime 命名空间。
1677    BetaRealtimeResource
1678);
1679handle!(
1680    /// Beta Realtime Sessions 资源。
1681    BetaRealtimeSessionsResource
1682);
1683handle!(
1684    /// Beta Realtime Transcription Sessions 资源。
1685    BetaRealtimeTranscriptionSessionsResource
1686);