deepgram.client

  1# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
  2# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
  3# SPDX-License-Identifier: MIT
  4
  5from typing import Optional
  6from importlib import import_module
  7import os
  8import logging
  9import deprecation  # type: ignore
 10
 11from . import __version__
 12from .utils import verboselogs
 13
 14# common
 15# pylint: disable=unused-import
 16from .clients import (
 17    TextSource,
 18    BufferSource,
 19    StreamSource,
 20    FileSource,
 21    UrlSource,
 22)
 23from .clients import BaseResponse
 24from .clients import (
 25    Average,
 26    Intent,
 27    Intents,
 28    IntentsInfo,
 29    Segment,
 30    SentimentInfo,
 31    Sentiment,
 32    Sentiments,
 33    SummaryInfo,
 34    Topic,
 35    Topics,
 36    TopicsInfo,
 37)
 38from .clients import (
 39    ModelInfo,
 40    Hit,
 41    Search,
 42)
 43from .clients import (
 44    OpenResponse,
 45    CloseResponse,
 46    UnhandledResponse,
 47    ErrorResponse,
 48)
 49from .clients import (
 50    DeepgramError,
 51    DeepgramTypeError,
 52    DeepgramModuleError,
 53    DeepgramApiError,
 54    DeepgramUnknownApiError,
 55)
 56
 57# listen client
 58from .clients import ListenRouter, ReadRouter, SpeakRouter, AgentRouter
 59
 60# speech-to-text
 61from .clients import LiveClient, AsyncLiveClient  # backward compat
 62from .clients import (
 63    ListenWebSocketClient,
 64    AsyncListenWebSocketClient,
 65)
 66from .clients import (
 67    ListenWebSocketOptions,
 68    LiveOptions,
 69    LiveTranscriptionEvents,
 70)
 71
 72# live client responses
 73from .clients import (
 74    #### top level
 75    LiveResultResponse,
 76    ListenWSMetadataResponse,
 77    SpeechStartedResponse,
 78    UtteranceEndResponse,
 79    #### common websocket response
 80    # OpenResponse,
 81    # CloseResponse,
 82    # ErrorResponse,
 83    # UnhandledResponse,
 84    #### unique
 85    ListenWSMetadata,
 86    ListenWSAlternative,
 87    ListenWSChannel,
 88    ListenWSWord,
 89)
 90
 91# prerecorded
 92from .clients import (
 93    # common
 94    # UrlSource,
 95    # BufferSource,
 96    # StreamSource,
 97    # TextSource,
 98    # FileSource,
 99    # unique
100    PreRecordedStreamSource,
101    PrerecordedSource,
102    ListenRestSource,
103)
104
105from .clients import (
106    PreRecordedClient,
107    AsyncPreRecordedClient,
108)  # backward compat
109from .clients import (
110    ListenRESTClient,
111    AsyncListenRESTClient,
112)
113from .clients import (
114    ListenRESTOptions,
115    PrerecordedOptions,
116)
117
118# rest client responses
119from .clients import (
120    #### top level
121    AsyncPrerecordedResponse,
122    PrerecordedResponse,
123    SyncPrerecordedResponse,
124    #### shared
125    # Average,
126    # Intent,
127    # Intents,
128    # IntentsInfo,
129    # Segment,
130    # SentimentInfo,
131    # Sentiment,
132    # Sentiments,
133    # SummaryInfo,
134    # Topic,
135    # Topics,
136    # TopicsInfo,
137    #### between rest and websocket
138    # ModelInfo,
139    # Alternative,
140    # Hit,
141    # Search,
142    # Channel,
143    # Word,
144    # unique
145    Entity,
146    ListenRESTMetadata,
147    Paragraph,
148    Paragraphs,
149    ListenRESTResults,
150    Sentence,
151    Summaries,
152    SummaryV1,
153    SummaryV2,
154    Translation,
155    Utterance,
156    Warning,
157    ListenRESTAlternative,
158    ListenRESTChannel,
159    ListenRESTWord,
160)
161
162# read
163from .clients import ReadClient, AsyncReadClient
164from .clients import AnalyzeClient, AsyncAnalyzeClient
165from .clients import (
166    AnalyzeOptions,
167    AnalyzeStreamSource,
168    AnalyzeSource,
169)
170
171# read client responses
172from .clients import (
173    #### top level
174    AsyncAnalyzeResponse,
175    SyncAnalyzeResponse,
176    AnalyzeResponse,
177    #### shared
178    # Average,
179    # Intent,
180    # Intents,
181    # IntentsInfo,
182    # Segment,
183    # SentimentInfo,
184    # Sentiment,
185    # Sentiments,
186    # SummaryInfo,
187    # Topic,
188    # Topics,
189    # TopicsInfo,
190    #### unique
191    AnalyzeMetadata,
192    AnalyzeResults,
193    AnalyzeSummary,
194)
195
196# speak
197## speak REST
198from .clients import (
199    #### top level
200    SpeakRESTOptions,
201    SpeakOptions,  # backward compat
202    #### common
203    # TextSource,
204    # BufferSource,
205    # StreamSource,
206    # FileSource,
207    #### unique
208    SpeakSource,
209    SpeakRestSource,
210    SpeakRESTSource,
211)
212
213from .clients import (
214    SpeakClient,  # backward compat
215    SpeakRESTClient,
216    AsyncSpeakRESTClient,
217)
218
219from .clients import (
220    SpeakResponse,  # backward compat
221    SpeakRESTResponse,
222)
223
224## speak WebSocket
225from .clients import SpeakWebSocketEvents, SpeakWebSocketMessage
226
227from .clients import (
228    SpeakWSOptions,
229)
230
231from .clients import (
232    SpeakWebSocketClient,
233    AsyncSpeakWebSocketClient,
234    SpeakWSClient,
235    AsyncSpeakWSClient,
236)
237
238from .clients import (
239    #### top level
240    SpeakWSMetadataResponse,
241    FlushedResponse,
242    ClearedResponse,
243    WarningResponse,
244    #### common websocket response
245    # OpenResponse,
246    # CloseResponse,
247    # UnhandledResponse,
248    # ErrorResponse,
249)
250
251# auth client classes
252from .clients import AuthRESTClient, AsyncAuthRESTClient
253
254# auth client responses
255from .clients import (
256    GrantTokenResponse,
257)
258
259# manage client classes/input
260from .clients import ManageClient, AsyncManageClient
261from .clients import (
262    ProjectOptions,
263    KeyOptions,
264    ScopeOptions,
265    InviteOptions,
266    UsageRequestOptions,
267    UsageSummaryOptions,
268    UsageFieldsOptions,
269)
270
271# manage client responses
272from .clients import (
273    #### top level
274    Message,
275    ProjectsResponse,
276    ModelResponse,
277    ModelsResponse,
278    MembersResponse,
279    KeyResponse,
280    KeysResponse,
281    ScopesResponse,
282    InvitesResponse,
283    UsageRequest,
284    UsageResponse,
285    UsageRequestsResponse,
286    UsageSummaryResponse,
287    UsageFieldsResponse,
288    BalancesResponse,
289    #### shared
290    Project,
291    STTDetails,
292    TTSMetadata,
293    TTSDetails,
294    Member,
295    Key,
296    Invite,
297    Config,
298    STTUsageDetails,
299    Callback,
300    TokenDetail,
301    SpeechSegment,
302    TTSUsageDetails,
303    STTTokens,
304    TTSTokens,
305    UsageSummaryResults,
306    Resolution,
307    UsageModel,
308    Balance,
309)
310
311# on-prem
312from .clients import (
313    OnPremClient,
314    AsyncOnPremClient,
315    SelfHostedClient,
316    AsyncSelfHostedClient,
317)
318
319
320# agent
321from .clients import AgentWebSocketEvents
322
323# websocket
324from .clients import (
325    AgentWebSocketClient,
326    AsyncAgentWebSocketClient,
327)
328
329from .clients import (
330    #### common websocket response
331    # OpenResponse,
332    # CloseResponse,
333    # ErrorResponse,
334    # UnhandledResponse,
335    #### unique
336    WelcomeResponse,
337    SettingsAppliedResponse,
338    ConversationTextResponse,
339    UserStartedSpeakingResponse,
340    AgentThinkingResponse,
341    FunctionCalling,
342    FunctionCallRequest,
343    AgentStartedSpeakingResponse,
344    AgentAudioDoneResponse,
345    InjectionRefusedResponse,
346)
347
348from .clients import (
349    # top level
350    SettingsConfigurationOptions,
351    UpdateInstructionsOptions,
352    UpdateSpeakOptions,
353    InjectAgentMessageOptions,
354    FunctionCallResponse,
355    AgentKeepAlive,
356    # sub level
357    Listen,
358    Speak,
359    Header,
360    Item,
361    Properties,
362    Parameters,
363    Function,
364    Provider,
365    Think,
366    Agent,
367    Input,
368    Output,
369    Audio,
370    Context,
371)
372
373
374# client errors and options
375from .options import DeepgramClientOptions, ClientOptionsFromEnv
376from .errors import DeepgramApiKeyError
377
378# pylint: enable=unused-import
379
380
381class Deepgram:  # pylint: disable=broad-exception-raised
382    """
383    The Deepgram class is no longer a class in version 3 of this SDK.
384    """
385
386    def __init__(self, *anything):
387        raise Exception(
388            """
389            FATAL ERROR:
390            You are attempting to instantiate a Deepgram object, which is no longer a class in version 3 of this SDK.
391
392            To fix this issue:
393                1. You need to revert to the previous version 2 of the SDK: pip install deepgram-sdk==2.12.0
394                2. or, update your application's code to use version 3 of this SDK. See the README for more information.
395
396            Things to consider:
397
398                - This Version 3 of the SDK requires Python 3.10 or higher.
399                  Older versions (3.9 and lower) of Python are nearing end-of-life: https://devguide.python.org/versions/
400                  Understand the risks of using a version of Python nearing EOL.
401
402                - Version 2 of the SDK will receive maintenance updates in the form of security fixes only.
403                  No new features will be added to version 2 of the SDK.
404            """
405        )
406
407
408class DeepgramClient:
409    """
410    Represents a client for interacting with the Deepgram API.
411
412    This class provides a client for making requests to the Deepgram API with various configuration options.
413
414    Attributes:
415        api_key (str): The Deepgram API key used for authentication.
416        config_options (DeepgramClientOptions): An optional configuration object specifying client options.
417
418    Raises:
419        DeepgramApiKeyError: If the API key is missing or invalid.
420
421    Methods:
422        listen: Returns a ListenClient instance for interacting with Deepgram's transcription services.
423
424        manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources.
425        selfhosted: (Preferred) Returns an Threaded SelfHostedClient instance for interacting with Deepgram's on-premises API.
426
427        asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources.
428        asyncselfhosted: Returns an (Async) SelfHostedClient instance for interacting with Deepgram's on-premises API.
429    """
430
431    _config: DeepgramClientOptions
432    _logger: verboselogs.VerboseLogger
433
434    def __init__(
435        self,
436        api_key: str = "",
437        config: Optional[DeepgramClientOptions] = None,
438    ):
439        self._logger = verboselogs.VerboseLogger(__name__)
440        self._logger.addHandler(logging.StreamHandler())
441
442        if api_key == "" and config is not None:
443            self._logger.info("Attempting to set API key from config object")
444            api_key = config.api_key
445        if api_key == "":
446            self._logger.info("Attempting to set API key from environment variable")
447            api_key = os.getenv("DEEPGRAM_API_KEY", "")
448        if api_key == "":
449            self._logger.warning("WARNING: API key is missing")
450
451        self.api_key = api_key
452        if config is None:  # Use default configuration
453            self._config = DeepgramClientOptions(self.api_key)
454        else:
455            config.set_apikey(self.api_key)
456            self._config = config
457
458    @property
459    def listen(self):
460        """
461        Returns a Listen dot-notation router for interacting with Deepgram's transcription services.
462        """
463        return ListenRouter(self._config)
464
465    @property
466    def read(self):
467        """
468        Returns a Read dot-notation router for interacting with Deepgram's read services.
469        """
470        return ReadRouter(self._config)
471
472    @property
473    def speak(self):
474        """
475        Returns a Speak dot-notation router for interacting with Deepgram's speak services.
476        """
477        return SpeakRouter(self._config)
478
479    @property
480    @deprecation.deprecated(
481        deprecated_in="3.4.0",
482        removed_in="4.0.0",
483        current_version=__version__,
484        details="deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.",
485    )
486    def asyncspeak(self):
487        """
488        DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.
489        """
490        return self.Version(self._config, "asyncspeak")
491
492    @property
493    def manage(self):
494        """
495        Returns a ManageClient instance for managing Deepgram resources.
496        """
497        return self.Version(self._config, "manage")
498
499    @property
500    def asyncmanage(self):
501        """
502        Returns an AsyncManageClient instance for managing Deepgram resources.
503        """
504        return self.Version(self._config, "asyncmanage")
505
506    @property
507    def auth(self):
508        """
509        Returns an AuthRESTClient instance for managing short-lived tokens.
510        """
511        return self.Version(self._config, "auth")
512
513    @property
514    def asyncauth(self):
515        """
516        Returns an AsyncAuthRESTClient instance for managing short-lived tokens.
517        """
518        return self.Version(self._config, "asyncauth")
519
520    @property
521    @deprecation.deprecated(
522        deprecated_in="3.4.0",
523        removed_in="4.0.0",
524        current_version=__version__,
525        details="deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.",
526    )
527    def onprem(self):
528        """
529        DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.
530        """
531        return self.Version(self._config, "selfhosted")
532
533    @property
534    def selfhosted(self):
535        """
536        Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API.
537        """
538        return self.Version(self._config, "selfhosted")
539
540    @property
541    @deprecation.deprecated(
542        deprecated_in="3.4.0",
543        removed_in="4.0.0",
544        current_version=__version__,
545        details="deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.",
546    )
547    def asynconprem(self):
548        """
549        DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.
550        """
551        return self.Version(self._config, "asyncselfhosted")
552
553    @property
554    def asyncselfhosted(self):
555        """
556        Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API.
557        """
558        return self.Version(self._config, "asyncselfhosted")
559
560    @property
561    def agent(self):
562        """
563        Returns a Agent dot-notation router for interacting with Deepgram's speak services.
564        """
565        return AgentRouter(self._config)
566
567    # INTERNAL CLASSES
568    class Version:
569        """
570        Represents a version of the Deepgram API.
571        """
572
573        _logger: verboselogs.VerboseLogger
574        _config: DeepgramClientOptions
575        _parent: str
576
577        def __init__(self, config, parent: str):
578            self._logger = verboselogs.VerboseLogger(__name__)
579            self._logger.addHandler(logging.StreamHandler())
580            self._logger.setLevel(config.verbose)
581
582            self._config = config
583            self._parent = parent
584
585        # FUTURE VERSIONING:
586        # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API.
587        # @property
588        # def latest(self):
589        #     match self._parent:
590        #         case "manage":
591        #             return ManageClient(self._config)
592        #         case "selfhosted":
593        #             return SelfHostedClient(self._config)
594        #         case _:
595        #             raise DeepgramModuleError("Invalid parent")
596
597        def v(self, version: str = ""):
598            # pylint: disable-msg=too-many-statements
599            """
600            Returns a client for the specified version of the API.
601            """
602            self._logger.debug("Version.v ENTER")
603            self._logger.info("version: %s", version)
604            if len(version) == 0:
605                self._logger.error("version is empty")
606                self._logger.debug("Version.v LEAVE")
607                raise DeepgramModuleError("Invalid module version")
608
609            parent = ""
610            filename = ""
611            classname = ""
612            match self._parent:
613                case "manage":
614                    parent = "manage"
615                    filename = "client"
616                    classname = "ManageClient"
617                case "asyncmanage":
618                    parent = "manage"
619                    filename = "async_client"
620                    classname = "AsyncManageClient"
621                case "asyncspeak":
622                    return AsyncSpeakRESTClient(self._config)
623                case "selfhosted":
624                    parent = "selfhosted"
625                    filename = "client"
626                    classname = "SelfHostedClient"
627                case "asyncselfhosted":
628                    parent = "selfhosted"
629                    filename = "async_client"
630                    classname = "AsyncSelfHostedClient"
631                case "auth":
632                    parent = "auth"
633                    filename = "client"
634                    classname = "AuthRESTClient"
635                case "asyncauth":
636                    parent = "auth"
637                    filename = "async_client"
638                    classname = "AsyncAuthRESTClient"
639                case _:
640                    self._logger.error("parent unknown: %s", self._parent)
641                    self._logger.debug("Version.v LEAVE")
642                    raise DeepgramModuleError("Invalid parent type")
643
644            # create class path
645            path = f"deepgram.clients.{parent}.v{version}.{filename}"
646            self._logger.info("path: %s", path)
647            self._logger.info("classname: %s", classname)
648
649            # import class
650            mod = import_module(path)
651            if mod is None:
652                self._logger.error("module path is None")
653                self._logger.debug("Version.v LEAVE")
654                raise DeepgramModuleError("Unable to find package")
655
656            my_class = getattr(mod, classname)
657            if my_class is None:
658                self._logger.error("my_class is None")
659                self._logger.debug("Version.v LEAVE")
660                raise DeepgramModuleError("Unable to find class")
661
662            # instantiate class
663            my_class_instance = my_class(self._config)
664            self._logger.notice("Version.v succeeded")
665            self._logger.debug("Version.v LEAVE")
666            return my_class_instance
667
668        # pylint: enable-msg=too-many-statements
class Deepgram:
382class Deepgram:  # pylint: disable=broad-exception-raised
383    """
384    The Deepgram class is no longer a class in version 3 of this SDK.
385    """
386
387    def __init__(self, *anything):
388        raise Exception(
389            """
390            FATAL ERROR:
391            You are attempting to instantiate a Deepgram object, which is no longer a class in version 3 of this SDK.
392
393            To fix this issue:
394                1. You need to revert to the previous version 2 of the SDK: pip install deepgram-sdk==2.12.0
395                2. or, update your application's code to use version 3 of this SDK. See the README for more information.
396
397            Things to consider:
398
399                - This Version 3 of the SDK requires Python 3.10 or higher.
400                  Older versions (3.9 and lower) of Python are nearing end-of-life: https://devguide.python.org/versions/
401                  Understand the risks of using a version of Python nearing EOL.
402
403                - Version 2 of the SDK will receive maintenance updates in the form of security fixes only.
404                  No new features will be added to version 2 of the SDK.
405            """
406        )

