openai-core 0.1.1

Rust SDK for OpenAI-compatible ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Responses and Realtime namespace implementations and builders.

use std::collections::BTreeMap;
#[cfg(feature = "structured-output")]
use std::marker::PhantomData;
use std::time::Duration;

use http::Method;
#[cfg(feature = "structured-output")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_util::sync::CancellationToken;

use crate::Client;
use crate::config::RequestOptions;
use crate::error::{Error, Result};
use crate::generated::endpoints;
#[cfg(feature = "structured-output")]
use crate::helpers::{ParsedResponse, parse_json_payload};
use crate::json_payload::JsonPayload;
use crate::response_meta::ApiResponse;
use crate::stream::{ResponseEventStream, ResponseStream};
use crate::transport::{RequestSpec, merge_json_body};
#[cfg(feature = "realtime")]
use crate::websocket::RealtimeSocket;
#[cfg(feature = "responses-ws")]
use crate::websocket::ResponsesSocket;

use super::{
    ChatToolDefinition, ConversationItem, DeleteResponse, InputTokenCount, JsonRequestBuilder,
    ListRequestBuilder, NoContentRequestBuilder, RealtimeCallsResource,
    RealtimeClientSecretsResource, RealtimeResource, RealtimeSessionPayload, Response,
    ResponseCreateParams, ResponseInputItemPayload, ResponseInputItemsResource,
    ResponseInputPayload, ResponseInputTokensResource, ResponsesResource, encode_path_segment,
    value_from,
};

/// Realtime API 返回的临时 client secret。
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RealtimeSessionClientSecret {
    /// 过期时间。
    pub expires_at: u64,
    /// 可下发给前端的临时密钥。
    #[serde(default)]
    pub value: String,
    /// 额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// `realtime.client_secrets.create` 的返回值。
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RealtimeClientSecretCreateResponse {
    /// 官方 documented spec 返回的顶层 secret 值。
    pub value: Option<String>,
    /// 官方 documented spec 返回的顶层过期时间。
    pub expires_at: Option<u64>,
    /// 新版结构化 client secret。
    pub client_secret: Option<RealtimeSessionClientSecret>,
    /// 某些兼容 Provider 返回的扁平 secret 字段。
    pub secret: Option<String>,
    /// 会话配置类型。
    #[serde(rename = "type")]
    pub session_type: Option<String>,
    /// 生效后的会话配置。
    pub session: Option<RealtimeSessionPayload>,
    /// 额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl RealtimeClientSecretCreateResponse {
    /// 返回兼容不同 Provider 形态的 secret 值。
    pub fn secret_value(&self) -> Option<&str> {
        self.client_secret
            .as_ref()
            .map(|secret| secret.value.as_str())
            .or(self.value.as_deref())
            .or(self.secret.as_deref())
    }
}

impl ResponsesResource {
    /// 创建 responses 请求构建器。
    pub fn create(&self) -> ResponseCreateRequestBuilder {
        ResponseCreateRequestBuilder::new(self.client.clone())
    }

    /// 创建 responses 结构化解析构建器。
    #[cfg(feature = "structured-output")]
    #[cfg_attr(docsrs, doc(cfg(feature = "structured-output")))]
    pub fn parse<T>(&self) -> ResponseParseRequestBuilder<T> {
        ResponseParseRequestBuilder::new(self.client.clone())
    }

    /// 创建 responses 流式构建器。
    pub fn stream(&self) -> ResponseStreamRequestBuilder {
        ResponseStreamRequestBuilder::new(self.client.clone())
    }

    /// 按响应 ID 继续一个已有的 Responses SSE 流。
    pub fn stream_response(&self, response_id: impl Into<String>) -> ResponseStreamRequestBuilder {
        ResponseStreamRequestBuilder::new(self.client.clone()).response_id(response_id)
    }

    /// 创建 Responses WebSocket 连接构建器。
    #[cfg(feature = "responses-ws")]
    #[cfg_attr(docsrs, doc(cfg(feature = "responses-ws")))]
    pub fn ws(&self) -> ResponsesSocketRequestBuilder {
        ResponsesSocketRequestBuilder::new(self.client.clone())
    }

    /// 获取 response。
    pub fn retrieve(&self, response_id: impl Into<String>) -> JsonRequestBuilder<Response> {
        JsonRequestBuilder::new(
            self.client.clone(),
            "responses.retrieve",
            Method::GET,
            format!("/responses/{}", encode_path_segment(response_id.into())),
        )
    }

    /// 删除 response。
    pub fn delete(&self, response_id: impl Into<String>) -> JsonRequestBuilder<DeleteResponse> {
        JsonRequestBuilder::new(
            self.client.clone(),
            "responses.delete",
            Method::DELETE,
            format!("/responses/{}", encode_path_segment(response_id.into())),
        )
    }

    /// 取消后台 response。
    pub fn cancel(&self, response_id: impl Into<String>) -> JsonRequestBuilder<Response> {
        JsonRequestBuilder::new(
            self.client.clone(),
            "responses.cancel",
            Method::POST,
            format!(
                "/responses/{}/cancel",
                encode_path_segment(response_id.into())
            ),
        )
    }

    /// 压缩 response。
    pub fn compact(&self) -> JsonRequestBuilder<Response> {
        JsonRequestBuilder::new(
            self.client.clone(),
            "responses.compact",
            Method::POST,
            "/responses/compact",
        )
    }

    /// 返回 input_items 子资源。
    pub fn input_items(&self) -> ResponseInputItemsResource {
        ResponseInputItemsResource::new(self.client.clone())
    }

    /// 返回 input_tokens 子资源。
    pub fn input_tokens(&self) -> ResponseInputTokensResource {
        ResponseInputTokensResource::new(self.client.clone())
    }
}

impl ResponseInputItemsResource {
    /// 列出 response 输入项。
    pub fn list(&self, response_id: impl Into<String>) -> ListRequestBuilder<ConversationItem> {
        let endpoint = endpoints::responses::RESPONSES_INPUT_ITEMS_LIST;
        ListRequestBuilder::new(
            self.client.clone(),
            endpoint.id,
            endpoint.render(&[("response_id", &encode_path_segment(response_id.into()))]),
        )
    }
}

impl ResponseInputTokensResource {
    /// 统计输入 token。
    pub fn count(&self) -> JsonRequestBuilder<InputTokenCount> {
        let endpoint = endpoints::responses::RESPONSES_INPUT_TOKENS_COUNT;
        JsonRequestBuilder::new(
            self.client.clone(),
            endpoint.id,
            Method::POST,
            endpoint.template,
        )
    }
}

impl RealtimeResource {
    /// 创建 Realtime WebSocket 连接构建器。
    #[cfg(feature = "realtime")]
    #[cfg_attr(docsrs, doc(cfg(feature = "realtime")))]
    pub fn ws(&self) -> RealtimeSocketRequestBuilder {
        RealtimeSocketRequestBuilder::new(self.client.clone())
    }

    /// 返回 client_secrets 子资源。
    pub fn client_secrets(&self) -> RealtimeClientSecretsResource {
        RealtimeClientSecretsResource::new(self.client.clone())
    }

    /// 返回 calls 子资源。
    pub fn calls(&self) -> RealtimeCallsResource {
        RealtimeCallsResource::new(self.client.clone())
    }
}

impl RealtimeClientSecretsResource {
    /// 创建 client secret。
    pub fn create(&self) -> JsonRequestBuilder<RealtimeClientSecretCreateResponse> {
        let endpoint = endpoints::responses::REALTIME_CLIENT_SECRETS_CREATE;
        JsonRequestBuilder::new(
            self.client.clone(),
            endpoint.id,
            Method::POST,
            endpoint.template,
        )
    }
}

impl RealtimeCallsResource {
    /// 接听通话。
    pub fn accept(&self, call_id: impl Into<String>) -> NoContentRequestBuilder {
        realtime_call_action(
            self.client.clone(),
            endpoints::responses::REALTIME_CALLS_ACCEPT,
            call_id,
        )
    }

    /// 挂断通话。
    pub fn hangup(&self, call_id: impl Into<String>) -> NoContentRequestBuilder {
        realtime_call_action(
            self.client.clone(),
            endpoints::responses::REALTIME_CALLS_HANGUP,
            call_id,
        )
    }

    /// 转接通话。
    pub fn refer(&self, call_id: impl Into<String>) -> NoContentRequestBuilder {
        realtime_call_action(
            self.client.clone(),
            endpoints::responses::REALTIME_CALLS_REFER,
            call_id,
        )
    }

    /// 拒绝通话。
    pub fn reject(&self, call_id: impl Into<String>) -> NoContentRequestBuilder {
        realtime_call_action(
            self.client.clone(),
            endpoints::responses::REALTIME_CALLS_REJECT,
            call_id,
        )
    }
}

fn realtime_call_action(
    client: Client,
    endpoint: endpoints::PathTemplateEndpoint,
    call_id: impl Into<String>,
) -> NoContentRequestBuilder {
    NoContentRequestBuilder::new(
        client,
        endpoint.id,
        Method::POST,
        endpoint.render(&[("call_id", &encode_path_segment(call_id.into()))]),
    )
    .extra_header("accept", "*/*")
}

/// 表示 Responses 创建构建器。
#[derive(Debug, Clone, Default)]
pub struct ResponseCreateRequestBuilder {
    client: Option<Client>,
    pub(crate) params: ResponseCreateParams,
    options: RequestOptions,
    extra_body: BTreeMap<String, Value>,
    provider_options: BTreeMap<String, Value>,
}

/// 表示 Responses 流式构建器。
#[derive(Debug, Clone)]
pub struct ResponseStreamRequestBuilder {
    inner: ResponseCreateRequestBuilder,
    response_id: Option<String>,
    starting_after: Option<u64>,
}

/// 表示 Realtime WebSocket 连接构建器。
#[cfg(feature = "realtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "realtime")))]
#[derive(Debug, Clone)]
pub struct RealtimeSocketRequestBuilder {
    client: Client,
    model: Option<String>,
    options: RequestOptions,
}

/// 表示 Responses WebSocket 连接构建器。
#[cfg(feature = "responses-ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "responses-ws")))]
#[derive(Debug, Clone)]
pub struct ResponsesSocketRequestBuilder {
    client: Client,
    options: RequestOptions,
}

impl ResponseStreamRequestBuilder {
    pub(crate) fn new(client: Client) -> Self {
        Self {
            inner: ResponseCreateRequestBuilder::new(client),
            response_id: None,
            starting_after: None,
        }
    }

    /// 设置模型。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    /// 设置输入文本。
    pub fn input_text(mut self, input: impl Into<String>) -> Self {
        self.inner = self.inner.input_text(input);
        self
    }

    /// 设置输入项数组。
    pub fn input_items(mut self, items: Vec<ResponseInputItemPayload>) -> Self {
        self.inner = self.inner.input_items(items);
        self
    }

    /// 直接设置输入载荷。
    pub fn input(mut self, input: impl Into<ResponseInputPayload>) -> Self {
        self.inner = self.inner.input(input);
        self
    }

    /// 设置温度。
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.inner = self.inner.temperature(temperature);
        self
    }

    /// 追加工具定义。
    pub fn tool(mut self, tool: ChatToolDefinition) -> Self {
        self.inner = self.inner.tool(tool);
        self
    }

    /// 添加请求体字段。
    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
        self.inner = self.inner.extra_body(key, value);
        self
    }

    /// 添加 provider 选项。
    pub fn provider_option(
        mut self,
        key: impl Into<String>,
        value: impl Into<JsonPayload>,
    ) -> Self {
        self.inner = self.inner.provider_option(key, value);
        self
    }

    /// 添加额外请求头。
    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.inner.options.insert_header(key, value);
        self
    }

    /// 添加额外查询参数。
    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.inner.options.insert_query(key, value);
        self
    }

    /// 覆盖请求超时时间。
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.inner.options.timeout = Some(timeout);
        self
    }

    /// 覆盖最大重试次数。
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.inner.options.max_retries = Some(max_retries);
        self
    }

    /// 设置取消令牌。
    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
        self.inner.options.cancellation_token = Some(token);
        self
    }

    /// 按响应 ID 继续一个已有的 Responses SSE 流。
    pub fn response_id(mut self, response_id: impl Into<String>) -> Self {
        self.response_id = Some(response_id.into());
        self
    }

    /// 当继续已有流时,只消费给定序号之后的事件。
    pub fn starting_after(mut self, sequence_number: u64) -> Self {
        self.starting_after = Some(sequence_number);
        self
    }

    /// 发送流式 Responses 请求。
    ///
    /// # Errors
    ///
    /// 当参数校验失败、请求失败或流初始化失败时返回错误。
    pub async fn send(mut self) -> Result<ResponseStream> {
        let (client, spec) = if let Some(response_id) = self.response_id.take() {
            if self.inner.params.model.is_some()
                || self.inner.params.input.is_some()
                || self.inner.params.temperature.is_some()
                || !self.inner.params.tools.is_empty()
                || !self.inner.extra_body.is_empty()
                || !self.inner.provider_options.is_empty()
            {
                return Err(Error::InvalidConfig(
                    "按 response_id 继续流时,不应再设置创建期参数或请求体扩展字段".into(),
                ));
            }

            let client = self
                .inner
                .client
                .take()
                .ok_or_else(|| Error::InvalidConfig("Responses 构建器缺少客户端".into()))?;
            let mut spec = RequestSpec::new(
                "responses.stream.retrieve",
                Method::GET,
                format!("/responses/{}", encode_path_segment(response_id)),
            );
            spec.options = self.inner.options;
            spec.options.insert_query("stream", "true");
            if let Some(sequence_number) = self.starting_after {
                spec.options
                    .insert_query("starting_after", sequence_number.to_string());
            }
            (client, spec)
        } else {
            if self.starting_after.is_some() {
                return Err(Error::InvalidConfig(
                    "`starting_after` 只能与 `response_id` 一起使用".into(),
                ));
            }
            self.inner.build_spec(true)?
        };
        Ok(ResponseStream::new(client.execute_sse(spec).await?))
    }

    /// 发送流式 Responses 请求,并返回带高层语义事件的运行时流。
    ///
    /// # Errors
    ///
    /// 当参数校验失败、请求失败或流初始化失败时返回错误。
    pub async fn send_events(self) -> Result<ResponseEventStream> {
        Ok(self.send().await?.events())
    }
}

#[cfg(feature = "realtime")]
impl RealtimeSocketRequestBuilder {
    pub(crate) fn new(client: Client) -> Self {
        Self {
            client,
            model: None,
            options: RequestOptions::default(),
        }
    }

    /// 设置 Realtime 连接所使用的模型或 deployment。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// 添加额外请求头。
    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_header(key, value);
        self
    }

    /// 添加额外查询参数。
    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_query(key, value);
        self
    }

    /// 建立 Realtime WebSocket 连接。
    ///
    /// # Errors
    ///
    /// 当参数校验失败或握手失败时返回错误。
    pub async fn connect(self) -> Result<RealtimeSocket> {
        RealtimeSocket::connect(&self.client, self.model, self.options).await
    }
}

#[cfg(feature = "responses-ws")]
impl ResponsesSocketRequestBuilder {
    pub(crate) fn new(client: Client) -> Self {
        Self {
            client,
            options: RequestOptions::default(),
        }
    }

    /// 添加额外请求头。
    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_header(key, value);
        self
    }

    /// 添加额外查询参数。
    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_query(key, value);
        self
    }

    /// 建立 Responses WebSocket 连接。
    ///
    /// # Errors
    ///
    /// 当握手失败时返回错误。
    pub async fn connect(self) -> Result<ResponsesSocket> {
        ResponsesSocket::connect(&self.client, self.options).await
    }
}

impl ResponseCreateRequestBuilder {
    pub(crate) fn new(client: Client) -> Self {
        Self {
            client: Some(client),
            ..Self::default()
        }
    }

    /// 设置模型。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.params.model = Some(model.into());
        self
    }

    /// 直接设置输入文本。
    pub fn input_text(mut self, input: impl Into<String>) -> Self {
        self.params.input = Some(ResponseInputPayload::from(input.into()));
        self
    }

    /// 设置输入项数组。
    pub fn input_items(mut self, items: Vec<ResponseInputItemPayload>) -> Self {
        self.params.input = Some(ResponseInputPayload::from(items));
        self
    }

    /// 直接设置输入载荷。
    pub fn input(mut self, input: impl Into<ResponseInputPayload>) -> Self {
        self.params.input = Some(input.into());
        self
    }

    /// 设置温度。
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.params.temperature = Some(temperature);
        self
    }

    /// 追加工具定义。
    pub fn tool(mut self, tool: ChatToolDefinition) -> Self {
        self.params.tools.push(tool);
        self
    }

    /// 追加请求体字段。
    pub fn extra_body(mut self, key: impl Into<String>, value: impl Into<JsonPayload>) -> Self {
        self.extra_body.insert(key.into(), value.into().into_raw());
        self
    }

    /// 追加 provider 选项。
    pub fn provider_option(
        mut self,
        key: impl Into<String>,
        value: impl Into<JsonPayload>,
    ) -> Self {
        self.provider_options
            .insert(key.into(), value.into().into_raw());
        self
    }

    /// 添加额外请求头。
    pub fn extra_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_header(key, value);
        self
    }

    /// 添加额外查询参数。
    pub fn extra_query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.insert_query(key, value);
        self
    }

    /// 覆盖请求超时时间。
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.options.timeout = Some(timeout);
        self
    }

    /// 覆盖最大重试次数。
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.options.max_retries = Some(max_retries);
        self
    }

    /// 设置取消令牌。
    pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
        self.options.cancellation_token = Some(token);
        self
    }

    pub(crate) fn build_spec(mut self, stream: bool) -> Result<(Client, RequestSpec)> {
        let client = self
            .client
            .take()
            .ok_or_else(|| Error::InvalidConfig("Responses 构建器缺少客户端".into()))?;
        if self.params.model.as_deref().unwrap_or_default().is_empty() {
            return Err(Error::MissingRequiredField { field: "model" });
        }
        if self.params.input.is_none() {
            return Err(Error::MissingRequiredField { field: "input" });
        }

        self.params.stream = Some(stream);
        let provider_key = client.provider().kind().as_key();
        let mut body = merge_json_body(
            Some(value_from(&self.params)?),
            &self.extra_body,
            provider_key,
            &self.provider_options,
        );
        if !self.params.tools.is_empty()
            && let Some(object) = body.as_object_mut()
        {
            object.insert(
                "tools".into(),
                Value::Array(
                    self.params
                        .tools
                        .iter()
                        .map(ChatToolDefinition::as_response_tool_value)
                        .collect(),
                ),
            );
        }
        let mut spec = RequestSpec::new(
            if stream {
                "responses.stream"
            } else {
                "responses.create"
            },
            Method::POST,
            "/responses",
        );
        spec.body = Some(body);
        spec.options = self.options;
        Ok((client, spec))
    }

    /// 发送普通 Responses 请求。
    ///
    /// # Errors
    ///
    /// 当参数校验失败、请求失败或反序列化失败时返回错误。
    pub async fn send(self) -> Result<Response> {
        Ok(self.send_with_meta().await?.data)
    }

    /// 发送普通 Responses 请求并保留元信息。
    ///
    /// # Errors
    ///
    /// 当参数校验失败、请求失败或反序列化失败时返回错误。
    pub async fn send_with_meta(self) -> Result<ApiResponse<Response>> {
        let (client, spec) = self.build_spec(false)?;
        client.execute_json(spec).await
    }
}

/// 表示 Responses 结构化解析构建器。
#[cfg(feature = "structured-output")]
#[derive(Debug, Clone)]
pub struct ResponseParseRequestBuilder<T> {
    inner: ResponseCreateRequestBuilder,
    _marker: PhantomData<T>,
}

#[cfg(feature = "structured-output")]
impl<T> ResponseParseRequestBuilder<T> {
    pub(crate) fn new(client: Client) -> Self {
        Self {
            inner: ResponseCreateRequestBuilder::new(client),
            _marker: PhantomData,
        }
    }

    /// 设置模型。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    /// 设置输入文本。
    pub fn input_text(mut self, input: impl Into<String>) -> Self {
        self.inner = self.inner.input_text(input);
        self
    }

    /// 设置输入数组。
    pub fn input_items(mut self, items: Vec<ResponseInputItemPayload>) -> Self {
        self.inner = self.inner.input_items(items);
        self
    }
}

#[cfg(feature = "structured-output")]
impl<T> ResponseParseRequestBuilder<T>
where
    T: JsonSchema + serde::de::DeserializeOwned,
{
    /// 发送请求并解析结构化输出。
    ///
    /// # Errors
    ///
    /// 当响应缺少可解析文本或 JSON 解析失败时返回错误。
    pub async fn send(self) -> Result<ParsedResponse<T>> {
        let response = self.inner.send().await?;
        let output_text = response
            .output_text()
            .ok_or_else(|| Error::InvalidConfig("Responses 返回中缺少可解析文本".into()))?;
        let parsed = parse_json_payload(&output_text)?;
        Ok(ParsedResponse { response, parsed })
    }
}