Skip to content
2 changes: 2 additions & 0 deletions .fernignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Custom client implementation extending BaseClient with additional features:
# - access_token parameter support (Bearer token authentication)
# - auth=False for self-hosted servers without authentication (no key, no Authorization header)
# - Automatic session ID generation and header injection (x-deepgram-session-id)
# - transport_factory parameter for plugging in a custom WebSocket transport
# - reconnect flag (default True) — declarative flag indicating whether the SDK
Expand Down Expand Up @@ -280,6 +281,7 @@ tests/custom/test_model_dict_compat.py
tests/custom/test_query_encoder.py
tests/custom/test_regen_response_fields.py
tests/custom/test_secure_logging.py
tests/custom/test_self_hosted_no_auth.py
tests/custom/test_socket_client_shims.py
tests/custom/test_socket_unknown_fallback.py
tests/custom/test_speak_v2_connect_wire.py
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Current permanently frozen files:
- `tests/custom/test_query_encoder.py` — hand-written regression test that `core/query_encoder.py` coerces Python bools to lowercase `"true"`/`"false"` before `urlencode` so websocket query strings stay wire-correct
- `tests/custom/test_regen_response_fields.py` — hand-written regression test guarding response fields added by recent regenerations: `ListenV1Response/ResultsMetadata.diarize_info` (`model_uuid`, `arch`), per-word `speaker` / `speaker_confidence`, Nova-3 multilingual `languages` / `languages_hinted` / word and utterance `language`, and `ListenV2TurnInfo.trigger`. Same rationale as `test_latency_report_stt_compat.py`: `UncheckedBaseModel` + `skip_validation` makes response parsing lenient, so a future spec removal would silently turn these into `None` rather than failing. Fixtures are real captured payloads; the `trigger` cases pin the parsing contract for the values the server sends (`model` / `manual` / `timeout`) plus the absent case, which is what a deployment without ForceEndTurn enabled (self-hosted without the feature flag) returns. Live coverage of the same field lives in `tests/manual/listen/v2/force_end_turn/`
- `tests/custom/test_secure_logging.py` — hand-written regression test that the `websockets` Authorization-header DEBUG logs are redacted (API key never logged in clear text)
- `tests/custom/test_self_hosted_no_auth.py` — hand-written regression coverage for `auth=False` against generated API-key headers, caller-provided and per-request HTTP headers, supplied HTTPX client defaults/auth, HTTP streams, public/raw WebSocket paths, and custom transports. Keeps the self-hosted no-auth guarantee intact across sync and async clients.
- `tests/custom/test_socket_unknown_fallback.py` — hand-written regression coverage that every generated socket client returns an unknown server frame as a dictionary; Speak V1 remains a strict expected failure until Fern fixes the undiscriminated-union coercion tracked above
- `tests/custom/test_speak_v2_interrupt_configure.py` — hand-written coverage for the Speak V2 barge-in / mid-stream reconfigure surface (`send_interrupt`, `send_configure`, `SpeechInterrupted`, `ConfigureSuccess`/`ConfigureFailure`, and the `speed`/`expressivity` connect params)
- `tests/custom/test_voice_agent_force_end_turn_example.py` — hand-written regression coverage that the Voice Agent ForceEndTurn example waits for a rejection queued after `AgentAudioDone`
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,29 @@ The SDK automatically discovers credentials from these environment variables:

**Precedence:** Explicit parameters > Environment variables

### Self-Hosted Servers Without Authentication

A self-hosted or local Deepgram server may not require request authentication. Point the client at it with a custom environment and pass `auth=False` so the SDK doesn't ask for an API key:

```python
from deepgram import DeepgramClient
from deepgram.environment import DeepgramClientEnvironment

client = DeepgramClient(
environment=DeepgramClientEnvironment(
base="http://127.0.0.1:8000",
production="ws://127.0.0.1:8000",
agent="ws://127.0.0.1:8000",
agent_rest="http://127.0.0.1:8000",
),
auth=False,
)
```

With `auth=False` no `Authorization` header is sent on HTTP requests or WebSocket connections, and `DEEPGRAM_API_KEY` is ignored. It can't be combined with `api_key` or `access_token`; if your server does require a key, pass `api_key` as usual.

If you pass your own `httpx_client` with `auth=False`, the SDK removes authentication only from its requests to the configured Deepgram server. Other requests made with that client keep their `Authorization` header and `auth` setting.

## Async Client