The Deepgram class is no longer a class in version 3 of this SDK.

Deepgram(*anything)
387    def __init__(self, *anything):
388        raise Exception(
389            """
390            FATAL ERROR:
391            You are attempting to instantiate a Deepgram object, which is no longer a class in version 3 of this SDK.
392
393            To fix this issue:
394                1. You need to revert to the previous version 2 of the SDK: pip install deepgram-sdk==2.12.0
395                2. or, update your application's code to use version 3 of this SDK. See the README for more information.
396
397            Things to consider:
398
399                - This Version 3 of the SDK requires Python 3.10 or higher.
400                  Older versions (3.9 and lower) of Python are nearing end-of-life: https://devguide.python.org/versions/
401                  Understand the risks of using a version of Python nearing EOL.
402
403                - Version 2 of the SDK will receive maintenance updates in the form of security fixes only.
404                  No new features will be added to version 2 of the SDK.
405            """
406        )
class DeepgramClient:
409class DeepgramClient:
410    """
411    Represents a client for interacting with the Deepgram API.
412
413    This class provides a client for making requests to the Deepgram API with various configuration options.
414
415    Attributes:
416        api_key (str): The Deepgram API key used for authentication.
417        config_options (DeepgramClientOptions): An optional configuration object specifying client options.
418
419    Raises:
420        DeepgramApiKeyError: If the API key is missing or invalid.
421
422    Methods:
423        listen: Returns a ListenClient instance for interacting with Deepgram's transcription services.
424
425        manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources.
426        selfhosted: (Preferred) Returns an Threaded SelfHostedClient instance for interacting with Deepgram's on-premises API.
427
428        asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources.
429        asyncselfhosted: Returns an (Async) SelfHostedClient instance for interacting with Deepgram's on-premises API.
430    """
431
432    _config: DeepgramClientOptions
433    _logger: verboselogs.VerboseLogger
434
435    def __init__(
436        self,
437        api_key: str = "",
438        config: Optional[DeepgramClientOptions] = None,
439    ):
440        self._logger = verboselogs.VerboseLogger(__name__)
441        self._logger.addHandler(logging.StreamHandler())
442
443        if api_key == "" and config is not None:
444            self._logger.info("Attempting to set API key from config object")
445            api_key = config.api_key
446        if api_key == "":
447            self._logger.info("Attempting to set API key from environment variable")
448            api_key = os.getenv("DEEPGRAM_API_KEY", "")
449        if api_key == "":
450            self._logger.warning("WARNING: API key is missing")
451
452        self.api_key = api_key
453        if config is None:  # Use default configuration
454            self._config = DeepgramClientOptions(self.api_key)
455        else:
456            config.set_apikey(self.api_key)
457            self._config = config
458
459    @property
460    def listen(self):
461        """
462        Returns a Listen dot-notation router for interacting with Deepgram's transcription services.
463        """
464        return ListenRouter(self._config)
465
466    @property
467    def read(self):
468        """
469        Returns a Read dot-notation router for interacting with Deepgram's read services.
470        """
471        return ReadRouter(self._config)
472
473    @property
474    def speak(self):
475        """
476        Returns a Speak dot-notation router for interacting with Deepgram's speak services.
477        """
478        return SpeakRouter(self._config)
479
480    @property
481    @deprecation.deprecated(
482        deprecated_in="3.4.0",
483        removed_in="4.0.0",
484        current_version=__version__,
485        details="deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.",
486    )
487    def asyncspeak(self):
488        """
489        DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.
490        """
491        return self.Version(self._config, "asyncspeak")
492
493    @property
494    def manage(self):
495        """
496        Returns a ManageClient instance for managing Deepgram resources.
497        """
498        return self.Version(self._config, "manage")
499
500    @property
501    def asyncmanage(self):
502        """
503        Returns an AsyncManageClient instance for managing Deepgram resources.
504        """
505        return self.Version(self._config, "asyncmanage")
506
507    @property
508    def auth(self):
509        """
510        Returns an AuthRESTClient instance for managing short-lived tokens.
511        """
512        return self.Version(self._config, "auth")
513
514    @property
515    def asyncauth(self):
516        """
517        Returns an AsyncAuthRESTClient instance for managing short-lived tokens.
518        """
519        return self.Version(self._config, "asyncauth")
520
521    @property
522    @deprecation.deprecated(
523        deprecated_in="3.4.0",
524        removed_in="4.0.0",
525        current_version=__version__,
526        details="deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.",
527    )
528    def onprem(self):
529        """
530        DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.
531        """
532        return self.Version(self._config, "selfhosted")
533
534    @property
535    def selfhosted(self):
536        """
537        Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API.
538        """
539        return self.Version(self._config, "selfhosted")
540
541    @property
542    @deprecation.deprecated(
543        deprecated_in="3.4.0",
544        removed_in="4.0.0",
545        current_version=__version__,
546        details="deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.",
547    )
548    def asynconprem(self):
549        """
550        DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.
551        """
552        return self.Version(self._config, "asyncselfhosted")
553
554    @property
555    def asyncselfhosted(self):
556        """
557        Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API.
558        """
559        return self.Version(self._config, "asyncselfhosted")
560
561    @property
562    def agent(self):
563        """
564        Returns a Agent dot-notation router for interacting with Deepgram's speak services.
565        """
566        return AgentRouter(self._config)
567
568    # INTERNAL CLASSES
569    class Version:
570        """
571        Represents a version of the Deepgram API.
572        """
573
574        _logger: verboselogs.VerboseLogger
575        _config: DeepgramClientOptions
576        _parent: str
577
578        def __init__(self, config, parent: str):
579            self._logger = verboselogs.VerboseLogger(__name__)
580            self._logger.addHandler(logging.StreamHandler())
581            self._logger.setLevel(config.verbose)
582
583            self._config = config
584            self._parent = parent
585
586        # FUTURE VERSIONING:
587        # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API.
588        # @property
589        # def latest(self):
590        #     match self._parent:
591        #         case "manage":
592        #             return ManageClient(self._config)
593        #         case "selfhosted":
594        #             return SelfHostedClient(self._config)
595        #         case _:
596        #             raise DeepgramModuleError("Invalid parent")
597
598        def v(self, version: str = ""):
599            # pylint: disable-msg=too-many-statements
600            """
601            Returns a client for the specified version of the API.
602            """
603            self._logger.debug("Version.v ENTER")
604            self._logger.info("version: %s", version)
605            if len(version) == 0:
606                self._logger.error("version is empty")
607                self._logger.debug("Version.v LEAVE")
608                raise DeepgramModuleError("Invalid module version")
609
610            parent = ""
611            filename = ""
612            classname = ""
613            match self._parent:
614                case "manage":
615                    parent = "manage"
616                    filename = "client"
617                    classname = "ManageClient"
618                case "asyncmanage":
619                    parent = "manage"
620                    filename = "async_client"
621                    classname = "AsyncManageClient"
622                case "asyncspeak":
623                    return AsyncSpeakRESTClient(self._config)
624                case "selfhosted":
625                    parent = "selfhosted"
626                    filename = "client"
627                    classname = "SelfHostedClient"
628                case "asyncselfhosted":
629                    parent = "selfhosted"
630                    filename = "async_client"
631                    classname = "AsyncSelfHostedClient"
632                case "auth":
633                    parent = "auth"
634                    filename = "client"
635                    classname = "AuthRESTClient"
636                case "asyncauth":
637                    parent = "auth"
638                    filename = "async_client"
639                    classname = "AsyncAuthRESTClient"
640                case _:
641                    self._logger.error("parent unknown: %s", self._parent)
642                    self._logger.debug("Version.v LEAVE")
643                    raise DeepgramModuleError("Invalid parent type")
644
645            # create class path
646            path = f"deepgram.clients.{parent}.v{version}.{filename}"
647            self._logger.info("path: %s", path)
648            self._logger.info("classname: %s", classname)
649
650            # import class
651            mod = import_module(path)
652            if mod is None:
653                self._logger.error("module path is None")
654                self._logger.debug("Version.v LEAVE")
655                raise DeepgramModuleError("Unable to find package")
656
657            my_class = getattr(mod, classname)
658            if my_class is None:
659                self._logger.error("my_class is None")
660                self._logger.debug("Version.v LEAVE")
661                raise DeepgramModuleError("Unable to find class")
662
663            # instantiate class
664            my_class_instance = my_class(self._config)
665            self._logger.notice("Version.v succeeded")
666            self._logger.debug("Version.v LEAVE")
667            return my_class_instance
668
669        # pylint: enable-msg=too-many-statements

Represents a client for interacting with the Deepgram API.

This class provides a client for making requests to the Deepgram API with various configuration options.

Attributes: api_key (str): The Deepgram API key used for authentication. config_options (DeepgramClientOptions): An optional configuration object specifying client options.

Raises: DeepgramApiKeyError: If the API key is missing or invalid.

Methods: listen: Returns a ListenClient instance for interacting with Deepgram's transcription services.

manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources.
selfhosted: (Preferred) Returns an Threaded SelfHostedClient instance for interacting with Deepgram's on-premises API.

asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources.
asyncselfhosted: Returns an (Async) SelfHostedClient instance for interacting with Deepgram's on-premises API.
DeepgramClient( api_key: str = '', config: Optional[deepgram.options.DeepgramClientOptions] = None)
435    def __init__(
436        self,
437        api_key: str = "",
438        config: Optional[DeepgramClientOptions] = None,
439    ):
440        self._logger = verboselogs.VerboseLogger(__name__)
441        self._logger.addHandler(logging.StreamHandler())
442
443        if api_key == "" and config is not None:
444            self._logger.info("Attempting to set API key from config object")
445            api_key = config.api_key
446        if api_key == "":
447            self._logger.info("Attempting to set API key from environment variable")
448            api_key = os.getenv("DEEPGRAM_API_KEY", "")
449        if api_key == "":
450            self._logger.warning("WARNING: API key is missing")
451
452        self.api_key = api_key
453        if config is None:  # Use default configuration
454            self._config = DeepgramClientOptions(self.api_key)
455        else:
456            config.set_apikey(self.api_key)
457            self._config = config
api_key
listen
459    @property
460    def listen(self):
461        """
462        Returns a Listen dot-notation router for interacting with Deepgram's transcription services.
463        """
464        return ListenRouter(self._config)

Returns a Listen dot-notation router for interacting with Deepgram's transcription services.

read
466    @property
467    def read(self):
468        """
469        Returns a Read dot-notation router for interacting with Deepgram's read services.
470        """
471        return ReadRouter(self._config)

Returns a Read dot-notation router for interacting with Deepgram's read services.

speak
473    @property
474    def speak(self):
475        """
476        Returns a Speak dot-notation router for interacting with Deepgram's speak services.
477        """
478        return SpeakRouter(self._config)

Returns a Speak dot-notation router for interacting with Deepgram's speak services.

asyncspeak
480    @property
481    @deprecation.deprecated(
482        deprecated_in="3.4.0",
483        removed_in="4.0.0",
484        current_version=__version__,
485        details="deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.",
486    )
487    def asyncspeak(self):
488        """
489        DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.
490        """
491        return self.Version(self._config, "asyncspeak")

DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.

manage
493    @property
494    def manage(self):
495        """
496        Returns a ManageClient instance for managing Deepgram resources.
497        """
498        return self.Version(self._config, "manage")

Returns a ManageClient instance for managing Deepgram resources.

asyncmanage
500    @property
501    def asyncmanage(self):
502        """
503        Returns an AsyncManageClient instance for managing Deepgram resources.
504        """
505        return self.Version(self._config, "asyncmanage")

