deepgram 0.14.0

Community Rust SDK for Deepgram's automated speech recognition APIs.
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
#![forbid(unsafe_code)]
#![warn(missing_debug_implementations, missing_docs, clippy::cargo)]
#![allow(clippy::multiple_crate_versions, clippy::derive_partial_eq_without_eq)]

//! Official Rust SDK for Deepgram's automated speech recognition APIs.
//!
//! Get started transcribing with a [`Transcription`] object.
//!
//! # Cargo features
//!
//! - `listen` (default): speech-to-text, REST and WebSocket, including Flux.
//! - `speak` (default): text-to-speech, REST and WebSocket, including Flux.
//! - `manage` (default): project, key, and usage management.
//! - `read` (default): Text Intelligence over `/v1/read`; see the `read` module.
//! - `agent` (default): the Voice Agent WebSocket client; see the `agent` module.
//! - `connect-diagnostics`: per-phase connect timings for `/v1/listen`
//!   WebSocket connections; see the `diagnostics` module.
//! - `rustls-tls-native-roots`: also trust the operating system's certificate
//!   store for `wss://` WebSocket connections, on top of the bundled public
//!   roots. For
//!   TLS-inspecting proxies, internal CAs, and self-hosted deployments; see
//!   the `tls` module.

use core::fmt;
pub use http::Error as HttpError;
pub use reqwest::Error as ReqwestError;
pub use serde_json::Error as SerdeJsonError;
pub use serde_urlencoded::ser::Error as SerdeUrlencodedError;
use std::io;
use std::ops::Deref;
#[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
pub use tungstenite::Error as TungsteniteError;

use reqwest::{
    header::{HeaderMap, HeaderValue},
    RequestBuilder,
};
use serde::de::DeserializeOwned;
use thiserror::Error;
use url::Url;

#[cfg(feature = "agent")]
pub mod agent;
pub mod auth;
#[cfg(any(feature = "listen", feature = "read"))]
pub mod common;
#[cfg(feature = "connect-diagnostics")]
pub mod diagnostics;
#[cfg(feature = "listen")]
pub mod listen;
#[cfg(feature = "manage")]
pub mod manage;
#[cfg(feature = "read")]
pub mod read;
#[cfg(feature = "speak")]
pub mod speak;
#[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
pub mod tls;

/// The `rustls` crate this SDK's WebSocket connections are built on,
/// re-exported so a [`rustls::ClientConfig`] passed to
/// [`Deepgram::tls_config`] is guaranteed to be the matching version.
///
/// This ties the SDK's public API to rustls 0.23: a future rustls major
/// bump will be a breaking change for this crate as well.
#[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
pub use rustls;

#[cfg(feature = "listen")]
pub use listen::websocket::TranscriptionStream;
#[cfg(feature = "read")]
pub use read::TextIntelligence;

static DEEPGRAM_BASE_URL: &str = "https://api.deepgram.com";

/// The `Host` header for a WebSocket handshake to `url`: the authority
/// without userinfo, so the host plus the port whenever the port is not
/// the scheme default. `url::Url::host_str` already brackets IPv6
/// literals, and `url::Url::port` is `None` for a default port (80 for
/// `ws`, 443 for `wss`), so `wss://api.deepgram.com/v1/listen` gives
/// `api.deepgram.com` and `ws://127.0.0.1:54321/v1/listen` gives
/// `127.0.0.1:54321`. Every WebSocket surface uses this so a self-hosted
/// or proxied deployment on a non-default port is routed by its full
/// authority.
#[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
pub(crate) fn websocket_host_header(url: &Url) -> Option<String> {
    let host = url.host_str()?;
    Some(match url.port() {
        Some(port) => format!("{host}:{port}"),
        None => host.to_owned(),
    })
}

#[cfg(all(test, any(feature = "listen", feature = "speak", feature = "agent")))]
mod websocket_host_header_tests {
    use super::websocket_host_header;
    use url::Url;

    fn parse(s: &str) -> Url {
        s.parse().expect("valid URL")
    }

    #[test]
    fn includes_a_non_default_port() {
        assert_eq!(
            websocket_host_header(&parse("ws://127.0.0.1:54321/v1/listen")).as_deref(),
            Some("127.0.0.1:54321")
        );
        assert_eq!(
            websocket_host_header(&parse("wss://dg.internal.example:8443/v1/listen")).as_deref(),
            Some("dg.internal.example:8443")
        );
    }

    #[test]
    fn omits_the_scheme_default_port() {
        assert_eq!(
            websocket_host_header(&parse("wss://api.deepgram.com/v1/listen")).as_deref(),
            Some("api.deepgram.com")
        );
        assert_eq!(
            websocket_host_header(&parse("wss://api.deepgram.com:443/v1/listen")).as_deref(),
            Some("api.deepgram.com")
        );
        assert_eq!(
            websocket_host_header(&parse("ws://localhost:80/v1/listen")).as_deref(),
            Some("localhost")
        );
    }

    #[test]
    fn keeps_ipv6_brackets() {
        assert_eq!(
            websocket_host_header(&parse("ws://[::1]:9000/v1/listen")).as_deref(),
            Some("[::1]:9000")
        );
        assert_eq!(
            websocket_host_header(&parse("wss://[2001:db8::1]:8443/v1/listen")).as_deref(),
            Some("[2001:db8::1]:8443")
        );
    }

    #[test]
    fn drops_userinfo() {
        assert_eq!(
            websocket_host_header(&parse("wss://user:secret@dg.example:8443/v1/listen")).as_deref(),
            Some("dg.example:8443")
        );
    }
}

pub(crate) static USER_AGENT: &str = concat!(
    env!("CARGO_PKG_NAME"),
    "/",
    env!("CARGO_PKG_VERSION"),
    " rust",
);

/// Transcribe audio using Deepgram's automated speech recognition.
///
/// Constructed using [`Deepgram::transcription`].
///
/// See the [Deepgram API Reference][api] for more info.
///
/// [api]: https://developers.deepgram.com/api-reference/#transcription
#[derive(Debug, Clone)]
pub struct Transcription<'a>(#[allow(unused)] pub &'a Deepgram);

/// Generate speech from text using Deepgram's text to speech api.
///
/// Constructed using [`Deepgram::text_to_speech`].
///
/// See the [Deepgram API Reference][api] for more info.
///
/// [api]: https://developers.deepgram.com/reference/text-to-speech-api
#[derive(Debug, Clone)]
pub struct Speak<'a>(#[allow(unused)] pub &'a Deepgram);

impl Deepgram {
    /// Construct a new [`Transcription`] from a [`Deepgram`].
    pub fn transcription(&self) -> Transcription<'_> {
        self.into()
    }

    /// Construct a new [`Speak`] from a [`Deepgram`].
    pub fn text_to_speech(&self) -> Speak<'_> {
        self.into()
    }
}

impl<'a> From<&'a Deepgram> for Transcription<'a> {
    /// Construct a new [`Transcription`] from a [`Deepgram`].
    fn from(deepgram: &'a Deepgram) -> Self {
        Self(deepgram)
    }
}

impl<'a> From<&'a Deepgram> for Speak<'a> {
    /// Construct a new [`Speak`] from a [`Deepgram`].
    fn from(deepgram: &'a Deepgram) -> Self {
        Self(deepgram)
    }
}

impl Transcription<'_> {
    /// Expose a method to access the inner `Deepgram` reference if needed.
    pub fn deepgram(&self) -> &Deepgram {
        self.0
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
/// A string wrapper that redacts its contents when formatted with `Debug`.
pub(crate) struct RedactedString(pub String);

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

impl Deref for RedactedString {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Authentication method for Deepgram API requests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AuthMethod {
    /// Use an API key with "Token" prefix (e.g., "Token dg_xxx").
    /// This is for permanent API keys created in the Deepgram console.
    ApiKey(RedactedString),

    /// Use a temporary token with "Bearer" prefix (e.g., "Bearer dg_xxx").
    /// This is for temporary tokens obtained via token-based authentication.
    TempToken(RedactedString),
}

impl AuthMethod {
    /// Get the authorization header value for this authentication method.
    pub(crate) fn header_value(&self) -> String {
        match self {
            AuthMethod::ApiKey(key) => format!("Token {}", key.0),
            AuthMethod::TempToken(token) => format!("Bearer {}", token.0),
        }
    }
}

/// A client for the Deepgram API.
///
/// Make transcriptions requests using [`Deepgram::transcription`].
#[derive(Debug, Clone)]
pub struct Deepgram {
    #[cfg_attr(not(feature = "listen"), allow(unused))]
    auth: Option<AuthMethod>,
    #[cfg_attr(not(feature = "listen"), allow(unused))]
    base_url: Url,
    #[cfg_attr(not(feature = "listen"), allow(unused))]
    client: reqwest::Client,
    #[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
    tls: tls::TlsSettings,
}

/// Errors that may arise from the [`deepgram`](crate) crate.
// TODO sub-errors for the different types?
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DeepgramError {
    /// The Deepgram API returned an error.
    #[error("The Deepgram API returned an error.")]
    DeepgramApiError {
        /// Error message from the Deepgram API.
        body: String,

        /// Underlying [`reqwest::Error`] from the HTTP request.
        err: ReqwestError,
    },

    /// Something went wrong when generating the http request.
    #[error("Something went wrong when generating the http request: {0}")]
    HttpError(#[from] HttpError),

    /// Something went wrong when making the HTTP request.
    #[error("Something went wrong when making the HTTP request: {0}")]
    ReqwestError(#[from] ReqwestError),

    /// Something went wrong during I/O.
    #[error("Something went wrong during I/O: {0}")]
    IoError(#[from] io::Error),

    #[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
    /// Something went wrong with WS.
    #[error("Something went wrong with WS: {0}")]
    WsError(#[from] Box<TungsteniteError>),

    /// The server presented a TLS certificate whose issuer is not among this
    /// client's trust roots, so the WebSocket handshake was refused.
    ///
    /// Typical causes are a TLS-inspecting corporate proxy re-signing
    /// traffic, an internal CA, or a self-hosted deployment. The message
    /// ends with the remedy that applies to the trust roots in effect: the
    /// `rustls-tls-native-roots` cargo feature, or [`Deepgram::tls_config`].
    /// See [`tls`] for the full picture.
    #[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
    #[error("TLS certificate presented by {host} is not trusted ({source}). {}", tls::untrusted_hint(.trust))]
    UntrustedTlsCertificate {
        /// The host the connection was made to.
        host: String,
        /// The trust roots that were in effect for the attempt.
        trust: tls::TlsTrust,
        /// The underlying handshake error.
        #[source]
        source: Box<TungsteniteError>,
    },

    /// Something went wrong during serialization/deserialization.
    #[error("Something went wrong during json serialization/deserialization: {0}")]
    JsonError(#[from] SerdeJsonError),

    /// Something went wrong during serialization/deserialization.
    #[error("Something went wrong during query serialization: {0}")]
    UrlencodedError(#[from] SerdeUrlencodedError),

    /// The data stream produced an error
    #[error("The data stream produced an error: {0}")]
    StreamError(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),

    /// The provided base url is not valid
    #[error("The provided base url is not valid")]
    InvalidUrl,

    /// The provided options are not valid for the requested transport
    /// or endpoint.
    #[error("The provided options are not valid for this request: {0}")]
    InvalidOptions(String),

    /// A websocket close from was received indicating an error
    #[error("websocket close frame received with error content: code: {code}, reason: {reason}")]
    WebsocketClose {
        /// The numerical code indicating the reason for the error
        code: u16,
        /// A textual description of the error reason
        reason: String,
    },

    /// [`Agent::start_at_url`](crate::agent::Agent::start_at_url) was
    /// asked to open a cleartext (`ws://`) Voice Agent session to a host
    /// that is not loopback, so the request was refused before any
    /// connection was attempted and the credential was never sent.
    ///
    /// The payload's `url` field is the rejected origin only
    /// (`scheme://host[:port]`) — path, query, and userinfo are omitted
    /// so the error is safe to log.
    #[cfg(feature = "agent")]
    #[error(transparent)]
    InsecureAgentUrl(#[from] agent::InsecureAgentUrl),

    /// An unexpected error occurred in the client
    #[error("an unepected error occurred in the deepgram client: {0}")]
    InternalClientError(anyhow::Error),

    /// A Deepgram API server response was not in the expected format.
    #[error("The Deepgram API server response was not in the expected format: {0}")]
    UnexpectedServerResponse(anyhow::Error),
}

#[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
impl From<TungsteniteError> for DeepgramError {
    fn from(err: TungsteniteError) -> Self {
        Self::from(Box::new(err))
    }
}

#[cfg_attr(not(feature = "listen"), allow(unused))]
type Result<T, E = DeepgramError> = std::result::Result<T, E>;

impl Deepgram {
    /// Construct a new Deepgram client.
    ///
    /// The client will be pointed at Deepgram's hosted API.
    ///
    /// Create your first API key on the [Deepgram Console][console].
    ///
    /// [console]: https://console.deepgram.com/
    ///
    /// # Errors
    ///
    /// Errors under the same conditions as [`reqwest::ClientBuilder::build`].
    pub fn new<K: AsRef<str>>(api_key: K) -> Result<Self> {
        let auth = AuthMethod::ApiKey(RedactedString(api_key.as_ref().to_owned()));
        // This cannot panic because we are converting a static value
        // that is known-good.
        let base_url = DEEPGRAM_BASE_URL.try_into().unwrap();
        Self::inner_constructor(base_url, Some(auth))
    }

    /// Construct a new Deepgram client with a temporary token.
    ///
    /// This uses the "Bearer" prefix for authentication, suitable for temporary tokens.
    pub fn with_temp_token<T: AsRef<str>>(temp_token: T) -> Result<Self> {
        let auth = AuthMethod::TempToken(RedactedString(temp_token.as_ref().to_owned()));
        let base_url = DEEPGRAM_BASE_URL.try_into().unwrap();
        Self::inner_constructor(base_url, Some(auth))
    }

    /// Construct a new Deepgram client with the specified base URL.
    ///
    /// When using a self-hosted instance of deepgram, this will be the
    /// host portion of your own instance. For instance, if you would
    /// query your deepgram instance at `http://deepgram.internal/v1/listen`,
    /// the base_url will be `http://deepgram.internal`.
    ///
    /// A base URL that carries a path of its own must end in a slash.
    /// Endpoint paths are resolved against it with `Url::join`, which
    /// replaces the last segment of a path that does not end in one:
    /// `http://deepgram.internal/abc/` resolves to
    /// `http://deepgram.internal/abc/v1/listen`, while
    /// `http://deepgram.internal/abc` resolves to
    /// `http://deepgram.internal/v1/listen` and drops the `abc`.
    ///
    /// Every request this client makes goes to this base URL, including the
    /// management API (projects, keys, members, scopes, invitations, usage,
    /// and billing) and the token grant in [`crate::auth`]. To reach
    /// Deepgram's hosted management or auth API while your audio goes
    /// elsewhere, build a second client with [`Deepgram::new`] and make
    /// those calls on that one.
    ///
    /// A base URL that carries a path prefix must end in a slash to keep it.
    /// Endpoint paths are joined on by RFC 3986 relative resolution, which
    /// replaces the last segment of a path that does not end in one: with
    /// `http://gateway.internal/deepgram/`, `projects().list()` goes to
    /// `http://gateway.internal/deepgram/v1/projects`, while with
    /// `http://gateway.internal/deepgram` it goes to
    /// `http://gateway.internal/v1/projects` and the prefix is silently
    /// dropped. A base URL with no path of its own
    /// (`http://deepgram.internal`) needs no trailing slash.
    ///
    /// Self-hosted instances do not in general authenticate incoming
    /// requests, so unlike in [`Deepgram::new`], so no api key needs to be
    /// provided. The SDK will not include an `Authorization` header in its
    /// requests. If an API key is required, consider using
    /// [`Deepgram::with_base_url_and_api_key`].
    ///
    /// The base URL's scheme decides how WebSocket connections are made:
    /// `https://` gives `wss://`, with TLS and certificate verification (see
    /// the `tls` module); `http://` gives plaintext `ws://`, with neither, so
    /// credentials and audio travel unencrypted. Use `http://` only for local
    /// testing (as in the example below) and prefer `https://` whenever an
    /// API key, a temporary token, or private traffic is involved.
    ///
    /// [console]: https://console.deepgram.com/
    ///
    /// # Example:
    ///
    /// ```
    /// # use deepgram::Deepgram;
    /// let deepgram = Deepgram::with_base_url(
    ///     "http://localhost:8080",
    /// );
    /// ```
    ///
    /// # Errors
    ///
    /// Errors under the same conditions as [`reqwest::Client::new`], or if `base_url`
    /// is not a valid URL.
    pub fn with_base_url<U>(base_url: U) -> Result<Self>
    where
        U: TryInto<Url>,
        U::Error: std::fmt::Debug,
    {
        let base_url = base_url.try_into().map_err(|_| DeepgramError::InvalidUrl)?;
        Self::inner_constructor(base_url, None)
    }

    /// Construct a new Deepgram client with the specified base URL and
    /// API Key.
    ///
    /// When using a self-hosted instance of deepgram, this will be the
    /// host portion of your own instance. For instance, if you would
    /// query your deepgram instance at `http://deepgram.internal/v1/listen`,
    /// the base_url will be `http://deepgram.internal`.
    ///
    /// A base URL that carries a path of its own must end in a slash.
    /// Endpoint paths are resolved against it with `Url::join`, which
    /// replaces the last segment of a path that does not end in one:
    /// `http://deepgram.internal/abc/` resolves to
    /// `http://deepgram.internal/abc/v1/listen`, while
    /// `http://deepgram.internal/abc` resolves to
    /// `http://deepgram.internal/v1/listen` and drops the `abc`.
    ///
    /// Every request this client makes goes to this base URL, including the
    /// management API (projects, keys, members, scopes, invitations, usage,
    /// and billing) and the token grant in [`crate::auth`], and it carries
    /// `api_key` with it. To reach Deepgram's hosted management or auth API
    /// while your audio goes elsewhere, build a second client with
    /// [`Deepgram::new`] and make those calls on that one.
    ///
    /// A base URL that carries a path prefix must end in a slash to keep it.
    /// Endpoint paths are joined on by RFC 3986 relative resolution, which
    /// replaces the last segment of a path that does not end in one: with
    /// `http://gateway.internal/deepgram/`, `projects().list()` goes to
    /// `http://gateway.internal/deepgram/v1/projects`, while with
    /// `http://gateway.internal/deepgram` it goes to
    /// `http://gateway.internal/v1/projects` and the prefix is silently
    /// dropped. A base URL with no path of its own
    /// (`http://deepgram.internal`) needs no trailing slash.
    ///
    /// The base URL's scheme decides how WebSocket connections are made:
    /// `https://` gives `wss://`, with TLS and certificate verification (see
    /// the `tls` module); `http://` gives plaintext `ws://`, with neither, so
    /// credentials and audio travel unencrypted. Use `http://` only for local
    /// testing (as in the example below) and prefer `https://` whenever an
    /// API key, a temporary token, or private traffic is involved.
    ///
    /// [console]: https://console.deepgram.com/
    ///
    /// # Example:
    ///
    /// ```
    /// # use deepgram::Deepgram;
    /// let deepgram = Deepgram::with_base_url_and_api_key(
    ///     "http://localhost:8080",
    ///     "apikey12345",
    /// ).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Errors under the same conditions as [`reqwest::ClientBuilder::build`], or if `base_url`
    /// is not a valid URL.
    pub fn with_base_url_and_api_key<U, K>(base_url: U, api_key: K) -> Result<Self>
    where
        U: TryInto<Url>,
        U::Error: std::fmt::Debug,
        K: AsRef<str>,
    {
        let base_url = base_url.try_into().map_err(|_| DeepgramError::InvalidUrl)?;
        let auth = AuthMethod::ApiKey(RedactedString(api_key.as_ref().to_owned()));
        Self::inner_constructor(base_url, Some(auth))
    }

    /// Construct a new Deepgram client with the specified base URL and temp token.
    ///
    /// As with [`Deepgram::with_base_url_and_api_key`], every request this
    /// client makes goes to this base URL, including the management API and
    /// the token grant in [`crate::auth`], and it carries `temp_token` with
    /// it. And as there, a base URL that carries a path prefix must end in a
    /// slash (`http://gateway.internal/deepgram/`) to keep it: endpoint paths
    /// are joined on by RFC 3986 relative resolution, which replaces the last
    /// segment of a path that does not end in one, so without the slash the
    /// prefix is silently dropped.
    pub fn with_base_url_and_temp_token<U, T>(base_url: U, temp_token: T) -> Result<Self>
    where
        U: TryInto<Url>,
        U::Error: std::fmt::Debug,
        T: AsRef<str>,
    {
        let base_url = base_url.try_into().map_err(|_| DeepgramError::InvalidUrl)?;
        let auth = AuthMethod::TempToken(RedactedString(temp_token.as_ref().to_owned()));
        Self::inner_constructor(base_url, Some(auth))
    }

    fn inner_constructor(base_url: Url, auth: Option<AuthMethod>) -> Result<Self> {
        if base_url.cannot_be_a_base() {
            return Err(DeepgramError::InvalidUrl);
        }
        let authorization_header = {
            let mut header = HeaderMap::new();
            if let Some(auth) = &auth {
                let header_value = auth.header_value();
                if let Ok(mut value) = HeaderValue::from_str(&header_value) {
                    // reqwest's `Client` Debug output includes its default
                    // headers; a sensitive value prints as `Sensitive`
                    // instead of the token, so `{:?}` on a `Deepgram` (or any
                    // sub-client holding one) never reveals the credential.
                    value.set_sensitive(true);
                    header.insert("Authorization", value);
                }
            }
            header
        };

        Ok(Deepgram {
            auth,
            base_url,
            client: reqwest::Client::builder()
                .user_agent(USER_AGENT)
                .default_headers(authorization_header)
                .build()?,
            #[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
            tls: tls::TlsSettings::new(),
        })
    }

    /// Join a relative API path, such as `v1/projects`, onto this client's
    /// configured base URL.
    ///
    /// Every management request and the token grant request are built this
    /// way, so a client constructed with [`Deepgram::with_base_url`] sends
    /// them to that host rather than to `https://api.deepgram.com`. Pass the
    /// path without a leading slash so a base URL that carries a path prefix
    /// (`http://gateway/deepgram/`) keeps it, matching how the transcription
    /// and speech surfaces build theirs.
    ///
    /// Not feature-gated: [`crate::auth`] is always compiled, so this is
    /// reachable in every feature combination, `--no-default-features`
    /// included.
    ///
    /// # Errors
    ///
    /// Returns [`DeepgramError::InvalidUrl`] if `path` cannot be joined onto
    /// the base URL.
    pub(crate) fn api_url(&self, path: &str) -> Result<Url> {
        self.base_url
            .join(path)
            .map_err(|_| DeepgramError::InvalidUrl)
    }

    /// Use your own [`rustls::ClientConfig`] for every `wss://` WebSocket
    /// connection this client opens (live transcription, Flux
    /// speech-to-text, streaming text-to-speech, Flux text-to-speech). It
    /// is used verbatim: trust roots, client authentication, protocol
    /// versions, and session resumption are all yours to decide.
    ///
    /// Reach for this when the defaults don't fit — pinning to a private CA,
    /// presenting a client certificate, a custom verifier — and the
    /// `rustls-tls-native-roots` feature (trust the OS store in addition to
    /// the bundled public roots) isn't enough. Build the config from
    /// [`deepgram::rustls`](crate::rustls) so the versions match.
    ///
    /// # Only `wss://` is affected
    ///
    /// A client built from an `http://` (or `ws://`) base URL — see
    /// [`Deepgram::with_base_url`] — opens plaintext `ws://` WebSockets. No
    /// TLS handshake takes place and no certificate is verified, so this
    /// config (and the `rustls-tls-native-roots` feature) has no effect on
    /// those connections, and credentials and audio travel unencrypted. Keep
    /// `http://` base URLs to local testing and use `https://` whenever an
    /// API key, a temporary token, or private traffic is involved, including
    /// self-hosted deployments.
    ///
    /// REST requests are made with `reqwest` and are not affected.
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use deepgram::{rustls, Deepgram};
    ///
    /// let mut roots = rustls::RootCertStore::empty();
    /// // roots.add(my_private_ca_der)?;
    /// let config = rustls::ClientConfig::builder()
    ///     .with_root_certificates(roots)
    ///     .with_no_client_auth();
    ///
    /// let dg = Deepgram::new("YOUR_DEEPGRAM_API_KEY")?.tls_config(config);
    /// # let _ = dg;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(any(feature = "listen", feature = "speak", feature = "agent"))]
    pub fn tls_config(mut self, config: impl Into<std::sync::Arc<rustls::ClientConfig>>) -> Self {
        self.tls = tls::TlsSettings::custom(config.into());
        self
    }
}

/// Sends the request and checks the response for an error.
///
/// If there is an error, it translates it into a [`DeepgramError::DeepgramApiError`].
/// Otherwise, it deserializes the JSON accordingly.
#[cfg_attr(not(feature = "listen"), allow(unused))]
async fn send_and_translate_response<R: DeserializeOwned>(
    request_builder: RequestBuilder,
) -> crate::Result<R> {
    let response = request_builder.send().await?;

    match response.error_for_status_ref() {
        Ok(_) => Ok(response.json().await?),
        Err(err) => Err(DeepgramError::DeepgramApiError {
            body: response.text().await?,
            err,
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_auth_method_header_value() {
        let api_key = AuthMethod::ApiKey(RedactedString("test_api_key".to_string()));
        assert_eq!(api_key.header_value(), "Token test_api_key".to_string());

        let temp_token = AuthMethod::TempToken(RedactedString("test_temp_token".to_string()));
        assert_eq!(
            temp_token.header_value(),
            "Bearer test_temp_token".to_string()
        );
    }

    #[test]
    fn test_deepgram_new_with_temp_token() {
        let client = Deepgram::with_temp_token("test_temp_token").unwrap();
        assert_eq!(
            client.auth,
            Some(AuthMethod::TempToken(RedactedString(
                "test_temp_token".to_string()
            )))
        );
    }

    #[test]
    fn test_deepgram_new_with_api_key() {
        let client = Deepgram::new("test_api_key").unwrap();
        assert_eq!(
            client.auth,
            Some(AuthMethod::ApiKey(RedactedString(
                "test_api_key".to_string()
            )))
        );
    }

    #[test]
    fn debug_output_never_contains_the_credential() {
        // `Deepgram` derives Debug and holds a reqwest `Client`, whose Debug
        // output dumps its default headers. The Authorization header must be
        // marked sensitive so neither the raw key nor the header value leaks
        // through `{:?}` on the client or on any sub-client that holds it.
        let key = "fake-key-abc123";
        let client = Deepgram::new(key).unwrap();
        // Every sub-client holds the same `Deepgram`, so each one is a
        // separate way to print it. Feature-gated ones are pushed
        // conditionally so this test covers whatever is compiled in.
        let mut debugs = vec![
            format!("{client:?}"),
            format!("{:#?}", client),
            format!("{:?}", client.transcription()),
            format!("{:?}", client.text_to_speech()),
        ];
        #[cfg(feature = "agent")]
        debugs.push(format!("{:?}", client.agent()));
        #[cfg(feature = "read")]
        debugs.push(format!("{:?}", client.text_intelligence()));
        #[cfg(feature = "manage")]
        {
            debugs.push(format!("{:?}", client.self_hosted()));
            debugs.push(format!("{:?}", client.models()));
            debugs.push(format!("{:?}", client.projects()));
            debugs.push(format!("{:?}", client.keys()));
        }
        debugs.push(format!("{:?}", client.auth()));
        for debug in debugs {
            assert!(!debug.contains(key), "{debug}");
            assert!(!debug.contains("Token "), "{debug}");
        }

        let token = "fake-temp-token-xyz789";
        let client = Deepgram::with_temp_token(token).unwrap();
        let debug = format!("{client:?}");
        assert!(!debug.contains(token), "{debug}");
        assert!(!debug.contains("Bearer "), "{debug}");
    }
}