Skip to content

feat: support arbitrary attributes for speak provider #532

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

naomi-lgbt
Copy link
Contributor

@naomi-lgbt naomi-lgbt commented May 29, 2025

Proposed changes

Types of changes

What types of changes does your code introduce to the community Python SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

Summary by CodeRabbit

  • New Features

    • Added a new example script demonstrating the setup and usage of a Deepgram Voice Agent with customizable provider options and event logging.
  • Refactor

    • Updated provider configuration handling to use plain dictionaries with attribute-style access, simplifying customization and extension.
  • Chores

    • Removed the SpeakProvider class and related references from the codebase, reducing the number of predefined provider types.

Copy link
Contributor

coderabbitai bot commented May 29, 2025

"""

Walkthrough

The changes remove the SpeakProvider class and all related imports, exports, and aliases from the Deepgram codebase. The Speak class is updated to use a plain dictionary for its provider attribute, with a custom wrapper for attribute access. An example script is added demonstrating agent configuration with arbitrary keys.

Changes

Files/Paths Change Summary
deepgram/init.py, deepgram/client.py, deepgram/clients/init.py,
deepgram/clients/agent/init.py, deepgram/clients/agent/client.py,
deepgram/clients/agent/v1/init.py,
deepgram/clients/agent/v1/websocket/init.py Removed all imports, exports, and aliases of SpeakProvider throughout the module hierarchy.
deepgram/clients/agent/v1/websocket/options.py Deleted SpeakProvider class; updated Speak class to use a dict for provider with attribute access.
examples/agent/arbitrary_keys/main.py Added new example script showing agent setup and usage with arbitrary provider keys.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ExampleScript
    participant DeepgramClient
    participant VoiceAgentWS

    User->>ExampleScript: Run main()
    ExampleScript->>DeepgramClient: Initialize with API key
    ExampleScript->>VoiceAgentWS: Configure agent options (audio, providers, etc.)
    ExampleScript->>VoiceAgentWS: Register event handlers
    ExampleScript->>VoiceAgentWS: Start connection with options
    VoiceAgentWS-->>ExampleScript: on_welcome, on_settings, on_error events
    ExampleScript->>VoiceAgentWS: Finish connection
    ExampleScript-->>User: Print and log status
Loading

Suggested reviewers

  • jpvajda
    """

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1973bbc and 4cf0542.

📒 Files selected for processing (1)
  • deepgram/clients/agent/v1/websocket/options.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepgram/clients/agent/v1/websocket/options.py
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
examples/agent/arbitrary_keys/main.py (1)

23-100: Well-structured example demonstrating arbitrary provider attributes.

This example effectively demonstrates the new flexible provider configuration with arbitrary keys. The implementation follows good practices with proper error handling, environment variable usage, and resource cleanup.

A few minor suggestions for improvement:

+        # Create chatlog.txt if it doesn't exist and add timestamp
+        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        with open("chatlog.txt", 'a') as chatlog:
+            chatlog.write(f"\n=== Session started at {timestamp} ===\n")
+
         def on_welcome(self, welcome, **kwargs):
             print(f"Welcome message received: {welcome}")
             with open("chatlog.txt", 'a') as chatlog:
-                chatlog.write(f"Welcome message: {welcome}\n")
+                chatlog.write(f"[{datetime.now().strftime('%H:%M:%S')}] Welcome: {welcome}\n")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 052aadd and 1973bbc.

📒 Files selected for processing (9)
  • deepgram/__init__.py (0 hunks)
  • deepgram/client.py (0 hunks)
  • deepgram/clients/__init__.py (0 hunks)
  • deepgram/clients/agent/__init__.py (0 hunks)
  • deepgram/clients/agent/client.py (0 hunks)
  • deepgram/clients/agent/v1/__init__.py (0 hunks)
  • deepgram/clients/agent/v1/websocket/__init__.py (0 hunks)
  • deepgram/clients/agent/v1/websocket/options.py (2 hunks)
  • examples/agent/arbitrary_keys/main.py (1 hunks)
💤 Files with no reviewable changes (7)
  • deepgram/client.py
  • deepgram/init.py
  • deepgram/clients/agent/v1/init.py
  • deepgram/clients/agent/client.py
  • deepgram/clients/init.py
  • deepgram/clients/agent/v1/websocket/init.py
  • deepgram/clients/agent/init.py
🧰 Additional context used
🪛 GitHub Actions: Check - lint
deepgram/clients/agent/v1/websocket/options.py

[warning] 228-228: pylint: Missing class docstring (missing-class-docstring)


[warning] 233-233: pylint: Consider explicitly re-raising using 'except KeyError as exc' and 'raise AttributeError(name) from exc' (raise-missing-from)

🔇 Additional comments (3)
examples/agent/arbitrary_keys/main.py (1)

