Deepgram Python SDK

repository·main·Indexed 19 days ago

https://github.com/deepgram/deepgram-python-sdk

A Python SDK (version 7.6.1) for accessing Deepgram's automated speech recognition, text-to-speech, and language understanding APIs. It provides both synchronous (DeepgramClient) and asynchronous (AsyncDeepgramClient) clients to handle real-time speech recognition via WebSockets, pre-recorded file transcription, text analysis, and the creation of conversational AI Voice Agents. The SDK includes high-level helpers like TextBuilder and supports custom transports, including a SageMaker transport for AWS endpoints.

Tokens
73.7K
Snippets
209
Records
276
Agent score
66%

What's inside deepgram-python-sdk

  1. Overview of Deepgram Python SDK example categories

    main

    The SDK examples are organized into functional categories to help you find specific implementation patterns:

    • Authentication (01-09): API key and Access Token methods.
    • Transcription / Listen (10-19): Prerecorded audio (URL or local file), async callbacks, and Live WebSocket (V1 and V2).
    • Text-to-Speech / Speak (20-29): Single REST requests, streaming via WebSocket, and TextBuilder (including Flux V2).
    • Voice Agent (30-39): Configuration and usage for Voice Agents.
    • Text Intelligence / Read (40-49): AI-driven text analysis.
    • Management API (50-59): Managing projects, keys, members, invites, usage, billing, and models.
    • On-Premises (60-69): Credentials management for on-prem environments.
    • Configuration & Advanced (70-79): Request options, query parameters, and error handling patterns.
  2. Migrate Agent Think and Speak Types in v7

    main

    In v7, agent-specific think/speak schemas were consolidated into shared top-level schemas in deepgram.types. If your code imported types from deepgram.agent.v1.types or deepgram.agent.v1.requests, you must update your imports to use the new consolidated types.

    Mapping Table:

    v6 Typev7 ReplacementImport Path
    AgentV1SettingsAgentSpeakEndpointSpeakSettingsV1deepgram.types.speak_settings_v1
    AgentV1SettingsAgentSpeakOneItemSpeakSettingsV1deepgram.types.speak_settings_v1
    AgentV1SettingsAgentThinkOneItemThinkSettingsV1deepgram.types.think_settings_v1
    AgentV1UpdateSpeakSpeakEndpointSpeakSettingsV1deepgram.types.speak_settings_v1
    # v7 Usage Example
    from deepgram.types.speak_settings_v1 import SpeakSettingsV1
    from deepgram.types.speak_settings_v1provider import SpeakSettingsV1Provider_Deepgram
    from deepgram.types.think_settings_v1 import ThinkSettingsV1
    from deepgram.types.think_settings_v1provider import ThinkSettingsV1Provider_OpenAi
    
    speak = [
        SpeakSettingsV1(
            provider=SpeakSettingsV1Provider_Deepgram(
                type="deepgram",
                model="aura-2-asteria-en",
            )
        )
    ]
    
    think = [
        ThinkSettingsV1(
            provider=ThinkSettingsV1Provider_OpenAi(
                type="open_ai",
                model="gpt-4o-mini",
            )
        )
    ]
  3. Configure Authentication for DeepgramClient in v5.0.0

    main

    The v5.0.0 SDK follows a specific priority order for authentication. If multiple methods are provided, the one higher in the list takes precedence:

    1. Explicit access_token parameter (highest priority)
    2. Explicit api_key parameter
    3. DEEPGRAM_TOKEN environment variable
    4. DEEPGRAM_API_KEY environment variable (lowest priority)
  4. How custom transports work

    main

    The SDK allows you to replace the default websockets transport with your own implementation. This is useful for using alternative protocols (like HTTP/2 or SSE), implementing test doubles, or using proxied connections. You can pass your class or a factory callable as transport_factory when creating the client.

    Sync Transports

    Implement send(), recv(), __iter__(), and close() for use with DeepgramClient.

    from deepgram import DeepgramClient
    from deepgram.core.events import EventType
    
    class MyTransport:
        def __init__(self, url: str, headers: dict):
            ...  # establish your connection
    
        def send(self, data): ...   # send str or bytes
        def recv(self): ...         # return next message
        def __iter__(self): ...     # yield messages until closed
        def close(self): ...        # tear down connection
    
    client = DeepgramClient(api_key="...", transport_factory=MyTransport)
    
    with client.listen.v1.connect(model="nova-3") as connection:
        connection.on(EventType.MESSAGE, on_message)
        connection.start_listening()

    Async Transports

    Implement async def send(), async def recv(), async def __aiter__(), and async def close() for use with AsyncDeepgramClient.

    from deepgram import AsyncDeepgramClient
    
    client = AsyncDeepgramClient(api_key="...", transport_factory=MyAsyncTransport)
    
    async with client.listen.v1.connect(model="nova-3") as connection:
        connection.on(EventType.MESSAGE, on_message)
        await connection.start_listening()
  5. Migrate from Deepgram SDK v2 to v3+

    main

    When upgrading from version 2 to version 3 or later, several breaking changes require code updates. The SDK has undergone a complete restructure to improve organization and type safety.

    Key Changes

    • Client Class: The Deepgram class is removed. Use DeepgramClient instead.
    • API Access Pattern: Direct methods on the main client are removed. You must now use the versioned API structure, typically using the .v("1") pattern.
    • Parameter Management: Instead of passing direct parameters to methods, use the new typed options objects.
    • Async/Sync Support: The SDK now provides distinct synchronous and asynchronous classes and methods.
    • WebSocket/Live Client: The live client has been improved with better abstractions and a new event handling system.

    Migration Checklist

    1. Upgrade the package: pip install --upgrade deepgram-sdk
    2. Replace Deepgram with DeepgramClient.
    3. Update API method calls to the new versioned structure (e.g., client.v("1").<method>).
    4. Replace direct method parameters with options objects.
    5. Update WebSocket event handling to the new system.
    6. Update error handling to accommodate new exception types.

    Important Notes

    • Captions: WebVTT and SRT captioning functionality has moved to a standalone package: deepgram-python-captions.
    • Self-hosted: While self-hosted API functionality is currently unchanged, be aware that breaking changes may occur in v4.
    pip install --upgrade deepgram-sdk
  6. How Listen V2 (WebSocket) changed in v6

    main

    The Listen V2 WebSocket implementation in v6 simplifies media and control message handling:

    1. Media Sending: Pass bytes directly to connection.send_media(audio_bytes) instead of using a ListenV2MediaMessage wrapper.
    2. Control Messages: Use the dedicated connection.send_close_stream() method instead of connection.send_control(ListenV2ControlMessage(type="CloseStream")).
    # v6 usage for Listen V2 WebSocket
    from deepgram.listen.v2.types import ListenV2Connected, ListenV2TurnInfo
    
    with client.listen.v2.connect(
        model="flux-general-en", encoding="linear16", sample_rate=16000
    ) as connection:
        def on_message(message) -> None:
            msg_type = getattr(message, "type", "Unknown")
            print(f"Received {msg_type} event")
    
        connection.on(EventType.MESSAGE, on_message)
        connection.start_listening()
    
        connection.send_media(audio_bytes)      # bytes directly
        connection.send_close_stream()          # no argument needed
  7. Migrate Read V1 (Text Analysis) to v5.0.0

    main

    Text analysis in v5.0.0 is accessed via client.read.v1.text.analyze(). Parameters like sentiment, summarize, topics, intents, and language are passed directly to the method.

    response = client.read.v1.text.analyze(
        request={"text": "Hello, world!"},
        language="en",
        sentiment=True,
        summarize=True,
        topics=True,
        intents=True
    )
  8. Migrate from v5 to v6

    main

    When upgrading from version 5 to version 6 of the Deepgram Python SDK, several breaking changes must be addressed. The primary changes involve the removal of the deepgram.extensions.types.sockets module, the reorganization of Agent configuration types, and a significant change in how WebSocket control and media messages are handled.

    Migration Checklist

    • Upgrade to latest version: pip install --upgrade deepgram-sdk
    • Replace all imports from deepgram.extensions.types.sockets with new service-specific types paths.
    • Rename agent configuration types (e.g., AgentV1Agent to AgentV1SettingsAgent).
    • Update think/speak provider imports to deepgram.types.*.
    • Replace send_control() calls with dedicated methods like send_flush(), send_close(), or send_keep_alive().
    • Remove wrapper types from send_media() calls; pass raw bytes directly.
    • Update SpeakV1TextMessage to SpeakV1Text.
    • Remove Event/Message suffixes from event type names used in isinstance() checks.
    • Remove unused imports (e.g., SpeakV1ControlMessage, ListenV1MediaMessage).
    pip install --upgrade deepgram-sdk
  9. Migrate Manage V1 (Projects, Keys, Members, and Usage) to v5.0.0

    main

    The management API has been reorganized into a hierarchical structure under client.manage.v1.

    Key changes include:

    • Projects: get_projects() $\rightarrow$ projects.list(); get_project(id) $\rightarrow$ projects.get(project_id=id).
    • Keys: Now nested under projects: projects.keys.list(), projects.keys.get(), projects.keys.create(), projects.keys.delete().
    • Members: Now nested under projects: projects.members.list(), projects.members.delete(), projects.members.scopes.list(), projects.members.scopes.update().
    • Invitations: Now nested under members: projects.members.invites.list(), projects.members.invites.create(), projects.members.invites.delete().
    • Usage: get_usage_requests() $\rightarrow$ projects.requests.list(); get_usage_summary() $\rightarrow$ projects.usage.get(). A new projects.usage.breakdown.get() method is available in v5.
    • Billing: get_balances() $\rightarrow$ projects.balances.list().
    • Models: get_project_models() $\rightarrow$ projects.models.list().
    # Example: Managing Keys in v5.0.0
    response = client.manage.v1.projects.keys.list(
        project_id="550e8400-e29b-41d4-a716-446655440000"
    )
    
    # Example: Managing Members in v5.0.0
    response = client.manage.v1.projects.members.list(
        project_id="550e8400-e29b-41d4-a716-446655440000"
    )
    
    # Example: Getting Usage Summary in v5.0.0
    response = client.manage.v1.projects.usage.get(
        project_id="550e8400-e29b-41d4-a716-446655440000"
    )
  10. Migrate from v3+ to v5.0.0

    main

    When upgrading from v3+ to v5.0.0, follow this checklist to ensure compatibility with the new API structure:

    1. Upgrade the package: pip install --upgrade deepgram-sdk
    2. Update Authentication: Replace legacy API key configurations with the new authentication methods (using DEEPGRAM_API_KEY or DEEPGRAM_TOKEN).
    3. Refactor API Calls: Update method calls to the new flattened structure and cleaner parameter passing.
    4. Migrate WebSockets: Move from the legacy event system to the new context manager pattern.
    5. Update Keep Alive: Implement manual keep-alive via control messages as described in the WebSocket documentation.
    6. Update Error Handling: Adjust code to handle the new, improved exception types.
    7. Remove Legacy Patterns:
      • Remove custom configuration objects (use direct parameters instead).
      • Replace string-based versioning (e.g., v("1")) with direct versioning (e.g., v1).
      • Replace separate callback methods with the integrated main methods.
    pip install --upgrade deepgram-sdk