Skip to content

Conversation

jpvajda
Copy link
Contributor

@jpvajda jpvajda commented Jul 17, 2025

PR Summary: Add TTL Support to grant_token Endpoint

TL;DR

  • Added optional ttl_seconds parameter (1-3600 range, default 30) to both sync and async grant_token() methods in the auth clients.
  • This allows users to specify custom token lifespans when requesting access tokens from the Deepgram API.
  • ⚠️ Known Issue: The ttl_seconds parameter doesn't work yet on api.deepgram.com but can be tested on manage.deepgram.com. This will be fixed soon.

Changes Made

Core Implementation

  • Modified AuthRESTClient.grant_token() in deepgram/clients/auth/v1/client.py

    • Added optional ttl_seconds: Optional[int] = None parameter
    • Added validation for integer type and 1-3600 range (excluding booleans)
    • Added request body handling with JSON payload {"ttl_seconds": value}
    • Updated method signature and documentation
  • Modified AsyncAuthRESTClient.grant_token() in deepgram/clients/auth/v1/async_client.py

    • Identical changes as sync client but with async/await syntax
    • Maintains feature parity between sync and async implementations

Validation Logic

  • Type validation: Ensures ttl_seconds is an integer, explicitly excluding Python booleans (which are int subclass)
  • Range validation: Enforces 1-3600 seconds range with clear error messages
  • Request body: Only includes ttl_seconds in JSON payload when parameter is provided

Examples Updated

  • examples/auth/token/main.py: Added comprehensive TTL testing (default, custom, min, max values)
  • examples/auth/async_token/main.py: Added async TTL testing scenarios
  • examples/auth/bearer_token_demo/main.py: Updated to demonstrate custom TTL in complete workflow

New Test Suite

  • tests/unit_test/test_unit_grant_token.py: Created dedicated test file with 14 comprehensive tests
    • TestGrantTokenTTL: Basic TTL functionality and validation
    • TestAsyncGrantTokenTTL: Async TTL functionality
    • TestGrantTokenRequestBody: Request body validation
    • TestGrantTokenEdgeCases: Edge cases and boundary testing

Files Modified

deepgram/clients/auth/v1/client.py
deepgram/clients/auth/v1/async_client.py
examples/auth/token/main.py
examples/auth/async_token/main.py
examples/auth/bearer_token_demo/main.py
tests/unit_test/test_unit_grant_token.py (new)

Testing

  • 14 new unit tests covering all TTL scenarios and edge cases
  • All existing tests pass (100 tests total) - no regressions
  • Real API testing through updated examples demonstrating live functionality
  • Both sync and async implementations thoroughly tested

Usage Examples

Basic Usage

# Default TTL (30 seconds)
response = client.auth.v1.grant_token()

# Custom TTL (5 minutes)
response = client.auth.v1.grant_token(ttl_seconds=300)

# Async usage
response = await async_client.auth.v1.grant_token(ttl_seconds=1800)

Request Body

When ttl_seconds is provided, the request includes:

{
  "ttl_seconds": 300
}

Backward Compatibility

  • No breaking changes - ttl_seconds parameter is optional
  • Default behavior unchanged - existing code continues to work
  • API compatibility maintained - follows existing patterns

Validation

  • Type: Must be integer (bool explicitly excluded)
  • Range: 1-3600 seconds (1 second to 1 hour)
  • Error handling: Clear error messages for invalid inputs

This implementation provides developers with fine-grained control over access token lifespans while maintaining full backward compatibility and robust error handling.

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 support for specifying a custom time-to-live (TTL) in seconds when generating access tokens, with input validation for allowed ranges.
  • Bug Fixes
    • Improved input validation for TTL values to prevent invalid token requests.
  • Documentation
    • Updated usage examples and docstrings to reflect the new TTL parameter and its valid range.
  • Tests
    • Introduced comprehensive tests to verify correct TTL handling, input validation, and authorization behavior for both synchronous and asynchronous clients.

@jpvajda jpvajda requested a review from lukeocodes July 17, 2025 18:48
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

The grant_token method in both synchronous and asynchronous authentication clients now accepts an optional ttl_seconds parameter, allowing the specification of token time-to-live between 1 and 3600 seconds. Input validation is enforced, and the request body is conditionally constructed. Example scripts and a comprehensive unit test suite were updated or added to cover these changes.

Changes

File(s) Change Summary
deepgram/clients/auth/v1/async_client.py, deepgram/clients/auth/v1/client.py Updated grant_token method to accept optional ttl_seconds, added input validation, and conditional request body.
examples/auth/async_token/main.py, examples/auth/token/main.py Added test calls for grant_token with various TTL values and updated output messages.
examples/auth/bearer_token_demo/main.py Modified to explicitly request access token with ttl_seconds=600 and updated print statements.
tests/unit_test/test_unit_grant_token.py New unit test suite covering grant_token TTL handling, input validation, request formatting, and authorization.
tests/response_data/listen/rest/.json, tests/response_data/listen/websocket/.json Updated metadata (request_id, created, etc.) and, in one case, transcript content and timing in test response files.
tests/response_data/read/rest/*.json Expanded summary text, corrected phrasing, updated metadata, and increased output token count in test responses.
tests/response_data/speak/rest/*.json Updated "request_id" and "date" fields in test response JSON.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Client
    participant AuthRESTClient

    User->>Client: call grant_token(ttl_seconds)
    Client->>AuthRESTClient: grant_token(ttl_seconds)
    alt ttl_seconds is valid or None
        AuthRESTClient->>AuthRESTClient: validate ttl_seconds
        AuthRESTClient->>AuthRESTClient: build request body (with or without ttl_seconds)
        AuthRESTClient->>AuthRESTClient: send POST /token request
        AuthRESTClient-->>Client: return token response
        Client-->>User: return token
    else ttl_seconds is invalid
        AuthRESTClient->>AuthRESTClient: raise ValueError
        AuthRESTClient-->>Client: exception
        Client-->>User: exception
    end
Loading

Possibly related PRs

  • deepgram/deepgram-python-sdk#517: Adds foundational authentication client classes that are extended in this PR to support the ttl_seconds parameter and related validation logic.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (3.3.7)
deepgram/clients/auth/v1/async_client.py
deepgram/clients/auth/v1/client.py

📜 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 76939cf and 8653a04.

📒 Files selected for processing (2)
  • deepgram/clients/auth/v1/async_client.py (2 hunks)
  • deepgram/clients/auth/v1/client.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • deepgram/clients/auth/v1/async_client.py
  • deepgram/clients/auth/v1/client.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/grant-ttl-support

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 auto-generate unit tests to generate unit tests for 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: 0

🧹 Nitpick comments (5)
tests/response_data/speak/rest/1fe0ad339338a9d6cffbab2c7ace41ba5387b5fe7906854795702dce91034fd3-f8c3bf62a9aa3e6fc1619c250e48abe7519373d3edf41be62eb5dc45199af2ef-response.json (1)

1-1: Consider normalizing volatile fields in recorded fixtures

request_id and date change on every live call, so committing them verbatim makes future snapshot updates noisy. Stripping or stubbing these values (e.g., "request_id": "<any>", fixed epoch) keeps diffs minimal and avoids unnecessary fixture churn while still testing payload structure.

If you agree, I can draft a helper that post-processes TTS fixtures to blank these fields before committing.

tests/response_data/listen/rest/c4e1c0031174878d8f0e3dbd87916ee16d56f1c610ac525af5712ea37226a455-29e7c8100617f70da4ae9da1921cb5071a01219f4780ca70930b0a370ed2163a-response.json (1)

1-1: Strip volatile metadata to keep fixtures stable

request_id and created are inherently dynamic. Keeping them in committed fixtures guarantees noisy diffs on every regeneration and inflates review churn. Consider redacting or normalising these fields (e.g., "request_id": "<ignored>", "created": 0) before committing.

-  "request_id": "426529dd-f7d5-4295-99ea-6c6baf31721e",
-  "created": "2025-07-17T15:22:05.147Z",
+  "request_id": "<ignored>",
+  "created": 0,

Most snapshot/fixture libraries allow post-processing hooks—worth using here.

tests/response_data/listen/rest/a231370d439312b1a404bb6ad8de955e900ec8eae9a906329af8cc672e6ec7ba-29e7c8100617f70da4ae9da1921cb5071a01219f4780ca70930b0a370ed2163a-response.json (1)

1-1: Volatile metadata fields (request_id, created, sha256) make fixtures noisy.

These auto-generated values change on every recording, so any small re-capture forces an otherwise meaningless diff and pollutes PR history. Consider:

  1. Trimming/omitting volatile keys when serialising fixtures;
  2. Replacing them with deterministic placeholders (e.g. "REQUEST_ID_PLACEHOLDER"); or
  3. Normalising them inside the test harness (load JSON, overwrite the keys before comparison).

This keeps test data stable and reviews cleaner without losing coverage.

tests/response_data/listen/rest/a231370d439312b1a404bb6ad8de955e900ec8eae9a906329af8cc672e6ec7ba-a17f4880c5b4cf124ac54d06d77c9f0ab7f3fe1052ff1c7b090f7eaf8ede5b76-response.json (1)

1-1: Pretty-print fixture for maintainability

The entire JSON blob is stored on a single line. This makes diffs noisy (e.g., this change touches the whole file even though only a couple of fields were updated) and hard to review manually. Storing fixtures in a consistent, multi-line, indented format keeps future diffs minimal and readable.

-{"metadata": {...}}
+{
+  "metadata": {
+    ...
+  },
+  "results": {
+    ...
+  }
+}

A one-liner is fine at runtime, but in VCS a formatted version will save time for reviewers.

tests/response_data/listen/rest/c4e1c0031174878d8f0e3dbd87916ee16d56f1c610ac525af5712ea37226a455-a17f4880c5b4cf124ac54d06d77c9f0ab7f3fe1052ff1c7b090f7eaf8ede5b76-response.json (1)

1-1: Volatile metadata & single-line JSON make the fixture noisy and fragile

The only differences from the previous revision are values such as request_id, created, and some minor floating-point drift. These fields change on every real request, so committing the updated blob provides no coverage benefit and bloats diffs. Unit tests that need the transcript can:

  1. Strip/ignore known-volatile keys (request_id, created, maybe confidences beyond a tolerance) instead of snapshotting them.
  2. Store the fixture in a pretty-printed, multi-line format (json.dumps(obj, indent=2, sort_keys=True)) for readability and to minimise diff noise.

Consider regenerating the fixture with stable values or validating only the deterministic parts (transcript text, model id, word count, etc.) to keep future PRs clean.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between eca4b1e and 76939cf.

⛔ Files ignored due to path filters (1)
  • tests/response_data/speak/rest/1fe0ad339338a9d6cffbab2c7ace41ba5387b5fe7906854795702dce91034fd3-f8c3bf62a9aa3e6fc1619c250e48abe7519373d3edf41be62eb5dc45199af2ef.wav is excluded by !**/*.wav
📒 Files selected for processing (15)
  • deepgram/clients/auth/v1/async_client.py (1 hunks)
  • deepgram/clients/auth/v1/client.py (1 hunks)
  • examples/auth/async_token/main.py (1 hunks)
  • examples/auth/bearer_token_demo/main.py (1 hunks)
  • examples/auth/token/main.py (1 hunks)
  • tests/response_data/listen/rest/a231370d439312b1a404bb6ad8de955e900ec8eae9a906329af8cc672e6ec7ba-29e7c8100617f70da4ae9da1921cb5071a01219f4780ca70930b0a370ed2163a-response.json (1 hunks)
  • tests/response_data/listen/rest/a231370d439312b1a404bb6ad8de955e900ec8eae9a906329af8cc672e6ec7ba-a17f4880c5b4cf124ac54d06d77c9f0ab7f3fe1052ff1c7b090f7eaf8ede5b76-response.json (1 hunks)
  • tests/response_data/listen/rest/c4e1c0031174878d8f0e3dbd87916ee16d56f1c610ac525af5712ea37226a455-29e7c8100617f70da4ae9da1921cb5071a01219f4780ca70930b0a370ed2163a-response.json (1 hunks)
  • tests/response_data/listen/rest/c4e1c0031174878d8f0e3dbd87916ee16d56f1c610ac525af5712ea37226a455-a17f4880c5b4cf124ac54d06d77c9f0ab7f3fe1052ff1c7b090f7eaf8ede5b76-response.json (1 hunks)
  • tests/response_data/listen/websocket/ed5bfd217988aa8cad492f63f79dc59f5f02fb9b85befe6f6ce404b8f19aaa0d-42fc5ed98cabc1fa1a2f276301c27c46dd15f6f5187cd93d944cc94fa81c8469-response.json (1 hunks)
  • tests/response_data/listen/websocket/ed5bfd217988aa8cad492f63f79dc59f5f02fb9b85befe6f6ce404b8f19aaa0d-d7334c26cf6468c191e05ff5e8151da9b67985c66ab177e9446fd14bbafd70df-response.json (1 hunks)
  • tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-error.json (1 hunks)
  • tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-response.json (1 hunks)
  • tests/response_data/speak/rest/1fe0ad339338a9d6cffbab2c7ace41ba5387b5fe7906854795702dce91034fd3-f8c3bf62a9aa3e6fc1619c250e48abe7519373d3edf41be62eb5dc45199af2ef-response.json (1 hunks)
  • tests/unit_test/test_unit_grant_token.py (1 hunks)
🧰 Additional context used
🧠 Learnings (10)
📓 Common learnings
Learnt from: lukeocodes
PR: deepgram/deepgram-python-sdk#543
File: tests/unit_test/test_unit_authentication.py:67-87
Timestamp: 2025-06-22T17:02:32.416Z
Learning: When both api_key and access_token are explicitly provided via named parameters in the Deepgram Python SDK, access tokens should take precedence according to the documented priority order: explicit access_token parameter (highest), explicit api_key parameter, DEEPGRAM_ACCESS_TOKEN environment variable, and DEEPGRAM_API_KEY environment variable (lowest).
examples/auth/async_token/main.py (6)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-10-09T02:19:48.728Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-06-12T18:02:10.651Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/client.py:81-81
Timestamp: 2024-06-27T00:06:01.811Z
Learning: Imports for SpeakStreamClient and AsyncSpeakStreamClient in `deepgram/client.py` are necessary for export purposes and should not be flagged as unused in reviews.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/client.py:81-81
Timestamp: 2024-10-09T02:19:46.087Z
Learning: Imports for SpeakStreamClient and AsyncSpeakStreamClient in `deepgram/client.py` are necessary for export purposes and should not be flagged as unused in reviews.
Learnt from: lukeocodes
PR: deepgram/deepgram-python-sdk#543
File: tests/unit_test/test_unit_authentication.py:67-87
Timestamp: 2025-06-22T17:02:32.416Z
Learning: When both api_key and access_token are explicitly provided via named parameters in the Deepgram Python SDK, access tokens should take precedence according to the documented priority order: explicit access_token parameter (highest), explicit api_key parameter, DEEPGRAM_ACCESS_TOKEN environment variable, and DEEPGRAM_API_KEY environment variable (lowest).
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#472
File: examples/speech-to-text/websocket/replay/main.py:78-80
Timestamp: 2024-10-18T16:20:17.742Z
Learning: In the `examples` directory of the Deepgram Python SDK, code is intended as illustrative examples and doesn't require production-level error handling.
examples/auth/token/main.py (8)
Learnt from: lukeocodes
PR: deepgram/deepgram-python-sdk#543
File: tests/unit_test/test_unit_authentication.py:67-87
Timestamp: 2025-06-22T17:02:32.416Z
Learning: When both api_key and access_token are explicitly provided via named parameters in the Deepgram Python SDK, access tokens should take precedence according to the documented priority order: explicit access_token parameter (highest), explicit api_key parameter, DEEPGRAM_ACCESS_TOKEN environment variable, and DEEPGRAM_API_KEY environment variable (lowest).
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-10-09T02:19:48.728Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-06-12T18:02:10.651Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#472
File: examples/speech-to-text/websocket/replay/main.py:78-80
Timestamp: 2024-10-18T16:20:17.742Z
Learning: In the `examples` directory of the Deepgram Python SDK, code is intended as illustrative examples and doesn't require production-level error handling.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/speak/__init__.py:16-19
Timestamp: 2024-10-09T02:19:46.087Z
Learning: Unused imports in `deepgram/clients/speak/__init__.py` are retained for backward compatibility and should not be flagged for removal in reviews.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/speak/__init__.py:16-19
Timestamp: 2024-07-01T19:12:57.715Z
Learning: Unused imports in `deepgram/clients/speak/__init__.py` are retained for backward compatibility and should not be flagged for removal in reviews.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/listen/v1/__init__.py:36-43
Timestamp: 2024-10-09T02:19:46.086Z
Learning: Unused imports in `deepgram/clients/listen/v1/__init__.py` are retained to maintain backward compatibility and should not be flagged for removal in reviews.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/listen/v1/__init__.py:36-43
Timestamp: 2024-07-01T19:17:04.194Z
Learning: Unused imports in `deepgram/clients/listen/v1/__init__.py` are retained to maintain backward compatibility and should not be flagged for removal in reviews.
tests/response_data/speak/rest/1fe0ad339338a9d6cffbab2c7ace41ba5387b5fe7906854795702dce91034fd3-f8c3bf62a9aa3e6fc1619c250e48abe7519373d3edf41be62eb5dc45199af2ef-response.json (3)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#472
File: examples/text-to-speech/websocket/output_to_wav/main.py:16-17
Timestamp: 2024-10-18T00:30:20.224Z
Learning: In `examples/text-to-speech/websocket/output_to_wav/main.py`, the hardcoded values for `AUDIO_FILE` and `TTS_TEXT` are intentional and should remain as is.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#472
File: examples/text-to-speech/websocket/output_to_wav/main.py:52-56
Timestamp: 2024-10-18T00:30:04.220Z
Learning: In `examples/text-to-speech/websocket/output_to_wav/main.py`, the code is intended as an example demonstrating functionality, and refactoring suggestions may not be necessary.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#472
File: examples/text-to-speech/websocket/output_to_wav/main.py:38-41
Timestamp: 2024-10-18T00:30:01.884Z
Learning: In the `examples/text-to-speech/websocket/output_to_wav/main.py` file, the code is intended as a simple example, and additional error handling for file operations is not required.
deepgram/clients/auth/v1/client.py (1)
Learnt from: lukeocodes
PR: deepgram/deepgram-python-sdk#543
File: tests/unit_test/test_unit_authentication.py:67-87
Timestamp: 2025-06-22T17:02:32.416Z
Learning: When both api_key and access_token are explicitly provided via named parameters in the Deepgram Python SDK, access tokens should take precedence according to the documented priority order: explicit access_token parameter (highest), explicit api_key parameter, DEEPGRAM_ACCESS_TOKEN environment variable, and DEEPGRAM_API_KEY environment variable (lowest).
tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-response.json (2)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/clients/speak/v1/response.py:48-209
Timestamp: 2024-10-09T02:19:48.728Z
Learning: User dvonthenen prefers to defer certain suggestions, specifically regarding error handling and documentation enhancements in new data classes of `deepgram/clients/speak/v1/response.py`, and may revisit them later.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/clients/speak/v1/response.py:48-209
Timestamp: 2024-06-27T00:06:23.128Z
Learning: User dvonthenen prefers to defer certain suggestions, specifically regarding error handling and documentation enhancements in new data classes of `deepgram/clients/speak/v1/response.py`, and may revisit them later.
tests/response_data/listen/websocket/ed5bfd217988aa8cad492f63f79dc59f5f02fb9b85befe6f6ce404b8f19aaa0d-42fc5ed98cabc1fa1a2f276301c27c46dd15f6f5187cd93d944cc94fa81c8469-response.json (2)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/listen/v1/websocket/__init__.py:8-8
Timestamp: 2024-07-01T19:21:39.778Z
Learning: Unused imports in `deepgram/clients/listen/v1/websocket/__init__.py` are retained to maintain backward compatibility and should not be flagged for removal in reviews.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#426
File: deepgram/clients/listen/v1/websocket/__init__.py:8-8
Timestamp: 2024-10-09T02:19:46.086Z
Learning: Unused imports in `deepgram/clients/listen/v1/websocket/__init__.py` are retained to maintain backward compatibility and should not be flagged for removal in reviews.
deepgram/clients/auth/v1/async_client.py (1)
Learnt from: lukeocodes
PR: deepgram/deepgram-python-sdk#543
File: tests/unit_test/test_unit_authentication.py:67-87
Timestamp: 2025-06-22T17:02:32.416Z
Learning: When both api_key and access_token are explicitly provided via named parameters in the Deepgram Python SDK, access tokens should take precedence according to the documented priority order: explicit access_token parameter (highest), explicit api_key parameter, DEEPGRAM_ACCESS_TOKEN environment variable, and DEEPGRAM_API_KEY environment variable (lowest).
tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-error.json (2)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/clients/speak/v1/response.py:48-209
Timestamp: 2024-10-09T02:19:48.728Z
Learning: User dvonthenen prefers to defer certain suggestions, specifically regarding error handling and documentation enhancements in new data classes of `deepgram/clients/speak/v1/response.py`, and may revisit them later.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#424
File: deepgram/clients/speak/v1/response.py:48-209
Timestamp: 2024-06-27T00:06:23.128Z
Learning: User dvonthenen prefers to defer certain suggestions, specifically regarding error handling and documentation enhancements in new data classes of `deepgram/clients/speak/v1/response.py`, and may revisit them later.
tests/unit_test/test_unit_grant_token.py (2)
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-10-09T02:19:48.728Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
Learnt from: dvonthenen
PR: deepgram/deepgram-python-sdk#417
File: deepgram/clients/live/v1/client.py:14-14
Timestamp: 2024-06-12T18:02:10.651Z
Learning: Ignore suggestions to change import paths to local versions in test cases and examples as per user preference to use the actual `deepgram-sdk` package for testing.
🧬 Code Graph Analysis (4)
examples/auth/token/main.py (2)
deepgram/client.py (2)
  • auth (538-542)
  • v (628-697)
deepgram/clients/auth/v1/client.py (1)
  • grant_token (31-78)
deepgram/clients/auth/v1/client.py (1)
deepgram/clients/auth/v1/async_client.py (1)
  • grant_token (31-78)
deepgram/clients/auth/v1/async_client.py (1)
deepgram/clients/auth/v1/client.py (1)
  • grant_token (31-78)
tests/unit_test/test_unit_grant_token.py (3)
deepgram/client.py (3)
  • DeepgramClient (408-699)
  • auth (538-542)
  • asyncauth (545-549)
deepgram/clients/auth/v1/async_client.py (1)
  • grant_token (31-78)
deepgram/clients/auth/v1/client.py (1)
  • grant_token (31-78)
🔇 Additional comments (20)
tests/response_data/listen/rest/a231370d439312b1a404bb6ad8de955e900ec8eae9a906329af8cc672e6ec7ba-a17f4880c5b4cf124ac54d06d77c9f0ab7f3fe1052ff1c7b090f7eaf8ede5b76-response.json (1)

1-1: Confirm necessity of metadata churn

Only request_id and created values appear to have changed. If these fields are not functionally relevant for the assertions in your tests, consider stripping or stubbing them out so the file doesn’t need to change on every regeneration, which reduces commit noise and risk of merge conflicts.