The SDK provides full async/await support for non-blocking operations:
Expand Down
220 changes: 182 additions & 38 deletions src/deepgram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
- If `access_token` is provided, it takes precedence and sets `Authorization: bearer <token>`
- When `access_token` is used, `api_key` is forced to "token" to satisfy the generator,
but the Authorization header is overridden for all HTTP and WebSocket requests.
- `auth=False` for self-hosted or local Deepgram servers that don't require authentication:
- No API key is needed, and no Authorization header is sent on HTTP or WebSocket requests.
- When no key is available and the environment is not a Deepgram host, the missing-key
error suggests `auth=False`.
- `session_id` as a header sent with every request and websocket connection:
- If `session_id` is provided, it will be used; otherwise, a UUID is auto-generated
- The session_id is sent as the `x-deepgram-session-id` header
Expand All @@ -24,9 +28,11 @@

import os
import types
import urllib.parse
import uuid
from typing import Any, Callable, Dict, Optional

import httpx
from ._secure_logging import install_websocket_log_redaction
from .base_client import AsyncBaseClient, BaseClient
from .core.api_error import ApiError
Expand All @@ -35,6 +41,22 @@
from deepgram.core.client_wrapper import BaseClientWrapper


class _NoAuthorizationHeaders(Dict[str, str]):
"""A header map that permanently drops case-insensitive Authorization keys."""

def __init__(self, headers: Dict[str, str]) -> None:
super().__init__()
self.update(headers)

def __setitem__(self, key: str, value: str) -> None:
if key.lower() != "authorization":
super().__setitem__(key, value)

def update(self, *args: Any, **kwargs: str) -> None:
for key, value in dict(*args, **kwargs).items():
self[key] = value


def _apply_bearer_authorization_override(client_wrapper: BaseClientWrapper, bearer_token: str) -> None:
"""Override header providers to always use a Bearer authorization token.

Expand All @@ -57,6 +79,150 @@ def _get_headers_with_bearer(_self: Any) -> Dict[str, str]:
client_wrapper.httpx_client.base_headers = client_wrapper.get_headers


def _origin(url: str) -> Optional[tuple[str, str, Optional[int]]]:
try:
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in ("http", "https") or parsed.hostname is None:
return None
scheme = parsed.scheme.lower()
port = parsed.port
if (scheme == "http" and port == 80) or (scheme == "https" and port == 443):
port = None
return scheme, parsed.hostname.lower(), port
except ValueError:
return None


def _environment_origins(environment: Any) -> set[tuple[str, str, Optional[int]]]:
return {
origin
for name in ("base", "agent_rest")
if isinstance(url := getattr(environment, name, None), str)
if (origin := _origin(url)) is not None
}


def _remove_authorization_from_request(
request: httpx.Request, target_origins: set[tuple[str, str, Optional[int]]], session_id: str
) -> None:
# Normalize the request URL with the same helper used for the environment so an
# explicit default port survives httpx's scheme-case-sensitive port handling.
request_origin = _origin(str(request.url))
if request_origin not in target_origins or request.headers.get("x-deepgram-session-id") != session_id:
return

for header in list(request.headers):
if header.lower() == "authorization":
del request.headers[header]


def _install_no_authorization_request_hook(
httpx_client: Any, target_origins: set[tuple[str, str, Optional[int]]], session_id: str
) -> None:
"""Strip Authorization only from this client's requests to its Deepgram origins."""

def sync_request_hook(request: httpx.Request) -> None:
_remove_authorization_from_request(request, target_origins, session_id)

if isinstance(httpx_client, httpx.AsyncClient):

async def async_request_hook(request: httpx.Request) -> None:
_remove_authorization_from_request(request, target_origins, session_id)

httpx_client.event_hooks.setdefault("request", []).append(async_request_hook)
else:
httpx_client.event_hooks.setdefault("request", []).append(sync_request_hook)


def _apply_no_authorization_override(client_wrapper: BaseClientWrapper, session_id: str) -> None:
"""Drop the Authorization header from every HTTP and WebSocket request (``auth=False``)."""
original_get_headers = client_wrapper.get_headers

def _get_headers_without_auth(_self: Any) -> Dict[str, str]:
# Generated WebSocket clients append their per-call ``authorization`` and
# ``additional_headers`` after invoking this provider. Return a mapping
# that keeps suppressing the header through those later mutations.
return _NoAuthorizationHeaders(original_get_headers())

client_wrapper.get_headers = types.MethodType(_get_headers_without_auth, client_wrapper) # type: ignore[method-assign]

if hasattr(client_wrapper, "httpx_client") and hasattr(client_wrapper.httpx_client, "base_headers"):
client_wrapper.httpx_client.base_headers = client_wrapper.get_headers
_install_no_authorization_request_hook(
client_wrapper.httpx_client.httpx_client,
_environment_origins(client_wrapper.get_environment()),
session_id,
)


_MISSING_KEY_MESSAGE = "The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY"
_SELF_HOSTED_NO_AUTH_HINT = (
"If you are connecting to a self-hosted or local Deepgram server that does not require "
"authentication, pass auth=False when initializing the client."
)


def _is_deepgram_hosted(environment: Any) -> bool:
"""Whether the environment's REST base is Deepgram's hosted API.

Only an unset environment counts as hosted, because the client then uses
``DeepgramClientEnvironment.PRODUCTION``. A base that can't be parsed or has no host (for
example ``"127.0.0.1:8000"``, with the scheme left off) can never be Deepgram's host.
"""
if environment is None:
return True
base = getattr(environment, "base", None)
if not isinstance(base, str):
return False
try:
host = (urllib.parse.urlparse(base).hostname or "").lower()
except ValueError:
return False
return host == "deepgram.com" or host.endswith(".deepgram.com")


def _missing_key_error(environment: Any) -> ApiError:
body = _MISSING_KEY_MESSAGE
if not _is_deepgram_hosted(environment):
body = f"{body}. {_SELF_HOSTED_NO_AUTH_HINT}"
return ApiError(body=body)


def _resolve_credentials(kwargs: Dict[str, Any], access_token: Optional[str], auth: Any) -> None:
"""Fill ``kwargs["api_key"]`` for the generated base client, or raise if no credential is available.

Shared by the sync and async clients. The generated base client requires an api_key, so
``access_token`` and ``auth=False`` set a placeholder; the Authorization header is then
replaced (Bearer) or removed after construction.
"""
if auth is not None and auth is not False:
raise ValueError(
"auth only accepts False, which disables authentication for self-hosted servers. "
"To authenticate, omit auth and pass api_key or access_token."
)

environment = kwargs.get("environment")
if auth is False:
if access_token is not None or kwargs.get("api_key") is not None:
raise ValueError("auth=False cannot be combined with api_key or access_token")
kwargs["api_key"] = ""
elif access_token is not None:
# access_token takes precedence over api_key; the header becomes Bearer after construction.
if kwargs.get("api_key") is None:
kwargs["api_key"] = "token"
elif "api_key" in kwargs and kwargs["api_key"] is None:
# Fern now resolves None to DEEPGRAM_API_KEY in the base client. Preserve the SDK
# contract that an explicit None disables ambient lookup.
raise _missing_key_error(environment)
elif "api_key" not in kwargs:
# The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default argument, so
# it is read once at import. Re-read it here so a key set after import (load_dotenv below
# the imports) is still picked up.
kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY")
if kwargs["api_key"] is None:
raise _missing_key_error(environment)


