-
Notifications
You must be signed in to change notification settings - Fork 84
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
base: main
Are you sure you want to change the base?
Conversation
""" WalkthroughThe changes remove the Changes
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
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
📒 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
todict
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.
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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.
@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] | ||
|
||
|
There was a problem hiding this comment.
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}
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 applyChecklist
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.Further comments
Summary by CodeRabbit
New Features
Refactor
Chores
SpeakProvider
class and related references from the codebase, reducing the number of predefined provider types.