tests/response_data/listen/websocket/ed5bfd217988aa8cad492f63f79dc59f5f02fb9b85befe6f6ce404b8f19aaa0d-d7334c26cf6468c191e05ff5e8151da9b67985c66ab177e9446fd14bbafd70df-response.json (1)

1-1: LGTM: Routine test data maintenance

This is a standard metadata update refreshing the request_id field in the websocket response test data, which is common maintenance for test fixtures.

tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-response.json (1)

1-1: LGTM: Test data enhancement

This update includes both metadata refresh (request_id, timestamp) and content improvements to the summary text. The enhanced content and increased token count (112→146) reflect legitimate improvements to the test data.

tests/response_data/listen/websocket/ed5bfd217988aa8cad492f63f79dc59f5f02fb9b85befe6f6ce404b8f19aaa0d-42fc5ed98cabc1fa1a2f276301c27c46dd15f6f5187cd93d944cc94fa81c8469-response.json (1)

1-1: LGTM: Test data content update

This update replaces the transcript content and associated timing/confidence data with new audio segment results. The JSON structure remains consistent and the change appears to be legitimate test data maintenance.

examples/auth/bearer_token_demo/main.py (1)

33-35: LGTM: Excellent demonstration of TTL functionality

The example properly demonstrates the new ttl_seconds parameter with a reasonable value (600 seconds) and clear documentation through comments and print statements.

examples/auth/async_token/main.py (1)

26-44: LGTM: Comprehensive TTL demonstration

This example excellently demonstrates the new TTL functionality with multiple test cases covering default behavior, custom values, and boundary conditions. The async/await usage is correct and the descriptive output helps users understand the feature.

examples/auth/token/main.py (1)

25-43: Excellent comprehensive demonstration of the TTL feature!