61-61: Excellent demonstration of arbitrary key support.

This line perfectly demonstrates the new capability to add arbitrary attributes to the speak provider, which aligns with the PR objective.

deepgram/clients/agent/v1/websocket/options.py (2)

221-221: Provider type change enables arbitrary attributes.

The change from SpeakProvider to dict successfully enables arbitrary attribute support as demonstrated in the example script.


239-243: Simplified getitem method maintains essential functionality.

The removal of SpeakProvider-specific logic correctly simplifies this method while preserving the Endpoint conversion functionality.

Comment on lines 226 to 237
def __post_init__(self):
# Allow attribute-style access to provider dict
class AttrDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
if not isinstance(self.provider, AttrDict):
self.provider = AttrDict(self.provider)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix linting issues in AttrDict implementation.

The AttrDict implementation is clever and achieves the desired functionality, but there are linting issues that need to be addressed:

     def __post_init__(self):
-        # Allow attribute-style access to provider dict
         class AttrDict(dict):
+            """Dictionary that supports attribute-style access to keys."""
+            
             def __getattr__(self, name):
                 try:
                     return self[name]
                 except KeyError:
-                    raise AttributeError(name)
+                    raise AttributeError(name) from None
             def __setattr__(self, name, value):
                 self[name] = value
         if not isinstance(self.provider, AttrDict):
             self.provider = AttrDict(self.provider)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def __post_init__(self):
# Allow attribute-style access to provider dict
class AttrDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
if not isinstance(self.provider, AttrDict):
self.provider = AttrDict(self.provider)
def __post_init__(self):
class AttrDict(dict):
"""Dictionary that supports attribute-style access to keys."""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name) from None
def __setattr__(self, name, value):
self[name] = value
if not isinstance(self.provider, AttrDict):
self.provider = AttrDict(self.provider)
🧰 Tools
🪛 GitHub Actions: Check - lint

[warning] 228-228: pylint: Missing class docstring (missing-class-docstring)


[warning] 233-233: pylint: Consider explicitly re-raising using 'except KeyError as exc' and 'raise AttributeError(name) from exc' (raise-missing-from)

🤖 Prompt for AI Agents
In deepgram/clients/agent/v1/websocket/options.py around lines 226 to 237, the
AttrDict class implementation has linting issues likely related to missing
docstrings, improper method formatting, or naming conventions. To fix this, add
appropriate docstrings to the class and its methods, ensure consistent
indentation and spacing, and follow naming conventions for private methods if
applicable. Also, verify that exception raising syntax and method definitions
conform to linting standards.

Comment on lines -170 to -215
@dataclass
class SpeakProvider(BaseResponse):
"""
This class defines the provider for the Speak model.
"""

type: Optional[str] = field(default="deepgram")
"""
Deepgram OR OpenAI model to use.
"""
model: Optional[str] = field(
default="aura-2-thalia-en",
metadata=dataclass_config(exclude=lambda f: f is None),
)
"""
ElevenLabs or Cartesia model to use.
"""
model_id: Optional[str] = field(
default=None, metadata=dataclass_config(exclude=lambda f: f is None)
)
"""
Cartesia voice configuration.
"""
voice: Optional[CartesiaVoice] = field(
default=None, metadata=dataclass_config(exclude=lambda f: f is None)
)
"""
Cartesia language.
"""
language: Optional[str] = field(
default=None, metadata=dataclass_config(exclude=lambda f: f is None)
)
"""
ElevenLabs language.
"""
language_code: Optional[str] = field(
default=None, metadata=dataclass_config(exclude=lambda f: f is None)
)

def __getitem__(self, key):
_dict = self.to_dict()
if "voice" in _dict and isinstance(_dict["voice"], dict):
_dict["voice"] = CartesiaVoice.from_dict(_dict["voice"])
return _dict[key]


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking of something along the lines of

from dataclasses import dataclass, field, asdict
from typing import Any, Dict

@dataclass
class SpeakProvider:
    """
    This class defines the provider for the Speak model.
    """
    
    """
    The provider type. The only truly mandatory property.
    Marked optional because it has a default value.
    """
    type: Optional[str] = field(default="deepgram")
    
    """
    Internal property to store arbitrary proprties
    """
    __extra: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self):
        known_fields = {f.name for f in self.__dataclass_fields__.values()}
        for key in list(self.__dict__):
            if key not in known_fields:
                self.__extra[key] = self.__dict__.pop(key)

    def __getitem__(self, key):
        if key == "type":
            return self.type
        return self.__extra[key]

    def __setitem__(self, key, value):
        if key == "type":
            self.type = value
        else:
            self.__extra[key] = value

    def to_dict(self):
        return {"type": self.type, **self.__extra}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants