Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement elevenlabs import source (#69624)

Tom Owersd7bd80eab5ef
diff --git a/frontend/public/services/elevenlabs.svg b/frontend/public/services/elevenlabs.svg
new file mode 100644
index 000000000000..d44617dbde15
--- /dev/null
+++ b/frontend/public/services/elevenlabs.svg
@@ -0,0 +1 @@
+<svg fill="#000000" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>ElevenLabs</title><path d="M4.6035 0v24h4.9317V0zm9.8613 0v24h4.9317V0z"/></svg>
\ No newline at end of file
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2ba09abcfa63..75388f717068 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -145,6 +145,7 @@ the row lists both.
| e_conomic | HTTP | requests | ✅ |
| easypost | HTTP | requests | ✅ |
| easypromos | HTTP | requests | ✅ |
+| elevenlabs | HTTP | requests | ✅ |
| freshcaller | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
| freshsales | HTTP | requests | ✅ |
@@ -524,7 +525,6 @@ doesn't conflict with concurrent PRs.
- dynamodb
- e2b
- ebay
-- elevenlabs
- eloqua
- employment_hero
- encharge
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py
new file mode 100644
index 000000000000..37799d3b4bb7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/canonical_descriptions.py
@@ -0,0 +1,127 @@
+"""Canonical, documentation-sourced descriptions for ElevenLabs endpoints and columns.
+
+Sourced from the official ElevenLabs API reference (https://elevenlabs.io/docs/api-reference)
+and the published OpenAPI spec (https://api.elevenlabs.io/openapi.json). Keyed by the endpoint
+names in `settings.py` `ELEVENLABS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced ElevenLabs table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "history": {
+ "description": "A single speech generation (text-to-speech, speech-to-speech, or other audio product) with the input text, the voice and model used, and its character cost.",
+ "docs_url": "https://elevenlabs.io/docs/api-reference/history/list",
+ "columns": {
+ "history_item_id": "Unique identifier for the history item.",
+ "request_id": "The ID of the request that produced this item.",
+ "voice_id": "The ID of the voice used for the generation.",
+ "voice_name": "The name of the voice used for the generation.",
+ "voice_category": "The category of the voice: premade, cloned, generated, or professional.",
+ "model_id": "The ID of the model used for the generation.",
+ "text": "The text used to generate the audio item.",
+ "date_unix": "Unix timestamp (seconds) of when the item was created.",
+ "character_count_change_from": "The account's character count before this generation.",
+ "character_count_change_to": "The account's character count after this generation; the difference is the character cost of the item.",
+ "content_type": "The content type of the generated item.",
+ "state": "The state of the history item.",
+ "settings": "The voice settings used for the generation.",
+ "feedback": "Feedback associated with the generated item, null if none was provided.",
+ "share_link_id": "The ID of the share link for the item, if shared.",
+ "source": "The product that generated the item: TTS (text to speech), STS (speech to speech), Projects, AN (audio native), and others.",
+ "alignments": "Character alignment timing data for the generated audio.",
+ "dialogue": "The voice and text pairs used to generate the audio when the item was created via dialogue mode.",
+ "output_format": "The output format the audio was originally generated in.",
+ },
+ },
+ "conversations": {
+ "description": "A conversational AI conversation summary: which agent handled the call, when it started, how long it lasted, its status, and evaluation results.",
+ "docs_url": "https://elevenlabs.io/docs/api-reference/conversations/list",
+ "columns": {
+ "conversation_id": "Unique identifier for the conversation.",
+ "agent_id": "The ID of the agent that handled the conversation.",
+ "agent_name": "The name of the agent that handled the conversation.",
+ "branch_id": "The ID of the agent branch used for the conversation.",
+ "version_id": "The ID of the agent version used for the conversation.",
+ "start_time_unix_secs": "Unix timestamp (seconds) of when the conversation started.",
+ "call_duration_secs": "Duration of the call in seconds.",
+ "message_count": "Number of messages exchanged in the conversation.",
+ "status": "Processing status of the conversation (e.g. initiated, in-progress, processing, done, failed).",
+ "termination_reason": "Why the conversation ended.",
+ "call_successful": "Result of the agent's success evaluation for the call: success, failure, or unknown.",
+ "call_success_score": "Numeric success score assigned to the call.",
+ "transcript_summary": "Generated summary of the conversation transcript.",
+ "call_summary_title": "Short generated title summarizing the call.",
+ "main_language": "Detected main language of the conversation (language code).",
+ "conversation_initiation_source": "The surface the conversation was initiated from (e.g. phone, widget).",
+ "tool_names": "Names of the tools the agent used during the call.",
+ "direction": "Telephony direction of the call: inbound or outbound.",
+ "rating": "Overall user rating of the conversation (1-5).",
+ "sentiment_analysis": "Sentiment analysis results for the conversation.",
+ },
+ },
+ "agents": {
+ "description": "A conversational AI agent configured in the workspace, with its tags, creation time, and access information.",
+ "docs_url": "https://elevenlabs.io/docs/api-reference/agents/list",
+ "columns": {
+ "agent_id": "Unique identifier for the agent.",
+ "name": "The name of the agent.",
+ "tags": "Agent tags used to categorize the agent.",
+ "created_at_unix_secs": "Unix timestamp (seconds) of when the agent was created.",
+ "access_info": "The access information of the agent (creator, role).",
+ "last_call_time_unix_secs": "Unix timestamp (seconds) of the agent's most recent call, null if no calls have been made.",
+ "archived": "Whether the agent is archived.",
+ },
+ },
+ "voices": {
+ "description": "A voice available to the workspace: premade, cloned, generated, or professional, with its settings, labels, and sharing state.",
+ "docs_url": "https://elevenlabs.io/docs/api-reference/voices/search",
+ "columns": {
+ "voice_id": "Unique identifier for the voice.",
+ "name": "The name of the voice.",
+ "category": "The category of the voice: premade, cloned, generated, or professional.",
+ "description": "The description of the voice.",
+ "labels": "Labels associated with the voice (e.g. accent, age, gender).",
+ "samples": "List of audio samples associated with the voice.",
+ "settings": "The default generation settings of the voice.",
+ "sharing": "The sharing information of the voice.",
+ "fine_tuning": "Fine-tuning state and information for the voice.",
+ "preview_url": "URL of a preview audio clip for the voice.",
+ "available_for_tiers": "The subscription tiers the voice is available for.",
+ "high_quality_base_model_ids": "The base model IDs for high-quality renditions of this voice.",
+ "verified_languages": "The verified languages of the voice.",
+ "collection_ids": "The IDs of collections this voice belongs to.",
+ "is_owner": "Whether the voice is owned by the authenticated user.",
+ "is_legacy": "Whether the voice is a legacy voice.",
+ "is_mixed": "Whether the voice is a mixed voice.",
+ "created_at_unix": "Unix timestamp (seconds) of when the voice was created, null for older voices.",
+ "favorited_at_unix": "Unix timestamp (seconds) of when the voice was marked as favorite.",
+ "permission_on_resource": "The authenticated user's permission on the voice resource.",
+ },
+ },
+ "models": {
+ "description": "A speech model available on the account, with its capabilities, language support, and cost factor.",
+ "docs_url": "https://elevenlabs.io/docs/api-reference/models/list",
+ "columns": {
+ "model_id": "Unique identifier for the model.",
+ "name": "The name of the model.",
+ "description": "The description of the model.",
+ "can_be_finetuned": "Whether the model can be fine-tuned.",
+ "can_do_text_to_speech": "Whether the model can do text-to-speech.",
+ "can_do_voice_conversion": "Whether the model can do voice conversion.",
+ "can_use_style": "Whether the model supports style exaggeration.",
+ "can_use_speaker_boost": "Whether the model supports speaker boost.",
+ "serves_pro_voices": "Whether the model serves professional voices.",
+ "token_cost_factor": "The credit cost factor for the model.",
+ "requires_alpha_access": "Whether the model requires alpha access.",
+ "max_characters_request_free_user": "The maximum number of characters a free user can request per generation.",
+ "max_characters_request_subscribed_user": "The maximum number of characters a subscribed user can request per generation.",
+ "maximum_text_length_per_request": "The maximum length of text that can be requested for this model.",
+ "languages": "The languages supported by the model.",
+ "model_rates": "The billing rates for the model.",
+ "concurrency_group": "The concurrency group the model belongs to for rate limiting.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py
new file mode 100644
index 000000000000..3adbc6e47e51
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py
@@ -0,0 +1,223 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import (
+ ELEVENLABS_ENDPOINTS,
+ ElevenLabsEndpointConfig,
+)
+
+ELEVENLABS_BASE_URL = "https://api.elevenlabs.io"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class ElevenLabsRetryableError(Exception):
+ pass
+
+
+class ElevenLabsResumeConfig:
+ # Opaque pagination cursor of the next page to fetch. Only the cursor is persisted — the
+ # request URL is rebuilt locally from the endpoint catalog, so tampered resume state can't
+ # redirect the credential-bearing request to another host.
+ cursor: str
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "xi-api-key": api_key,
+ "Accept": "application/json",
+ }
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to a UNIX timestamp for ElevenLabs' time filters.
+
+ ElevenLabs stores and filters timestamps as epoch seconds, so the persisted watermark is
+ already an int in the common case; datetimes are accepted defensively.
+ """
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _build_params(config: ElevenLabsEndpointConfig, watermark: Optional[int], cursor: Optional[str]) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.page_size is not None:
+ params["page_size"] = config.page_size
+ params.update(config.extra_params)
+ if watermark is not None and config.incremental_param is not None:
+ params[config.incremental_param] = watermark
+ if cursor and config.cursor_param is not None:
+ params[config.cursor_param] = cursor
+ return params
+
+
+def _build_url(config: ElevenLabsEndpointConfig, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{ELEVENLABS_BASE_URL}{config.path}"
+ return f"{ELEVENLABS_BASE_URL}{config.path}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is genuine with one cheap probe against /v1/user.
+
+ ElevenLabs keys carry granular endpoint permissions and return 401 both for a fake key
+ (detail.status == "invalid_api_key") and for a real key missing the probed endpoint's
+ permission (detail.status == "missing_permissions"). A scoped-but-genuine key must pass
+ source-create — users may only grant the endpoints they intend to sync — so only an
+ invalid/unparseable 401 rejects.
+ """
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{ELEVENLABS_BASE_URL}/v1/user", headers=_get_headers(api_key), timeout=10
+ )
+ if response.status_code == 200:
+ return True
+ if response.status_code == 401:
+ try:
+ detail = response.json().get("detail", {})
+ except ValueError:
+ return False
+ status_text = detail.get("status") if isinstance(detail, dict) else None
+ return status_text == "missing_permissions"
+ return False
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((ElevenLabsRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # ElevenLabs rate limiting is concurrency-based per plan tier; a 429 clears as soon as
+ # in-flight requests drain, so exponential backoff is sufficient.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ElevenLabsRetryableError(f"ElevenLabs API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"ElevenLabs API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ElevenLabsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ELEVENLABS_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive instead of
+ # re-handshaking per request.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ watermark = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None
+ guard_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor: str | None = resume.cursor if resume is not None else None
+ if cursor:
+ logger.debug(f"ElevenLabs: resuming {endpoint} from cursor: {cursor}")
+
+ while True:
+ url = _build_url(config, _build_params(config, watermark, cursor))
+ data = _fetch(session, url, headers, logger)
+
+ items = data if config.data_key is None else (data.get(config.data_key) or [])
+ if not items:
+ break
+
+ yield items
+
+ if config.data_key is None or config.cursor_param is None:
+ # The whole collection arrives in one response (models) — nothing to paginate.
+ break
+
+ next_cursor = data.get(config.cursor_response_key)
+ if not data.get("has_more") or not next_cursor:
+ break
+
+ # Belt-and-braces stop for descending incremental endpoints: the server-side time
+ # filter is documented but couldn't be smoke-tested without credentials. If it were
+ # silently ignored, cursor pagination would otherwise walk the full history on every
+ # incremental sync — so stop once an entire page predates the watermark. (Never applied
+ # to ascending endpoints, where old rows arrive first by design.)
+ if watermark is not None and config.sort_mode == "desc" and guard_field is not None:
+ page_max = max(
+ (ts for ts in (_to_epoch(item.get(guard_field)) for item in items) if ts is not None),
+ default=None,
+ )
+ if page_max is not None and page_max < watermark:
+ break
+
+ # Save AFTER yielding the page so a crash re-yields the just-finished page rather than
+ # skipping it — merge dedupes on the primary key. Resume picks up at the next page.
+ cursor = next_cursor
+ resumable_source_manager.save_state(ElevenLabsResumeConfig(cursor=next_cursor))
+
+
+def elevenlabs_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ElevenLabsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = ELEVENLABS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=config.sort_mode,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py
new file mode 100644
index 000000000000..93d1bfe39c6e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py
@@ -0,0 +1,134 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ElevenLabsEndpointConfig:
+ name: str
+ # List endpoint path, relative to the API base URL.
+ path: str
+ # Key the list of objects is nested under in the response body (e.g. {"history": [...]}).
+ # None means the response body itself is the list (models).
+ data_key: Optional[str]
+ primary_key: str
+ # ElevenLabs mixes three cursor styles across endpoint families, so both sides of the
+ # cursor round-trip are declared per endpoint: the request query param we send the cursor
+ # in, and the response body key the next cursor comes back under. None = no pagination.
+ cursor_param: Optional[str] = None
+ cursor_response_key: Optional[str] = None
+ page_size: Optional[int] = None
+ # Server-side incremental filter query param, taking a unix-seconds timestamp. None means
+ # the endpoint has no server-side timestamp filter and syncs as full refresh only.
+ incremental_param: Optional[str] = None
+ # Static query params sent on every request (e.g. an explicit sort direction).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ sort_mode: SortMode = "desc"
+ # Field used to partition the warehouse table. Must be a stable creation timestamp,
+ # never an updated_at-style field that rewrites partitions on every sync.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ schema_description: Optional[str] = None
+
+
+# ElevenLabs timestamps are UNIX epoch seconds, so candidate incremental fields are stored as
+# integers even though the UI presents them as datetimes. Incremental sync is only enabled
+# where the API documents a server-side timestamp filter that lines up with a stable field on
+# the returned rows (history -> date_after_unix filters on date_unix, conversations ->
+# call_start_after_unix filters on start_time_unix_secs). Everything else is full refresh.
+#
+# The timestamp filters are taken from the published OpenAPI spec (date_after_unix is
+# documented inclusive); they could not be smoke-tested against the live API without
+# credentials, so the descending endpoints also carry a client-side watermark stop in the
+# transport as a belt-and-braces guard (see elevenlabs.py).
+ELEVENLABS_ENDPOINTS: dict[str, ElevenLabsEndpointConfig] = {
+ "history": ElevenLabsEndpointConfig(
+ name="history",
+ path="/v1/history",
+ data_key="history",
+ primary_key="history_item_id",
+ cursor_param="start_after_history_item_id",
+ cursor_response_key="last_history_item_id",
+ page_size=1000,
+ incremental_param="date_after_unix",
+ # Ascending creation order keeps already-fetched pages stable and lets the incremental
+ # watermark advance monotonically as pages are yielded.
+ extra_params={"sort_direction": "asc"},
+ sort_mode="asc",
+ partition_key="date_unix",
+ incremental_fields=[
+ {
+ "label": "date_unix",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date_unix",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ schema_description="Speech generation history items: the text, voice, model, and character cost of each generation.",
+ ),
+ "conversations": ElevenLabsEndpointConfig(
+ name="conversations",
+ path="/v1/convai/conversations",
+ data_key="conversations",
+ primary_key="conversation_id",
+ cursor_param="cursor",
+ cursor_response_key="next_cursor",
+ page_size=100,
+ incremental_param="call_start_after_unix",
+ # The conversations list has no sort parameter and returns newest-first.
+ sort_mode="desc",
+ partition_key="start_time_unix_secs",
+ incremental_fields=[
+ {
+ "label": "start_time_unix_secs",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time_unix_secs",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ schema_description="Conversational AI conversations: duration, status, call success, message counts, and summaries.",
+ ),
+ "agents": ElevenLabsEndpointConfig(
+ name="agents",
+ path="/v1/convai/agents",
+ data_key="agents",
+ primary_key="agent_id",
+ cursor_param="cursor",
+ cursor_response_key="next_cursor",
+ page_size=100,
+ # No server-side timestamp filter — full refresh only. Newest-first by default.
+ sort_mode="desc",
+ partition_key="created_at_unix_secs",
+ schema_description="Conversational AI agents configured in the workspace.",
+ ),
+ "voices": ElevenLabsEndpointConfig(
+ name="voices",
+ path="/v2/voices",
+ data_key="voices",
+ primary_key="voice_id",
+ cursor_param="next_page_token",
+ cursor_response_key="next_page_token",
+ page_size=100,
+ # No server-side timestamp filter — full refresh only. created_at_unix is nullable on
+ # older/premade voices, so the table is not partitioned on it.
+ sort_mode="desc",
+ schema_description="Voices available to the workspace, including cloned and professional voices.",
+ ),
+ "models": ElevenLabsEndpointConfig(
+ name="models",
+ path="/v1/models",
+ data_key=None,
+ primary_key="model_id",
+ # Small static catalog returned as a bare list in a single response — no pagination.
+ sort_mode="desc",
+ schema_description="Speech models available on the account, with capabilities and cost factors.",
+ ),
+}
+
+ENDPOINTS = tuple(ELEVENLABS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ELEVENLABS_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py
index 66ca248351ba..9e109daaf7ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/source.py
@@ -1,19 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (
+ ELEVENLABS_BASE_URL,
+ ElevenLabsResumeConfig,
+ elevenlabs_source,
+ validate_credentials as validate_elevenlabs_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import (
+ ELEVENLABS_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ElevenLabsSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ElevenLabsSource(SimpleSource[ElevenLabsSourceConfig]):
+class ElevenLabsSource(ResumableSource[ElevenLabsSourceConfig, ElevenLabsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ELEVENLABS
@@ -24,8 +49,102 @@ class ElevenLabsSource(SimpleSource[ElevenLabsSourceConfig]):
name=SchemaExternalDataSourceType.ELEVEN_LABS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="ElevenLabs",
- iconPath="/static/services/elevenlabs.png",
- keywords=["ai", "voice", "audio", "text-to-speech"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption=(
+ "Enter your ElevenLabs API key to sync your speech generation history, conversational AI "
+ "conversations and agents, voices, and models into the PostHog Data warehouse. Create a key under "
+ "[Profile → API keys](https://elevenlabs.io/app/settings/api-keys).\n\n"
+ "If the key uses restricted permissions, grant read access to the endpoints you want to sync: "
+ "**History**, **Conversational AI**, **Voices**, **Models**, and **User** (used to verify the key)."
+ ),
+ iconPath="/static/services/elevenlabs.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/elevenlabs",
+ keywords=["ai", "voice", "audio", "text-to-speech", "conversational ai"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ f"401 Client Error: Unauthorized for url: {ELEVENLABS_BASE_URL}": (
+ "Your ElevenLabs API key is invalid, has been revoked, or lacks the permission for this endpoint. "
+ "Check the key's permissions under Profile → API keys in ElevenLabs, then reconnect."
+ ),
+ f"403 Client Error: Forbidden for url: {ELEVENLABS_BASE_URL}": (
+ "Your ElevenLabs API key does not have access to this endpoint. "
+ "Check the key's permissions under Profile → API keys in ElevenLabs, then reconnect."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: ElevenLabsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=ELEVENLABS_ENDPOINTS[endpoint].incremental_param is not None,
+ supports_append=ELEVENLABS_ENDPOINTS[endpoint].incremental_param is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=ELEVENLABS_ENDPOINTS[endpoint].schema_description,
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: ElevenLabsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_elevenlabs_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid ElevenLabs API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ElevenLabsResumeConfig]:
+ return ResumableSourceManager[ElevenLabsResumeConfig](inputs, ElevenLabsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ElevenLabsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ElevenLabsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return elevenlabs_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py
new file mode 100644
index 000000000000..60f46d0eabb3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs.py
@@ -0,0 +1,358 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (
+ ElevenLabsResumeConfig,
+ _to_epoch,
+ elevenlabs_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import ENDPOINTS
+
+TRACKED_SESSION_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs.make_tracked_session"
+)
+
+
+def _make_manager(resume_state: ElevenLabsResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _resp(json_body: Any, status: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = json_body
+ resp.status_code = status
+ resp.ok = status < 400
+ return resp
+
+
+def _requests(mock_session: mock.MagicMock) -> list[tuple[str, dict[str, list[str]]]]:
+ """Return (path, parsed query params) for every GET the transport issued."""
+ calls = []
+ for call in mock_session.return_value.get.call_args_list:
+ url = call.args[0]
+ parts = urlsplit(url)
+ calls.append((parts.path, parse_qs(parts.query)))
+ return calls
+
+
+class TestToEpoch:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("bool_true", True, None),
+ ("int", 1700000000, 1700000000),
+ ("float", 1700000000.9, 1700000000),
+ ("numeric_string", "1700000000", 1700000000),
+ ("non_numeric_string", "not-a-number", None),
+ ("aware_datetime", datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ ("date", date(2023, 11, 14), 1699920000),
+ ]
+ )
+ def test_to_epoch(self, _name: str, value: Any, expected: int | None) -> None:
+ assert _to_epoch(value) == expected
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok_200", 200, {}, True),
+ # A genuine key that merely lacks the user_read permission must pass source-create.
+ ("missing_permissions", 401, {"detail": {"status": "missing_permissions", "message": "..."}}, True),
+ ("invalid_api_key", 401, {"detail": {"status": "invalid_api_key", "message": "..."}}, False),
+ ("unexpected_detail_shape", 401, {"detail": "unexpected shape"}, False),
+ ("forbidden", 403, {}, False),
+ ("server_error", 500, {}, False),
+ ]
+ )
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_status_mapping(
+ self, _name: str, status_code: int, body: dict[str, Any], expected: bool, mock_session: mock.MagicMock
+ ) -> None:
+ mock_session.return_value.get.return_value = _resp(body, status=status_code)
+ assert validate_credentials("key") is expected
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_non_json_401_is_invalid(self, mock_session: mock.MagicMock) -> None:
+ resp = _resp({}, status=401)
+ resp.json.side_effect = ValueError("not json")
+ mock_session.return_value.get.return_value = resp
+ assert validate_credentials("key") is False
+
+
+class TestGetRowsPagination:
+ @parameterized.expand(
+ [
+ (
+ "history",
+ "history",
+ "start_after_history_item_id",
+ {"history": [{"history_item_id": "h2"}], "last_history_item_id": "h2", "has_more": False},
+ ),
+ (
+ "conversations",
+ "conversations",
+ "cursor",
+ {"conversations": [{"conversation_id": "c2"}], "next_cursor": None, "has_more": False},
+ ),
+ (
+ "agents",
+ "agents",
+ "cursor",
+ {"agents": [{"agent_id": "a2"}], "next_cursor": None, "has_more": False},
+ ),
+ (
+ "voices",
+ "voices",
+ "next_page_token",
+ {"voices": [{"voice_id": "v2"}], "next_page_token": None, "has_more": False},
+ ),
+ ]
+ )
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_each_cursor_style_paginates_with_its_own_params(
+ self,
+ endpoint: str,
+ data_key: str,
+ cursor_param: str,
+ page_two_body: dict[str, Any],
+ mock_session: mock.MagicMock,
+ ) -> None:
+ cursor_response_key = {
+ "history": "last_history_item_id",
+ "conversations": "next_cursor",
+ "agents": "next_cursor",
+ "voices": "next_page_token",
+ }[endpoint]
+ page_one = {data_key: [{"id": "first"}], cursor_response_key: "cursor-1", "has_more": True}
+ mock_session.return_value.get.side_effect = [_resp(page_one), _resp(page_two_body)]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", endpoint, mock.MagicMock(), manager))
+
+ assert len(batches) == 2
+ requests = _requests(mock_session)
+ # First request carries no cursor; the second passes the returned cursor back in the
+ # endpoint family's own query param.
+ assert cursor_param not in requests[0][1]
+ assert requests[1][1][cursor_param] == ["cursor-1"]
+ # State is saved once, after the first page was yielded, pointing at page two.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].cursor == "cursor-1"
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_models_bare_list_single_fetch(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _resp([{"model_id": "eleven_v3"}])
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "models", mock.MagicMock(), manager))
+
+ assert batches == [[{"model_id": "eleven_v3"}]]
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_stops_when_has_more_false_even_with_cursor_present(self, mock_session: mock.MagicMock) -> None:
+ # /v1/history always echoes last_history_item_id; without the has_more check the
+ # transport would refetch the last page forever.
+ body = {"history": [{"history_item_id": "h1"}], "last_history_item_id": "h1", "has_more": False}
+ mock_session.return_value.get.return_value = _resp(body)
+
+ batches = list(get_rows("key", "history", mock.MagicMock(), _make_manager()))
+
+ assert len(batches) == 1
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_empty_page_yields_nothing(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _resp({"history": [], "has_more": False})
+
+ batches = list(get_rows("key", "history", mock.MagicMock(), _make_manager()))
+
+ assert batches == []
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_resumes_from_saved_cursor(self, mock_session: mock.MagicMock) -> None:
+ body = {"conversations": [{"conversation_id": "c9"}], "next_cursor": None, "has_more": False}
+ mock_session.return_value.get.return_value = _resp(body)
+
+ manager = _make_manager(ElevenLabsResumeConfig(cursor="saved-cursor"))
+ batches = list(get_rows("key", "conversations", mock.MagicMock(), manager))
+
+ assert [row["conversation_id"] for batch in batches for row in batch] == ["c9"]
+ requests = _requests(mock_session)
+ assert requests[0][1]["cursor"] == ["saved-cursor"]
+
+
+class TestGetRowsIncremental:
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_history_passes_server_side_filter_and_ascending_sort(self, mock_session: mock.MagicMock) -> None:
+ body = {"history": [{"history_item_id": "h1", "date_unix": 1700000100}], "has_more": False}
+ mock_session.return_value.get.return_value = _resp(body)
+
+ list(
+ get_rows(
+ "key",
+ "history",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="date_unix",
+ )
+ )
+
+ _, params = _requests(mock_session)[0]
+ assert params["date_after_unix"] == ["1700000000"]
+ assert params["sort_direction"] == ["asc"]
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_conversations_passes_call_start_after_unix(self, mock_session: mock.MagicMock) -> None:
+ body = {"conversations": [], "has_more": False}
+ mock_session.return_value.get.return_value = _resp(body)
+
+ list(
+ get_rows(
+ "key",
+ "conversations",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="start_time_unix_secs",
+ )
+ )
+
+ _, params = _requests(mock_session)[0]
+ assert params["call_start_after_unix"] == ["1700000000"]
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_descending_pagination_stops_once_page_predates_watermark(self, mock_session: mock.MagicMock) -> None:
+ # If ElevenLabs silently ignored call_start_after_unix, cursor pagination would walk the
+ # full conversation history on every incremental sync. The client-side guard must stop
+ # after the first page that is entirely older than the watermark.
+ stale_page = {
+ "conversations": [{"conversation_id": "old", "start_time_unix_secs": 1600000000}],
+ "next_cursor": "more",
+ "has_more": True,
+ }
+ mock_session.return_value.get.return_value = _resp(stale_page)
+
+ batches = list(
+ get_rows(
+ "key",
+ "conversations",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="start_time_unix_secs",
+ )
+ )
+
+ # The stale page is still yielded (merge dedupes it) but pagination stops there.
+ assert len(batches) == 1
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_descending_pagination_keeps_walking_without_watermark(self, mock_session: mock.MagicMock) -> None:
+ pages = [
+ _resp(
+ {
+ "conversations": [{"conversation_id": "new", "start_time_unix_secs": 1700000000}],
+ "next_cursor": "c1",
+ "has_more": True,
+ }
+ ),
+ _resp(
+ {
+ "conversations": [{"conversation_id": "old", "start_time_unix_secs": 1600000000}],
+ "next_cursor": None,
+ "has_more": False,
+ }
+ ),
+ ]
+ mock_session.return_value.get.side_effect = pages
+
+ batches = list(get_rows("key", "conversations", mock.MagicMock(), _make_manager()))
+
+ assert len(batches) == 2
+
+ @mock.patch(TRACKED_SESSION_PATH)
+ def test_ascending_history_never_triggers_watermark_stop(self, mock_session: mock.MagicMock) -> None:
+ # date_after_unix is inclusive, so page one re-includes the boundary row whose value
+ # equals the watermark. An asc endpoint must never be cut short by the desc guard.
+ pages = [
+ _resp(
+ {
+ "history": [{"history_item_id": "boundary", "date_unix": 1700000000}],
+ "last_history_item_id": "boundary",
+ "has_more": True,
+ }
+ ),
+ _resp(
+ {
+ "history": [{"history_item_id": "newer", "date_unix": 1700000500}],
+ "last_history_item_id": "newer",
+ "has_more": False,
+ }
+ ),
+ ]
+ mock_session.return_value.get.side_effect = pages
+
+ batches = list(
+ get_rows(
+ "key",
+ "history",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="date_unix",
+ )
+ )
+
+ assert len(batches) == 2
+
+
+class TestElevenLabsSource:
+ def test_endpoints_inventory(self) -> None:
+ assert ENDPOINTS == ("history", "conversations", "agents", "voices", "models")
+
+ @parameterized.expand(
+ [
+ ("history", "history_item_id", "date_unix", "asc"),
+ ("conversations", "conversation_id", "start_time_unix_secs", "desc"),
+ ("agents", "agent_id", "created_at_unix_secs", "desc"),
+ ("voices", "voice_id", None, "desc"),
+ ("models", "model_id", None, "desc"),
+ ]
+ )
+ def test_source_response_shape(
+ self, endpoint: str, primary_key: str, partition_key: str | None, sort_mode: str
+ ) -> None:
+ response = elevenlabs_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [primary_key]
+ assert response.sort_mode == sort_mode
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py
new file mode 100644
index 000000000000..6a80df1b8d68
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/tests/test_elevenlabs_source.py
@@ -0,0 +1,153 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.elevenlabs import (
+ ElevenLabsResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source import ElevenLabsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ElevenLabsSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestElevenLabsSource:
+ def setup_method(self):
+ self.source = ElevenLabsSource()
+ self.team_id = 123
+ self.config = ElevenLabsSourceConfig(api_key="key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ELEVENLABS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "ElevenLabs"
+ assert config.label == "ElevenLabs"
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/elevenlabs.svg"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/elevenlabs"
+
+ def test_source_config_fields(self):
+ config = self.source.get_source_config
+ assert [f.name for f in config.fields] == ["api_key"]
+
+ api_key = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.secret is True
+ assert api_key.required is True
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas iterates a static endpoint catalog with no I/O, so the public docs catalog renders.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert [t["name"] for t in documented] == list(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, supports_incremental",
+ [
+ ("history", True),
+ ("conversations", True),
+ ("agents", False),
+ ("voices", False),
+ ("models", False),
+ ],
+ )
+ def test_get_schemas_incremental_support(self, endpoint, supports_incremental):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_incremental
+ assert schema.incremental_fields == INCREMENTAL_FIELDS.get(endpoint, [])
+
+ def test_get_schemas_filtered_by_names(self):
+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["history"])] == ["history"]
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.elevenlabs.io/v1/history?page_size=1000",
+ "403 Client Error: Forbidden for url: https://api.elevenlabs.io/v1/convai/conversations?page_size=100",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://api.elevenlabs.io/v1/history",
+ "429 Client Error: Too Many Requests for url: https://api.elevenlabs.io/v1/history",
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient_or_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid ElevenLabs API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source.validate_elevenlabs_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ElevenLabsResumeConfig
+
+ @pytest.mark.parametrize("should_use_incremental_field", [True, False])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.elevenlabs.source.elevenlabs_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_elevenlabs_source, should_use_incremental_field):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "history"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = "date_unix"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_elevenlabs_source.assert_called_once()
+ kwargs = mock_elevenlabs_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "history"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ # The stored watermark must never leak into a full-refresh run.
+ assert kwargs["db_incremental_field_last_value"] == (1700000000 if should_use_incremental_field else None)
+
+ def test_canonical_descriptions_keyed_by_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions).issubset(set(ENDPOINTS))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index ac6f2aef6c62..dbcf2f966574 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1187,7 +1187,7 @@ class ElasticsearchSourceConfig(config.Config):
@config.config
class ElevenLabsSourceConfig(config.Config):
- pass
+ api_key: str
@config.config