Returns an AsyncManageClient instance for managing Deepgram resources.

auth
507    @property
508    def auth(self):
509        """
510        Returns an AuthRESTClient instance for managing short-lived tokens.
511        """
512        return self.Version(self._config, "auth")

Returns an AuthRESTClient instance for managing short-lived tokens.

asyncauth
514    @property
515    def asyncauth(self):
516        """
517        Returns an AsyncAuthRESTClient instance for managing short-lived tokens.
518        """
519        return self.Version(self._config, "asyncauth")

Returns an AsyncAuthRESTClient instance for managing short-lived tokens.

onprem
521    @property
522    @deprecation.deprecated(
523        deprecated_in="3.4.0",
524        removed_in="4.0.0",
525        current_version=__version__,
526        details="deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.",
527    )
528    def onprem(self):
529        """
530        DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.
531        """
532        return self.Version(self._config, "selfhosted")

DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.

selfhosted
534    @property
535    def selfhosted(self):
536        """
537        Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API.
538        """
539        return self.Version(self._config, "selfhosted")

Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API.

asynconprem
541    @property
542    @deprecation.deprecated(
543        deprecated_in="3.4.0",
544        removed_in="4.0.0",
545        current_version=__version__,
546        details="deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.",
547    )
548    def asynconprem(self):
549        """
550        DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.
551        """
552        return self.Version(self._config, "asyncselfhosted")

DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.

asyncselfhosted
554    @property
555    def asyncselfhosted(self):
556        """
557        Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API.
558        """
559        return self.Version(self._config, "asyncselfhosted")

Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API.

agent
561    @property
562    def agent(self):
563        """
564        Returns a Agent dot-notation router for interacting with Deepgram's speak services.
565        """
566        return AgentRouter(self._config)

Returns a Agent dot-notation router for interacting with Deepgram's speak services.

class DeepgramClient.Version:
569    class Version:
570        """
571        Represents a version of the Deepgram API.
572        """
573
574        _logger: verboselogs.VerboseLogger
575        _config: DeepgramClientOptions
576        _parent: str
577
578        def __init__(self, config, parent: str):
579            self._logger = verboselogs.VerboseLogger(__name__)
580            self._logger.addHandler(logging.StreamHandler())
581            self._logger.setLevel(config.verbose)
582
583            self._config = config
584            self._parent = parent
585
586        # FUTURE VERSIONING:
587        # When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API.
588        # @property
589        # def latest(self):
590        #     match self._parent:
591        #         case "manage":
592        #             return ManageClient(self._config)
593        #         case "selfhosted":
594        #             return SelfHostedClient(self._config)
595        #         case _:
596        #             raise DeepgramModuleError("Invalid parent")
597
598        def v(self, version: str = ""):
599            # pylint: disable-msg=too-many-statements
600            """
601            Returns a client for the specified version of the API.
602            """
603            self._logger.debug("Version.v ENTER")
604            self._logger.info("version: %s", version)
605            if len(version) == 0:
606                self._logger.error("version is empty")
607                self._logger.debug("Version.v LEAVE")
608                raise DeepgramModuleError("Invalid module version")
609
610            parent = ""
611            filename = ""
612            classname = ""
613            match self._parent:
614                case "manage":
615                    parent = "manage"
616                    filename = "client"
617                    classname = "ManageClient"
618                case "asyncmanage":
619                    parent = "manage"
620                    filename = "async_client"
621                    classname = "AsyncManageClient"
622                case "asyncspeak":
623                    return AsyncSpeakRESTClient(self._config)
624                case "selfhosted":
625                    parent = "selfhosted"
626                    filename = "client"
627                    classname = "SelfHostedClient"
628                case "asyncselfhosted":
629                    parent = "selfhosted"
630                    filename = "async_client"
631                    classname = "AsyncSelfHostedClient"
632                case "auth":
633                    parent = "auth"
634                    filename = "client"
635                    classname = "AuthRESTClient"
636                case "asyncauth":
637                    parent = "auth"
638                    filename = "async_client"
639                    classname = "AsyncAuthRESTClient"
640                case _:
641                    self._logger.error("parent unknown: %s", self._parent)
642                    self._logger.debug("Version.v LEAVE")
643                    raise DeepgramModuleError("Invalid parent type")
644
645            # create class path
646            path = f"deepgram.clients.{parent}.v{version}.{filename}"
647            self._logger.info("path: %s", path)
648            self._logger.info("classname: %s", classname)
649
650            # import class
651            mod = import_module(path)
652            if mod is None:
653                self._logger.error("module path is None")
654                self._logger.debug("Version.v LEAVE")
655                raise DeepgramModuleError("Unable to find package")
656
657            my_class = getattr(mod, classname)
658            if my_class is None:
659                self._logger.error("my_class is None")
660                self._logger.debug("Version.v LEAVE")
661                raise DeepgramModuleError("Unable to find class")
662
663            # instantiate class
664            my_class_instance = my_class(self._config)
665            self._logger.notice("Version.v succeeded")
666            self._logger.debug("Version.v LEAVE")
667            return my_class_instance
668
669        # pylint: enable-msg=too-many-statements

