linger-openai-sdk 0.1.1

Rust-native async SDK for OpenAI APIs with typed requests, streaming, uploads, retries, and pluggable transports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
use crate::error::{HeaderMap, LingerError};
use crate::transport::HttpRequest;
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::fmt;

/// EN: Request body for `POST /v1/realtime/calls`.
/// 中文:`POST /v1/realtime/calls` 的请求体。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeCallRequest {
    /// EN: WebRTC SDP offer generated by the caller.
    /// 中文:调用方生成的 WebRTC SDP offer。
    pub sdp: String,
    /// EN: Wire format used for the call creation request.
    /// 中文:创建 call 请求使用的传输格式。
    pub body_format: RealtimeCallBodyFormat,
    /// EN: Optional session configuration sent in multipart requests.
    /// 中文:multipart 请求中发送的可选 session 配置。
    pub session: Option<RealtimeSessionConfig>,
}

impl CreateRealtimeCallRequest {
    /// EN: Starts building a realtime call creation request.
    /// 中文:开始构建 realtime call 创建请求。
    pub fn builder() -> CreateRealtimeCallRequestBuilder {
        CreateRealtimeCallRequestBuilder::default()
    }

    pub(crate) fn apply_body(&self, request: &mut HttpRequest) -> Result<(), LingerError> {
        match self.body_format {
            RealtimeCallBodyFormat::Sdp => {
                request.insert_header("content-type", "application/sdp");
                request.set_body(Bytes::from(self.sdp.clone()));
            }
            RealtimeCallBodyFormat::Multipart => {
                let session = self
                    .session
                    .as_ref()
                    .map(serde_json::to_string)
                    .transpose()?;
                let boundary = realtime_multipart_boundary(&self.sdp, session.as_deref());
                request.insert_header(
                    "content-type",
                    format!("multipart/form-data; boundary={boundary}"),
                );
                request.set_body(self.multipart_body(&boundary, session.as_deref()));
            }
        }
        Ok(())
    }

    fn multipart_body(&self, boundary: &str, session: Option<&str>) -> Bytes {
        let mut body = Vec::new();
        push_typed_multipart_field(
            &mut body,
            boundary,
            "sdp",
            "application/sdp",
            self.sdp.as_bytes(),
        );
        if let Some(session) = session {
            push_typed_multipart_field(
                &mut body,
                boundary,
                "session",
                "application/json",
                session.as_bytes(),
            );
        }
        body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
        Bytes::from(body)
    }
}

/// EN: Wire body format for realtime call creation.
/// 中文:realtime call 创建请求的传输体格式。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RealtimeCallBodyFormat {
    /// EN: Send the SDP offer directly as `application/sdp`.
    /// 中文:直接以 `application/sdp` 发送 SDP offer。
    Sdp,
    /// EN: Send the SDP offer and optional session config as multipart fields.
    /// 中文:以 multipart 字段发送 SDP offer 和可选 session 配置。
    Multipart,
}

/// EN: Builder for realtime call creation requests.
/// 中文:realtime call 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeCallRequestBuilder {
    sdp: Option<String>,
    body_format: Option<RealtimeCallBodyFormat>,
    session: Option<RealtimeSessionConfig>,
}

impl CreateRealtimeCallRequestBuilder {
    /// EN: Sets the WebRTC SDP offer.
    /// 中文:设置 WebRTC SDP offer。
    pub fn sdp(mut self, sdp: impl Into<String>) -> Self {
        self.sdp = Some(sdp.into());
        self
    }

    /// EN: Sets the request wire body format.
    /// 中文:设置请求传输体格式。
    pub fn body_format(mut self, body_format: RealtimeCallBodyFormat) -> Self {
        self.body_format = Some(body_format);
        self
    }

    /// EN: Sets the optional session configuration for multipart requests.
    /// 中文:为 multipart 请求设置可选 session 配置。
    pub fn session(mut self, session: RealtimeSessionConfig) -> Self {
        self.session = Some(session);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateRealtimeCallRequest, LingerError> {
        let body_format = self
            .body_format
            .unwrap_or(RealtimeCallBodyFormat::Multipart);
        if body_format == RealtimeCallBodyFormat::Sdp && self.session.is_some() {
            return Err(LingerError::invalid_config(
                "session requires multipart body format",
            ));
        }
        Ok(CreateRealtimeCallRequest {
            sdp: required_string("sdp", self.sdp)?,
            body_format,
            session: self.session,
        })
    }
}

/// EN: SDP answer returned by `POST /v1/realtime/calls`.
/// 中文:`POST /v1/realtime/calls` 返回的 SDP answer。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RealtimeCallSdpAnswer {
    /// EN: SDP answer produced by OpenAI for the peer connection.
    /// 中文:OpenAI 为 peer connection 生成的 SDP answer。
    pub sdp: String,
    /// EN: Relative call URL from the `Location` response header, when present.
    /// 中文:`Location` 响应头中的相对 call URL,如存在。
    pub location: Option<String>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    request_id: Option<RequestId>,
}

impl RealtimeCallSdpAnswer {
    pub(crate) fn from_parts(
        headers: &HeaderMap,
        request_id: Option<RequestId>,
        body: Bytes,
    ) -> Result<Self, LingerError> {
        let sdp = String::from_utf8(body.to_vec())
            .map_err(|error| LingerError::serialization(error.to_string()))?;
        Ok(Self {
            sdp,
            location: headers.get("location").map(str::to_owned),
            request_id,
        })
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Request body for `POST /v1/realtime/calls/{call_id}/refer`.
/// 中文:`POST /v1/realtime/calls/{call_id}/refer` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateRealtimeCallReferRequest {
    /// EN: SIP Refer-To URI for the transfer destination.
    /// 中文:转接目标的 SIP Refer-To URI。
    pub target_uri: String,
}

impl CreateRealtimeCallReferRequest {
    /// EN: Starts building a realtime call refer request.
    /// 中文:开始构建 realtime call refer 请求。
    pub fn builder() -> CreateRealtimeCallReferRequestBuilder {
        CreateRealtimeCallReferRequestBuilder::default()
    }
}

/// EN: Builder for realtime call refer requests.
/// 中文:realtime call refer 请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeCallReferRequestBuilder {
    target_uri: Option<String>,
}

impl CreateRealtimeCallReferRequestBuilder {
    /// EN: Sets the destination URI for the SIP REFER request.
    /// 中文:设置 SIP REFER 请求的目标 URI。
    pub fn target_uri(mut self, target_uri: impl Into<String>) -> Self {
        self.target_uri = Some(target_uri.into());
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateRealtimeCallReferRequest, LingerError> {
        Ok(CreateRealtimeCallReferRequest {
            target_uri: required_string("target_uri", self.target_uri)?,
        })
    }
}

/// EN: Request body for `POST /v1/realtime/calls/{call_id}/reject`.
/// 中文:`POST /v1/realtime/calls/{call_id}/reject` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct RejectRealtimeCallRequest {
    /// EN: Optional SIP response code to send back to the caller.
    /// 中文:可选的 SIP 响应码,用于返回给呼叫方。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
}

impl RejectRealtimeCallRequest {
    /// EN: Starts building a realtime call reject request.
    /// 中文:开始构建 realtime call reject 请求。
    pub fn builder() -> RejectRealtimeCallRequestBuilder {
        RejectRealtimeCallRequestBuilder::default()
    }
}

/// EN: Builder for realtime call reject requests.
/// 中文:realtime call reject 请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RejectRealtimeCallRequestBuilder {
    status_code: Option<u16>,
}

impl RejectRealtimeCallRequestBuilder {
    /// EN: Sets the SIP response code to send back to the caller.
    /// 中文:设置返回给呼叫方的 SIP 响应码。
    pub fn status_code(mut self, status_code: u16) -> Self {
        self.status_code = Some(status_code);
        self
    }

    /// EN: Builds the request.
    /// 中文:构建请求。
    pub fn build(self) -> Result<RejectRealtimeCallRequest, LingerError> {
        Ok(RejectRealtimeCallRequest {
            status_code: self.status_code,
        })
    }
}