class DeepgramClient(BaseClient):
"""
Custom Deepgram client that extends the generated BaseClient.
Expand All @@ -65,6 +231,8 @@ class DeepgramClient(BaseClient):
- `session_id`: Optional session identifier. If not provided, a UUID is auto-generated.
Sent as `x-deepgram-session-id` header in all requests and websocket connections.
- `access_token`: Alternative to `api_key`. If provided, uses Bearer token authentication.
- `auth`: Pass ``False`` for a self-hosted or local Deepgram server that doesn't require
authentication. No API key is needed and no Authorization header is sent.
- `transport_factory`: Custom sync WebSocket transport factory. A callable
``factory(url, headers) -> transport`` whose return value must support
``send()``, ``recv()``, iteration, and ``close()``.
Expand All @@ -83,6 +251,7 @@ class DeepgramClient(BaseClient):

def __init__(self, *args, **kwargs) -> None:
access_token: Optional[str] = kwargs.pop("access_token", None)
auth: Any = kwargs.pop("auth", None)
session_id: Optional[str] = kwargs.pop("session_id", None)
transport_factory: Optional[Callable] = kwargs.pop("transport_factory", None)
reconnect: bool = bool(kwargs.pop("reconnect", True))
Expand All @@ -109,31 +278,17 @@ def __init__(self, *args, **kwargs) -> None:
# Ensure every request has a session identifier header
headers["x-deepgram-session-id"] = final_session_id

# Handle access_token: if provided, it takes precedence over api_key
# The base client requires api_key, so we set a placeholder if needed
# The Authorization header will be overridden to use Bearer token
if access_token is not None:
# Set a placeholder api_key if none provided (base client requires it)
if kwargs.get("api_key") is None:
kwargs["api_key"] = "token"
elif "api_key" in kwargs and kwargs["api_key"] is None:
# Fern now resolves None to DEEPGRAM_API_KEY in BaseClient. Preserve
# the SDK contract that an explicit None disables ambient lookup.
raise ApiError(
body="The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY"
)
elif "api_key" not in kwargs:
# The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default
# argument, so it is read once at import. Re-read it here so a key set after
# import (load_dotenv below the imports) is still picked up.
kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY")
_resolve_credentials(kwargs, access_token, auth)

super().__init__(*args, **kwargs)
self.session_id = final_session_id

# Override Authorization header to use Bearer token if access_token was provided
# Override Authorization header to use Bearer token if access_token was provided,
# or drop it entirely for auth=False
if access_token is not None:
_apply_bearer_authorization_override(self._client_wrapper, access_token)
elif auth is False:
_apply_no_authorization_override(self._client_wrapper, final_session_id)

# Install custom WebSocket transport if provided. Auto-disable
# `reconnect`: a custom transport owns its retry lifecycle, so flip
Expand All @@ -155,6 +310,8 @@ class AsyncDeepgramClient(AsyncBaseClient):
- `session_id`: Optional session identifier. If not provided, a UUID is auto-generated.
Sent as `x-deepgram-session-id` header in all requests and websocket connections.
- `access_token`: Alternative to `api_key`. If provided, uses Bearer token authentication.
- `auth`: Pass ``False`` for a self-hosted or local Deepgram server that doesn't require
authentication. No API key is needed and no Authorization header is sent.
- `transport_factory`: Custom async WebSocket transport factory. A callable
``factory(url, headers) -> transport`` whose return value must support
``send()``, ``recv()``, async iteration, and ``close()``.
Expand All @@ -173,6 +330,7 @@ class AsyncDeepgramClient(AsyncBaseClient):

def __init__(self, *args, **kwargs) -> None:
access_token: Optional[str] = kwargs.pop("access_token", None)
auth: Any = kwargs.pop("auth", None)
session_id: Optional[str] = kwargs.pop("session_id", None)
transport_factory: Optional[Callable] = kwargs.pop("transport_factory", None)
reconnect: bool = bool(kwargs.pop("reconnect", True))
Expand All @@ -199,31 +357,17 @@ def __init__(self, *args, **kwargs) -> None:
# Ensure every request has a session identifier header
headers["x-deepgram-session-id"] = final_session_id

# Handle access_token: if provided, it takes precedence over api_key
# The base client requires api_key, so we set a placeholder if needed
# The Authorization header will be overridden to use Bearer token
if access_token is not None:
# Set a placeholder api_key if none provided (base client requires it)
if kwargs.get("api_key") is None:
kwargs["api_key"] = "token"
elif "api_key" in kwargs and kwargs["api_key"] is None:
# Fern now resolves None to DEEPGRAM_API_KEY in AsyncBaseClient.
# Preserve the SDK contract that explicit None disables ambient lookup.
raise ApiError(
body="The client must be instantiated by either passing in api_key or setting DEEPGRAM_API_KEY"
)
elif "api_key" not in kwargs:
# The generated base client takes os.getenv("DEEPGRAM_API_KEY") as a default
# argument, so it is read once at import. Re-read it here so a key set after
# import (load_dotenv below the imports) is still picked up.
kwargs["api_key"] = os.getenv("DEEPGRAM_API_KEY")
_resolve_credentials(kwargs, access_token, auth)

super().__init__(*args, **kwargs)
self.session_id = final_session_id

# Override Authorization header to use Bearer token if access_token was provided
# Override Authorization header to use Bearer token if access_token was provided,
# or drop it entirely for auth=False
if access_token is not None:
_apply_bearer_authorization_override(self._client_wrapper, access_token)
elif auth is False:
_apply_no_authorization_override(self._client_wrapper, final_session_id)

# Install custom WebSocket transport if provided. Auto-disable
# `reconnect`: a custom transport owns its retry lifecycle, so flip
Expand Down
Loading
Loading