The example effectively showcases all key aspects of the new ttl_seconds parameter:

  • Default behavior without specifying TTL
  • Custom TTL values (300 seconds)
  • Boundary testing with minimum (1 second) and maximum (3600 seconds) values
  • Clear output messages for each test case

This provides developers with a complete understanding of how to use the TTL feature.

tests/response_data/read/rest/3917a1c81c08e360c0d4bba0ff9ebd645e610e4149483e5f2888a2c5df388b37-23e873efdfd4d680286fda14ff8f10864218311e79efc92ecc82bce3e574c366-error.json (1)

1-1: Test fixture content improvements look good.

The updates to the response data improve terminology ("voice-premises" correction) and add relevant product mentions. The JSON structure is valid and the content enhancements appear appropriate for test fixtures.

deepgram/clients/auth/v1/async_client.py (4)

31-31: Method signature updated correctly for TTL support.

The addition of the optional ttl_seconds parameter with proper type annotation is well-implemented.


33-44: Excellent docstring documentation.

The docstring clearly explains:

  • Parameter purpose and constraints (1-3600 seconds)
  • Default behavior (30 seconds)
  • Exception types and conditions

48-51: Robust input validation implementation.

The validation correctly:

  • Checks for integer type while excluding booleans (important since bool is a subclass of int in Python)
  • Validates the range constraints (1-3600 seconds)
  • Raises appropriate ValueError with clear message

56-71: Proper conditional request body construction.

The implementation correctly:

  • Constructs request body only when ttl_seconds is provided
  • Uses appropriate request paths (with/without JSON body)
  • Maintains proper authorization headers in both cases

This ensures backward compatibility while adding the new functionality.

deepgram/clients/auth/v1/client.py (4)

31-31: Method signature correctly updated for TTL support.

The addition of the optional ttl_seconds parameter maintains backward compatibility while adding the new functionality.


33-44: Comprehensive docstring documentation.

The docstring mirrors the async version and provides clear information about parameter constraints, default behavior, and exception handling.


48-51: Consistent input validation with async implementation.

The validation logic is identical to the async version, ensuring consistent behavior across both client types. The boolean exclusion is particularly important for preventing True/False values from being treated as 1/0.


56-71: Proper request handling with conditional body construction.

The implementation correctly handles both scenarios:

  • Sends JSON body when ttl_seconds is provided
  • Sends request without body when using default TTL
  • Maintains proper authorization headers in both cases

This ensures backward compatibility and optimal request formatting.

tests/unit_test/test_unit_grant_token.py (4)

11-123: Excellent comprehensive test coverage for sync TTL functionality.

The TestGrantTokenTTL class provides thorough coverage:

  • Default TTL behavior testing
  • Custom TTL values with proper mocking
  • Validation of valid boundary values (1, 30, 300, 1800, 3600)
  • Invalid value testing with appropriate error messages
  • Complete workflow testing from API key to access token with proper authorization headers

The test structure is well-organized and uses proper mocking to isolate the unit tests.


125-182: Comprehensive async TTL functionality testing.

The TestAsyncGrantTokenTTL class properly tests the async implementation:

  • Uses @pytest.mark.asyncio decorator correctly
  • Tests default and custom TTL behavior
  • Validates error handling for invalid values
  • Maintains consistency with sync test patterns

The async tests ensure both client types behave identically.


184-255: Thorough request body formatting validation.

The TestGrantTokenRequestBody class excellently tests:

  • Proper inclusion of ttl_seconds in request body when provided
  • Correct omission of JSON body when using default TTL
  • Authorization header formatting verification
  • Both sync and async request formatting

This ensures the API requests are properly formatted for the backend.


257-304: Comprehensive edge case and validation testing.

The TestGrantTokenEdgeCases class provides excellent coverage of:

  • Boundary value testing (1 and 3600 seconds)
  • Type validation for various invalid types (strings, floats, lists, dicts, booleans)
  • Range validation for out-of-bounds values
  • Proper error message verification

This thorough validation testing ensures robust input handling and clear error messages for developers.

Copy link
Contributor

@lukeocodes lukeocodes left a comment

Choose a reason for hiding this comment

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

good tests, good impl, good :)

@jpvajda jpvajda merged commit e9bedf2 into main Jul 18, 2025
5 checks passed
@jpvajda jpvajda deleted the feat/grant-ttl-support branch July 18, 2025 15:58
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