/// EN: Request body for `POST /v1/realtime/sessions`.
/// 中文:`POST /v1/realtime/sessions` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeSessionRequest {
    /// EN: Realtime model used for the session.
    /// 中文:此会话使用的 realtime 模型。
    pub model: String,
    /// EN: Forward-compatible optional session fields.
    /// 中文:前向兼容的可选会话字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateRealtimeSessionRequest {
    /// EN: Starts building a realtime session request.
    /// 中文:开始构建 realtime session 请求。
    pub fn builder() -> CreateRealtimeSessionRequestBuilder {
        CreateRealtimeSessionRequestBuilder::default()
    }
}

/// EN: Builder for realtime session creation requests.
/// 中文:realtime session 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeSessionRequestBuilder {
    model: Option<String>,
    extra: BTreeMap<String, Value>,
}

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

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

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

/// EN: Request body for `POST /v1/realtime/transcription_sessions`.
/// 中文:`POST /v1/realtime/transcription_sessions` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeTranscriptionSessionRequest {
    /// EN: Forward-compatible transcription session fields.
    /// 中文:前向兼容的 transcription session 字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateRealtimeTranscriptionSessionRequest {
    /// EN: Starts building a realtime transcription session request.
    /// 中文:开始构建 realtime transcription session 请求。
    pub fn builder() -> CreateRealtimeTranscriptionSessionRequestBuilder {
        CreateRealtimeTranscriptionSessionRequestBuilder::default()
    }
}

/// EN: Builder for realtime transcription session creation requests.
/// 中文:realtime transcription session 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeTranscriptionSessionRequestBuilder {
    extra: BTreeMap<String, Value>,
}

impl CreateRealtimeTranscriptionSessionRequestBuilder {
    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

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

/// EN: Translation session config for `POST /v1/realtime/translations/client_secrets`.
/// 中文:`POST /v1/realtime/translations/client_secrets` 的 translation session 配置。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeTranslationSessionRequest {
    /// EN: Realtime translation model used for the session.
    /// 中文:此 session 使用的 realtime translation 模型。
    pub model: String,
    /// EN: Forward-compatible translation session fields.
    /// 中文:前向兼容的 translation session 字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateRealtimeTranslationSessionRequest {
    /// EN: Starts building a realtime translation session request.
    /// 中文:开始构建 realtime translation session 请求。
    pub fn builder() -> CreateRealtimeTranslationSessionRequestBuilder {
        CreateRealtimeTranslationSessionRequestBuilder::default()
    }
}

/// EN: Builder for realtime translation session configs.
/// 中文:realtime translation session 配置的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeTranslationSessionRequestBuilder {
    model: Option<String>,
    extra: BTreeMap<String, Value>,
}

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

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

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

/// EN: Request body for `POST /v1/realtime/translations/client_secrets`.
/// 中文:`POST /v1/realtime/translations/client_secrets` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeTranslationClientSecretRequest {
    /// EN: Translation session configuration.
    /// 中文:Translation session 配置。
    pub session: CreateRealtimeTranslationSessionRequest,
    /// EN: Forward-compatible client secret fields such as expiration settings.
    /// 中文:前向兼容的 client secret 字段,例如过期设置。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateRealtimeTranslationClientSecretRequest {
    /// EN: Starts building a realtime translation client secret request.
    /// 中文:开始构建 realtime translation client secret 请求。
    pub fn builder() -> CreateRealtimeTranslationClientSecretRequestBuilder {
        CreateRealtimeTranslationClientSecretRequestBuilder::default()
    }
}

/// EN: Builder for realtime translation client secret requests.
/// 中文:realtime translation client secret 请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeTranslationClientSecretRequestBuilder {
    session: Option<CreateRealtimeTranslationSessionRequest>,
    extra: BTreeMap<String, Value>,
}

impl CreateRealtimeTranslationClientSecretRequestBuilder {
    /// EN: Sets the translation session configuration.
    /// 中文:设置 translation session 配置。
    pub fn session(mut self, session: CreateRealtimeTranslationSessionRequest) -> Self {
        self.session = Some(session);
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateRealtimeTranslationClientSecretRequest, LingerError> {
        validate_extra_fields(&self.extra)?;
        Ok(CreateRealtimeTranslationClientSecretRequest {
            session: self
                .session
                .ok_or_else(|| LingerError::invalid_config("session is required"))?,
            extra: self.extra,
        })
    }
}

/// EN: Request body for `POST /v1/realtime/client_secrets`.
/// 中文:`POST /v1/realtime/client_secrets` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateRealtimeClientSecretRequest {
    /// EN: Realtime or transcription session configuration.
    /// 中文:Realtime 或转录会话配置。
    pub session: RealtimeSessionConfig,
}

impl CreateRealtimeClientSecretRequest {
    /// EN: Starts building a realtime client secret creation request.
    /// 中文:开始构建 realtime client secret 创建请求。
    pub fn builder() -> CreateRealtimeClientSecretRequestBuilder {
        CreateRealtimeClientSecretRequestBuilder::default()
    }
}

/// EN: Builder for realtime client secret creation requests.
/// 中文:realtime client secret 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateRealtimeClientSecretRequestBuilder {
    session: Option<RealtimeSessionConfig>,
}

impl CreateRealtimeClientSecretRequestBuilder {
    /// EN: Sets the session configuration.
    /// 中文:设置会话配置。
    pub fn session(mut self, session: RealtimeSessionConfig) -> Self {
        self.session = Some(session);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateRealtimeClientSecretRequest, LingerError> {
        Ok(CreateRealtimeClientSecretRequest {
            session: self
                .session
                .ok_or_else(|| LingerError::invalid_config("session is required"))?,
        })
    }
}

/// EN: Forward-compatible realtime session configuration.
/// 中文:前向兼容的 realtime 会话配置。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct RealtimeSessionConfig {
    /// EN: Session kind, for example `realtime` or `transcription`.
    /// 中文:会话类型,例如 `realtime` 或 `transcription`。
    #[serde(rename = "type")]
    pub kind: String,
    /// EN: Optional realtime model.
    /// 中文:可选的 realtime 模型。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl RealtimeSessionConfig {
    /// EN: Starts building a session config with the documented session type.
    /// 中文:使用文档中的会话类型开始构建会话配置。
    pub fn builder(kind: impl Into<String>) -> RealtimeSessionConfigBuilder {
        RealtimeSessionConfigBuilder {
            kind: Some(kind.into()),
            model: None,
            extra: BTreeMap::new(),
        }
    }
}

/// EN: Builder for realtime session configuration.
/// 中文:realtime 会话配置的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RealtimeSessionConfigBuilder {
    kind: Option<String>,
    model: Option<String>,
    extra: BTreeMap<String, Value>,
}

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

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加一个前向兼容 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the session configuration.
    /// 中文:构建并校验会话配置。
    pub fn build(self) -> Result<RealtimeSessionConfig, LingerError> {
        validate_optional_string("model", self.model.as_deref())?;
        validate_extra_fields(&self.extra)?;
        Ok(RealtimeSessionConfig {
            kind: required_string("type", self.kind)?,
            model: self.model,
            extra: self.extra,
        })
    }
}