Represents a version of the Deepgram API.

DeepgramClient.Version(config, parent: str)
578        def __init__(self, config, parent: str):
579            self._logger = verboselogs.VerboseLogger(__name__)
580            self._logger.addHandler(logging.StreamHandler())
581            self._logger.setLevel(config.verbose)
582
583            self._config = config
584            self._parent = parent
def v(self, version: str = ''):
598        def v(self, version: str = ""):
599            # pylint: disable-msg=too-many-statements
600            """
601            Returns a client for the specified version of the API.
602            """
603            self._logger.debug("Version.v ENTER")
604            self._logger.info("version: %s", version)
605            if len(version) == 0:
606                self._logger.error("version is empty")
607                self._logger.debug("Version.v LEAVE")
608                raise DeepgramModuleError("Invalid module version")
609
610            parent = ""
611            filename = ""
612            classname = ""
613            match self._parent:
614                case "manage":
615                    parent = "manage"
616                    filename = "client"
617                    classname = "ManageClient"
618                case "asyncmanage":
619                    parent = "manage"
620                    filename = "async_client"
621                    classname = "AsyncManageClient"
622                case "asyncspeak":
623                    return AsyncSpeakRESTClient(self._config)
624                case "selfhosted":
625                    parent = "selfhosted"
626                    filename = "client"
627                    classname = "SelfHostedClient"
628                case "asyncselfhosted":
629                    parent = "selfhosted"
630                    filename = "async_client"
631                    classname = "AsyncSelfHostedClient"
632                case "auth":
633                    parent = "auth"
634                    filename = "client"
635                    classname = "AuthRESTClient"
636                case "asyncauth":
637                    parent = "auth"
638                    filename = "async_client"
639                    classname = "AsyncAuthRESTClient"
640                case _:
641                    self._logger.error("parent unknown: %s", self._parent)
642                    self._logger.debug("Version.v LEAVE")
643                    raise DeepgramModuleError("Invalid parent type")
644
645            # create class path
646            path = f"deepgram.clients.{parent}.v{version}.{filename}"
647            self._logger.info("path: %s", path)
648            self._logger.info("classname: %s", classname)
649
650            # import class
651            mod = import_module(path)
652            if mod is None:
653                self._logger.error("module path is None")
654                self._logger.debug("Version.v LEAVE")
655                raise DeepgramModuleError("Unable to find package")
656
657            my_class = getattr(mod, classname)
658            if my_class is None:
659                self._logger.error("my_class is None")
660                self._logger.debug("Version.v LEAVE")
661                raise DeepgramModuleError("Unable to find class")
662
663            # instantiate class
664            my_class_instance = my_class(self._config)
665            self._logger.notice("Version.v succeeded")
666            self._logger.debug("Version.v LEAVE")
667            return my_class_instance

Returns a client for the specified version of the API.