/// EN: Realtime client secret response.
/// 中文:Realtime client secret 响应。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct RealtimeClientSecret {
    /// EN: Ephemeral client secret value.
    /// 中文:临时 client secret 值。
    pub value: RealtimeClientSecretValue,
    /// EN: Unix timestamp for expiration, when returned.
    /// 中文:响应中存在时的过期 Unix 时间戳。
    #[serde(default)]
    pub expires_at: Option<u64>,
    /// EN: Session configuration returned by the API.
    /// 中文:API 返回的会话配置。
    #[serde(default)]
    pub session: Value,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl RealtimeClientSecret {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Realtime session response with an ephemeral client secret.
/// 中文:包含临时 client secret 的 realtime session 响应。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct RealtimeSession {
    /// EN: Realtime session id.
    /// 中文:Realtime session ID。
    pub id: String,
    /// EN: API object type, normally `realtime.session`.
    /// 中文:API 对象类型,通常为 `realtime.session`。
    pub object: String,
    /// EN: Realtime model used for the session.
    /// 中文:此会话使用的 realtime 模型。
    pub model: String,
    /// EN: Ephemeral client secret for client-side Realtime authentication.
    /// 中文:用于客户端 Realtime 认证的临时 client secret。
    pub client_secret: RealtimeClientSecret,
    /// EN: Additional response fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外响应字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl RealtimeSession {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Realtime transcription session response.
/// 中文:Realtime transcription session 响应。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct RealtimeTranscriptionSession {
    /// EN: Realtime transcription session id, when returned.
    /// 中文:返回时的 realtime transcription session ID。
    #[serde(default)]
    pub id: Option<String>,
    /// EN: API object type, normally `realtime.transcription_session`.
    /// 中文:API 对象类型,通常为 `realtime.transcription_session`。
    #[serde(default)]
    pub object: Option<String>,
    /// EN: Ephemeral client secret, when returned by the API.
    /// 中文:API 返回时的临时 client secret。
    #[serde(default)]
    pub client_secret: Option<RealtimeClientSecret>,
    /// EN: Additional response fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外响应字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl RealtimeTranscriptionSession {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Realtime translation client secret response.
/// 中文:Realtime translation client secret 响应。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct RealtimeTranslationClientSecret {
    /// EN: Ephemeral translation client secret value.
    /// 中文:临时 translation client secret 值。
    pub value: RealtimeClientSecretValue,
    /// EN: Unix timestamp for client secret expiration.
    /// 中文:client secret 过期的 Unix 时间戳。
    pub expires_at: u64,
    /// EN: Translation session returned by the API.
    /// 中文:API 返回的 translation session。
    pub session: Value,
    /// EN: Additional response fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外响应字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl RealtimeTranslationClientSecret {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Redacted wrapper for ephemeral realtime client secret values.
/// 中文:临时 realtime client secret 值的脱敏包装。
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(transparent)]
#[non_exhaustive]
pub struct RealtimeClientSecretValue(String);

impl RealtimeClientSecretValue {
    /// EN: Returns the raw secret value for callers that need to pass it to a client.
    /// 中文:返回原始 secret 值,供需要传给客户端的调用方使用。
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for RealtimeClientSecretValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("\"<redacted>\"")
    }
}

fn required_string(name: &str, value: Option<String>) -> Result<String, LingerError> {
    value
        .filter(|value| !value.trim().is_empty())
        .ok_or_else(|| LingerError::invalid_config(format!("{name} is required")))
}

fn validate_optional_string(name: &str, value: Option<&str>) -> Result<(), LingerError> {
    if value.is_some_and(|value| value.trim().is_empty()) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not be empty"
        )));
    }
    Ok(())
}

fn validate_extra_fields(extra: &BTreeMap<String, Value>) -> Result<(), LingerError> {
    for (key, value) in extra {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "extra field names must not be empty",
            ));
        }
        if value.is_null() {
            return Err(LingerError::invalid_config(format!(
                "extra field {key} must not be null"
            )));
        }
    }
    Ok(())
}

fn push_typed_multipart_field(
    body: &mut Vec<u8>,
    boundary: &str,
    name: &str,
    content_type: &str,
    value: &[u8],
) {
    body.extend_from_slice(
        format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\nContent-Type: {content_type}\r\n\r\n"
        )
        .as_bytes(),
    );
    body.extend_from_slice(value);
    body.extend_from_slice(b"\r\n");
}

fn realtime_multipart_boundary(sdp: &str, session: Option<&str>) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-realtime-boundary-{counter}");
        let boundary_bytes = boundary.as_bytes();
        let conflicts_with_sdp = contains_bytes(sdp.as_bytes(), boundary_bytes);
        let conflicts_with_session =
            session.is_some_and(|session| contains_bytes(session.as_bytes(), boundary_bytes));
        if !conflicts_with_sdp && !conflicts_with_session {
            return boundary;
        }
    }
    unreachable!("unbounded boundary counter")
}

fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}