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 bland_ai import source (#69625)

Tom Owersdc52496746f6
diff --git a/frontend/public/services/bland_ai.svg b/frontend/public/services/bland_ai.svg
new file mode 100644
index 000000000000..06ad460dedcc
--- /dev/null
+++ b/frontend/public/services/bland_ai.svg
@@ -0,0 +1,5 @@
+<svg width="576" height="147" viewBox="0 0 576 147" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M574.255 0H532.534C531.826 0 531.259 0.566676 531.259 1.27502V12.0064C531.259 12.7148 530.692 13.2815 529.984 13.2815H478.133C461.788 13.2815 448.046 24.3494 443.955 39.4017H443.938C443.787 39.9418 443.3 40.3491 442.707 40.3491C442.114 40.3491 441.627 39.9507 441.485 39.4017H441.467C437.385 24.3494 423.635 13.2815 407.29 13.2815H345.309C330.372 13.2815 317.604 22.5254 312.398 35.6032C311.884 36.8959 309.954 36.5152 309.945 35.1251L309.892 14.5565C309.892 13.857 309.317 13.2815 308.617 13.2815H212.495C197.566 13.2815 184.807 22.5165 179.592 35.5855C179.078 36.8782 177.148 36.4975 177.139 35.1074L177.077 1.27502C177.077 0.57553 176.502 0 175.802 0H134.072C133.373 0 132.797 0.566676 132.797 1.27502L132.735 35.1074C132.735 36.5063 130.805 36.8871 130.282 35.5855C125.076 22.5165 112.308 13.2815 97.3797 13.2815H45.5289C44.8205 13.2815 44.2539 12.7148 44.2539 12.0064V1.27502C44.2539 0.566676 43.6872 0 42.9788 0H1.27502C0.566676 0 0 0.566676 0 1.27502V56.278C0 56.9864 0.566676 57.553 1.27502 57.553H574.255C574.964 57.553 575.53 56.9864 575.53 56.278V1.27502C575.53 0.566676 574.964 0 574.255 0Z" fill="#151515"/>
+<path d="M574.26 101.825H1.44787C0.739528 101.825 0.172852 102.392 0.172852 103.1V144.821C0.172852 145.53 0.739528 146.096 1.44787 146.096H97.4021C112.339 146.096 125.107 136.852 130.314 123.775C130.827 122.482 132.757 122.863 132.766 124.253L132.819 144.83C132.819 145.53 133.395 146.105 134.094 146.105H175.825C176.524 146.105 177.1 145.539 177.1 144.83L177.153 124.253C177.153 122.863 179.092 122.473 179.605 123.775C184.812 136.852 197.58 146.096 212.517 146.096H441.454C442.154 146.096 442.729 145.53 442.729 144.821L442.782 124.253C442.782 122.863 444.721 122.473 445.235 123.775C450.441 136.852 463.209 146.096 478.146 146.096H574.269C574.977 146.096 575.544 145.53 575.544 144.821V103.1C575.544 102.392 574.977 101.825 574.269 101.825H574.26Z" fill="#151515"/>
+<path d="M575.532 79.7897C575.532 84.2492 572.083 87.4893 567.832 87.4893C563.582 87.4893 560.133 84.2492 560.133 79.7897C560.133 75.3303 563.582 72.0902 567.832 72.0902C572.083 72.0902 575.532 75.3303 575.532 79.7897ZM573.929 79.7897C573.929 76.2361 571.316 73.5186 567.832 73.5186C564.348 73.5186 561.735 76.2361 561.735 79.7897C561.735 83.3434 564.348 86.0608 567.832 86.0608C571.316 86.0608 573.929 83.3434 573.929 79.7897ZM566.578 80.3123V83.7963H564.662V75.6787H568.564C570.306 75.6787 571.351 76.6193 571.351 77.9781C571.351 78.9884 570.724 79.9639 569.435 80.2426L571.7 83.7963H569.574L567.379 80.3123H566.578ZM568.216 77.0374H566.578V78.9884H568.216C568.982 78.9884 569.33 78.5355 569.33 78.0129C569.33 77.4555 568.982 77.0374 568.216 77.0374Z" fill="#151515"/>
+</svg>
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 75388f717068..693294af1e01 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -72,6 +72,7 @@ the row lists both.
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
+| bland_ai | HTTP | requests | ✅ |
| blogger | HTTP | requests | ✅ |
| bluetally | HTTP | requests | ✅ |
| boldsign | HTTP | requests | ✅ |
@@ -473,7 +474,6 @@ doesn't conflict with concurrent PRs.
- baseten
- bigcommerce
- bitly
-- bland_ai
- box
- braintrust
- branch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/bland_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/bland_ai.py
new file mode 100644
index 000000000000..c860b5ed86be
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/bland_ai.py
@@ -0,0 +1,232 @@
+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.bland_ai.settings import BLAND_AI_ENDPOINTS
+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
+
+# The authorization header is the raw API key (no "Bearer" prefix).
+BASE_URL = "https://api.bland.ai"
+
+# GET /v1/calls default (and documented maximum) page size.
+PAGE_SIZE = 1000
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class BlandAIRetryableError(Exception):
+ pass
+
+
+class BlandAIResumeConfig:
+ # Index offset into the call list (`from` query param) of the next unfetched page.
+ offset: int = 0
+ # The exact `start_date` filter the interrupted run used. The pipeline checkpoints the
+ # incremental watermark per batch, so on resume `db_incremental_field_last_value` may already
+ # have advanced past the value we filtered by — reusing the original filter keeps the saved
+ # offset pointing into the same result set.
+ start_date: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "authorization": api_key,
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (BlandAIRetryableError, requests.ReadTimeout, requests.ConnectionError),
+ ),
+ stop=stop_after_attempt(5),
+ 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)
+
+ # Bland's read-endpoint rate limits aren't documented, so back off politely on 429 and 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BlandAIRetryableError(f"Bland AI API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Bland AI API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # Cheapest probe that exercises the token: list a single call. A bad key returns
+ # 401 {"errors": [{"error": "AUTH_FAILURE", ...}]}.
+ url = f"{BASE_URL}/v1/calls?{urlencode({'limit': 1})}"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _format_start_date(value: Any) -> str | None:
+ """Format the incremental watermark as the ISO 8601 value `start_date` accepts.
+
+ A naive datetime is stamped UTC — Bland interprets offset-less values as UTC anyway, and an
+ explicit offset guards against that default changing.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=UTC)
+ return value.isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _get_pathway_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ data = _fetch(session, f"{BASE_URL}/v1/pathway", headers, logger)
+
+ # The docs' response example shows a single pathway object without an explicit list wrapper,
+ # and we couldn't verify the live shape without account credentials — accept a bare list,
+ # common list wrappers, or a single object.
+ if isinstance(data, list):
+ rows = data
+ elif isinstance(data, dict):
+ wrapped = next((data[key] for key in ("pathways", "data") if isinstance(data.get(key), list)), None)
+ rows = wrapped if wrapped is not None else [data]
+ else:
+ rows = []
+
+ if rows:
+ yield rows
+
+
+def _transcript_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ calls: list[dict[str, Any]],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for call in calls:
+ detail = _fetch(session, f"{BASE_URL}/v1/calls/{call['call_id']}", headers, logger)
+ for utterance in detail.get("transcripts") or []:
+ rows.append(
+ {
+ **utterance,
+ "call_id": call["call_id"],
+ # The parent call's creation time. Utterance `created_at`s aren't monotonic
+ # across calls (a long call's utterances postdate the next call's creation),
+ # so this is the field the incremental cursor and partitioning key off.
+ # Direct access on purpose: a silent None here would corrupt partitions and
+ # stall the incremental watermark.
+ "call_created_at": call["created_at"],
+ }
+ )
+ return rows
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BLAND_AI_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every list page and hydration request so urllib3 keeps the
+ # connection alive instead of re-handshaking per request.
+ session = make_tracked_session()
+
+ if endpoint == "pathways":
+ yield from _get_pathway_rows(session, headers, logger)
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ offset = resume.offset
+ start_date = resume.start_date
+ logger.debug(f"Bland AI: resuming {endpoint} from offset {offset} (start_date={start_date})")
+ else:
+ offset = 0
+ start_date = _format_start_date(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ while True:
+ params: dict[str, Any] = {
+ "from": offset,
+ "limit": PAGE_SIZE,
+ # Ascending creation order so the pipeline's incremental watermark can checkpoint
+ # after every batch, and so index offsets stay stable while new calls append.
+ "ascending": "true",
+ "sort_by": "created_at",
+ }
+ if start_date:
+ # `start_date` is inclusive; the boundary row is re-fetched and deduped by merge.
+ params["start_date"] = start_date
+ data = _fetch(session, f"{BASE_URL}/v1/calls?{urlencode(params)}", headers, logger)
+
+ calls = data.get("calls") or []
+ if not calls:
+ break
+
+ rows = _transcript_rows(session, headers, calls, logger) if config.hydrate_transcripts else calls
+ if rows:
+ yield rows
+
+ offset += len(calls)
+ total_count = data.get("total_count")
+ if isinstance(total_count, int) and offset >= total_count:
+ 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 offset.
+ resumable_source_manager.save_state(BlandAIResumeConfig(offset=offset, start_date=start_date))
+
+
+def bland_ai_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = BLAND_AI_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,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ # Call endpoints request `ascending=true&sort_by=created_at`; pathways is a single
+ # unordered page on a full-refresh-only endpoint, so the value never drives a watermark.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/canonical_descriptions.py
new file mode 100644
index 000000000000..8301cbc6e201
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/canonical_descriptions.py
@@ -0,0 +1,82 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "calls": {
+ "description": (
+ "A phone call dispatched or received by your Bland AI account, with status, timing, cost, "
+ "and post-call analysis metadata. Transcripts are excluded from this table for size reasons — "
+ "sync the call_transcripts table for those."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/calls-id",
+ "columns": {
+ "call_id": "The unique identifier for the call.",
+ "created_at": "The timestamp for when the call request was created.",
+ "started_at": "The time the call was connected.",
+ "end_at": "The time the call will automatically be ended at if still connected (because of max_duration).",
+ "call_length": "The length of the call in minutes.",
+ "to": "The phone number that received the call.",
+ "from": "The phone number that made the call.",
+ "completed": "Whether the call has been completed.",
+ "inbound": "Whether the call was inbound or outbound. False for outbound calls.",
+ "queue_status": "The status of the call (new, queued, allocated, started, complete, or an error stage).",
+ "error_message": "The error recorded if the call failed at any stage.",
+ "answered_by": "Who answered the call (e.g. human, voicemail).",
+ "batch_id": "If the call is part of a batch, its batch_id.",
+ "campaign_id": "If the call is part of a campaign, its campaign id.",
+ "max_duration": "The maximum length of time the call was allowed to last, in minutes.",
+ "endpoint_url": "The URL of the deployment that handled the call.",
+ "transferred_to": "Number that the person was transferred to.",
+ "transferred_at": "The timestamp when the call was transferred to another number.",
+ "request_data": "Details about parameters in the original API request.",
+ "variables": "Variables extracted or injected during the call.",
+ "record": "Whether the call was recorded.",
+ "recording_url": "URL of the call recording, if recording was enabled.",
+ "metadata": "Arbitrary metadata attached to the call at dispatch time.",
+ "summary": "AI-generated summary of the call.",
+ "price": "The cost of the call.",
+ "local_dialing": "Whether local dialing was used for the call.",
+ "call_ended_by": "Which party ended the call.",
+ "pathway_id": "The conversational pathway that drove the call, if any.",
+ "pathway_logs": "Logs from the pathway execution.",
+ "pathway_version": "The version of the pathway used for the call.",
+ "analysis_schema": "The schema requested for post-call analysis.",
+ "analysis": "Post-call analysis results.",
+ "status": "The current status of the call.",
+ "corrected_duration": "The corrected duration of the call.",
+ "citations": "Citations extracted from the call.",
+ "voice_id": "The voice used by the agent on the call.",
+ },
+ },
+ "call_transcripts": {
+ "description": (
+ "A single utterance spoken during a Bland AI call. One row per phrase, joined to the calls "
+ "table via call_id. Fetched from the per-call detail endpoint since the call list excludes "
+ "transcripts for size reasons."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/calls-id",
+ "columns": {
+ "id": "The identifier of the transcript utterance within the call.",
+ "created_at": "The timestamp when the utterance was spoken.",
+ "text": "The text of the utterance.",
+ "user": "Who spoke the utterance: user, assistant, robot, or agent-action.",
+ "call_id": "The unique identifier of the call this utterance belongs to.",
+ "call_created_at": "The timestamp when the parent call request was created.",
+ },
+ },
+ "pathways": {
+ "description": (
+ "A conversational pathway in your Bland AI account — the node/edge graph that gives the "
+ "agent structured control over dialogue, branching, and actions."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/all_pathway",
+ "columns": {
+ "id": "The unique identifier of the pathway.",
+ "name": "The name of the conversational pathway.",
+ "description": "A description of the conversational pathway.",
+ "nodes": "Data about all the nodes in the pathway.",
+ "edges": "Data about the connections between nodes, including the labels and conditions for taking each edge.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/settings.py
new file mode 100644
index 000000000000..0fa4f50f3adc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/settings.py
@@ -0,0 +1,99 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class BlandAIEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ # 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
+ # Each page of listed calls is fanned out via GET /v1/calls/{call_id} and the detail's
+ # `transcripts` array is emitted as one row per utterance (the list endpoint excludes
+ # transcripts for size reasons).
+ hydrate_transcripts: bool = False
+ # True only when the API exposes a genuine server-side timestamp filter for this endpoint
+ # (`start_date` on GET /v1/calls). Pathways have no timestamp filters at all.
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+ description: str = ""
+
+
+# Bland AI's warehouse-relevant resources:
+#
+# - `calls` — GET /v1/calls. Index-offset pagination (`from` + `limit`, default page size 1000)
+# with `total_count`/`count` in the response. Server-side `start_date` filter (date or full
+# ISO 8601 datetime, interpreted against call creation time) plus `ascending=true&sort_by=created_at`
+# give a genuine incremental cursor on `created_at`. The API also exposes `update_start_date` /
+# `sort_by=updated_at`, but that filter is date-only and the documented call object doesn't
+# list an `updated_at` field we could track a watermark on, so we conservatively key on
+# `created_at` only (post-call analysis edits to old calls require a full refresh to re-sync).
+#
+# - `call_transcripts` — transcripts are excluded from the list endpoint for size reasons, so this
+# endpoint lists calls (same pagination/filtering as `calls`) and hydrates each via
+# GET /v1/calls/{call_id}, emitting one row per transcript utterance. One extra request per call,
+# so it's off by default. Rows carry the parent `call_id` (utterance ids aren't documented as
+# globally unique, hence the composite key) and `call_created_at`, the parent call's creation
+# time — the incremental/partition field, since utterance timestamps aren't monotonic across
+# calls (a long call's utterances can postdate the next call's creation).
+#
+# - `pathways` — GET /v1/pathway. Small (name/description/nodes/edges per pathway), no timestamp
+# filters, so full refresh only.
+BLAND_AI_ENDPOINTS: dict[str, BlandAIEndpointConfig] = {
+ "calls": BlandAIEndpointConfig(
+ name="calls",
+ primary_keys=["call_id"],
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description=(
+ "Metadata for every call dispatched or received by your account: status, timing, cost, "
+ "post-call analysis, and pathway info. Transcripts are excluded — sync call_transcripts for those."
+ ),
+ ),
+ "call_transcripts": BlandAIEndpointConfig(
+ name="call_transcripts",
+ primary_keys=["call_id", "id"],
+ partition_key="call_created_at",
+ hydrate_transcripts=True,
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "call_created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "call_created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ should_sync_default=False,
+ description=(
+ "One row per utterance spoken during a call. Requires one extra API request per call "
+ "(transcripts are excluded from the call list endpoint), so syncs are slower than the calls table."
+ ),
+ ),
+ "pathways": BlandAIEndpointConfig(
+ name="pathways",
+ primary_keys=["id"],
+ description=(
+ "Your conversational pathways — the node/edge graphs that drive agent conversations. "
+ "Full refresh only (the API has no timestamp filters for pathways)."
+ ),
+ ),
+}
+
+ENDPOINTS = tuple(BLAND_AI_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BLAND_AI_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/source.py
index 34b156559400..40e6d43347a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/source.py
@@ -1,19 +1,40 @@
-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.bland_ai.bland_ai import (
+ BASE_URL,
+ BlandAIResumeConfig,
+ bland_ai_source,
+ validate_credentials as validate_bland_ai_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.settings import BLAND_AI_ENDPOINTS
+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.generated_configs import BlandAISourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BlandAISource(SimpleSource[BlandAISourceConfig]):
+class BlandAISource(ResumableSource[BlandAISourceConfig, BlandAIResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BLANDAI
@@ -24,8 +45,96 @@ class BlandAISource(SimpleSource[BlandAISourceConfig]):
name=SchemaExternalDataSourceType.BLAND_AI,
category=DataWarehouseSourceCategory.COMMUNICATION,
label="Bland AI",
- iconPath="/static/services/bland_ai.png",
- keywords=["ai", "phone calls", "voice agent", "transcripts"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption=(
+ "Enter your Bland AI API key to sync your AI phone calls, transcripts, and "
+ "conversational pathways into the PostHog Data warehouse. Find your key in the "
+ "[Bland dashboard](https://app.bland.ai/) under **Settings → API keys**."
+ ),
+ iconPath="/static/services/bland_ai.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/bland-ai",
+ keywords=["ai", "phone calls", "voice agent", "transcripts"],
+ 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.bland_ai.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Bland returns 401 AUTH_FAILURE for a missing/invalid key on every endpoint. There's no
+ # scope/permission model, so a 401 is always a credential problem retrying can't fix.
+ return {
+ f"401 Client Error: Unauthorized for url: {BASE_URL}": (
+ "Your Bland AI API key is invalid or has been revoked. Create a new key in the "
+ "Bland dashboard, then reconnect."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: BlandAISourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint_config.name,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+ for endpoint_config in BLAND_AI_ENDPOINTS.values()
+ ]
+ 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: BlandAISourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_bland_ai_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Bland AI API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BlandAIResumeConfig]:
+ return ResumableSourceManager[BlandAIResumeConfig](inputs, BlandAIResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BlandAISourceConfig,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bland_ai_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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai.py
new file mode 100644
index 000000000000..0d7ed90e4868
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai.py
@@ -0,0 +1,293 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import urlencode
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.bland_ai import (
+ BASE_URL,
+ PAGE_SIZE,
+ BlandAIResumeConfig,
+ _format_start_date,
+ bland_ai_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.settings import ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.bland_ai"
+
+
+def _calls_url(offset: int, start_date: str | None = None) -> str:
+ params: dict[str, Any] = {"from": offset, "limit": PAGE_SIZE, "ascending": "true", "sort_by": "created_at"}
+ if start_date:
+ params["start_date"] = start_date
+ return f"{BASE_URL}/v1/calls?{urlencode(params)}"
+
+
+def _make_manager(resume_state: BlandAIResumeConfig | 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 _url_router(responses: dict[str, Any]) -> Any:
+ """Return a session.get side_effect that maps each requested URL to a mocked response."""
+
+ def fake_get(url: str, headers: Any = None, timeout: Any = None) -> mock.MagicMock:
+ return _resp(responses[url])
+
+ return fake_get
+
+
+class TestFormatStartDate:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ # A naive watermark is stamped UTC so the server-side filter is unambiguous.
+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05+00:00"),
+ ("aware_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05+00:00"),
+ ("date", date(2026, 1, 2), "2026-01-02"),
+ ("iso_string", "2026-01-02T03:04:05+00:00", "2026-01-02T03:04:05+00:00"),
+ ]
+ )
+ def test_format_start_date(self, _name: str, value: Any, expected: str | None) -> None:
+ assert _format_start_date(value) == expected
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False), ("error", 500, False)]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _resp({}, status=status_code)
+ assert validate_credentials("key") is expected
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ 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(f"{MODULE}.make_tracked_session")
+ def test_sends_raw_api_key_in_authorization_header(self, mock_session: mock.MagicMock) -> None:
+ # Bland expects the raw key, not a "Bearer "-prefixed value.
+ mock_session.return_value.get.return_value = _resp({}, status=200)
+ validate_credentials("sk-raw-key")
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["authorization"] == "sk-raw-key"
+
+
+class TestGetCallRows:
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_paginates_by_offset_until_total_count(self, mock_session: mock.MagicMock) -> None:
+ page_one = [{"call_id": f"c{i}", "created_at": "2026-01-01T00:00:00+00:00"} for i in range(PAGE_SIZE)]
+ page_two = [{"call_id": "clast", "created_at": "2026-01-02T00:00:00+00:00"}]
+ responses = {
+ _calls_url(0): {"total_count": PAGE_SIZE + 1, "count": PAGE_SIZE, "calls": page_one},
+ _calls_url(PAGE_SIZE): {"total_count": PAGE_SIZE + 1, "count": 1, "calls": page_two},
+ }
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "calls", mock.MagicMock(), manager))
+
+ assert [len(b) for b in batches] == [PAGE_SIZE, 1]
+ assert batches[1][0]["call_id"] == "clast"
+ # Reaching total_count terminates without requesting a third page.
+ assert mock_session.return_value.get.call_count == 2
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_stops_on_empty_page_when_total_count_overcounts(self, mock_session: mock.MagicMock) -> None:
+ # total_count can drift from what's actually returned; an empty page must still terminate.
+ responses = {
+ _calls_url(0): {"total_count": 50, "count": 2, "calls": [{"call_id": "c1"}, {"call_id": "c2"}]},
+ _calls_url(2): {"total_count": 50, "count": 0, "calls": []},
+ }
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ batches = list(get_rows("key", "calls", mock.MagicMock(), _make_manager()))
+
+ assert [len(b) for b in batches] == [2]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_incremental_watermark_becomes_start_date_filter(self, mock_session: mock.MagicMock) -> None:
+ watermark = datetime(2026, 1, 5, tzinfo=UTC)
+ url = _calls_url(0, start_date="2026-01-05T00:00:00+00:00")
+ responses = {url: {"total_count": 1, "count": 1, "calls": [{"call_id": "c1"}]}}
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ batches = list(
+ get_rows(
+ "key",
+ "calls",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ # The router KeyErrors on any URL without the start_date filter, so reaching here proves
+ # the watermark was sent server-side.
+ assert [r["call_id"] for b in batches for r in b] == ["c1"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_saves_state_after_each_page_with_filter(self, mock_session: mock.MagicMock) -> None:
+ start_date = "2026-01-05T00:00:00+00:00"
+ responses = {
+ _calls_url(0, start_date): {"total_count": 3, "count": 2, "calls": [{"call_id": "c1"}, {"call_id": "c2"}]},
+ _calls_url(2, start_date): {"total_count": 3, "count": 1, "calls": [{"call_id": "c3"}]},
+ }
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "key",
+ "calls",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),
+ )
+ )
+
+ # State is saved once (after page one; page two hits total_count) and carries both the next
+ # offset and the exact filter, so a resume continues the same result set.
+ manager.save_state.assert_called_once()
+ saved = manager.save_state.call_args.args[0]
+ assert saved.offset == 2
+ assert saved.start_date == start_date
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_offset_and_filter(self, mock_session: mock.MagicMock) -> None:
+ saved_filter = "2026-01-05T00:00:00+00:00"
+ responses = {
+ _calls_url(2, saved_filter): {"total_count": 3, "count": 1, "calls": [{"call_id": "c3"}]},
+ }
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ manager = _make_manager(BlandAIResumeConfig(offset=2, start_date=saved_filter))
+ batches = list(
+ get_rows(
+ "key",
+ "calls",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ # The checkpointed watermark has advanced past the interrupted run's filter; the
+ # resumed run must reuse the saved filter or the saved offset points at the wrong rows.
+ db_incremental_field_last_value=datetime(2026, 1, 7, tzinfo=UTC),
+ )
+ )
+
+ assert [r["call_id"] for b in batches for r in b] == ["c3"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_empty_account_yields_nothing(self, mock_session: mock.MagicMock) -> None:
+ responses = {_calls_url(0): {"total_count": 0, "count": 0, "calls": []}}
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ manager = _make_manager()
+ assert list(get_rows("key", "calls", mock.MagicMock(), manager)) == []
+ manager.save_state.assert_not_called()
+
+
+class TestGetCallTranscriptRows:
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_hydrates_each_call_and_injects_parent_keys(self, mock_session: mock.MagicMock) -> None:
+ responses = {
+ _calls_url(0): {
+ "total_count": 2,
+ "count": 2,
+ "calls": [
+ {"call_id": "c1", "created_at": "2026-01-01T00:00:00+00:00"},
+ {"call_id": "c2", "created_at": "2026-01-02T00:00:00+00:00"},
+ ],
+ },
+ f"{BASE_URL}/v1/calls/c1": {
+ "call_id": "c1",
+ "transcripts": [
+ {"id": 1, "text": "hello", "user": "assistant", "created_at": "2026-01-01T00:00:01+00:00"},
+ {"id": 2, "text": "hi", "user": "user", "created_at": "2026-01-01T00:00:05+00:00"},
+ ],
+ },
+ # A call with no transcripts (e.g. unanswered) must not break the batch.
+ f"{BASE_URL}/v1/calls/c2": {"call_id": "c2", "transcripts": None},
+ }
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ batches = list(get_rows("key", "call_transcripts", mock.MagicMock(), _make_manager()))
+ rows = [row for batch in batches for row in batch]
+
+ assert [r["id"] for r in rows] == [1, 2]
+ # Rows carry the parent call id (composite primary key) and the parent's creation time
+ # (the incremental/partition field — utterance timestamps aren't monotonic across calls).
+ assert all(r["call_id"] == "c1" for r in rows)
+ assert all(r["call_created_at"] == "2026-01-01T00:00:00+00:00" for r in rows)
+ assert rows[0]["text"] == "hello"
+
+
+class TestGetPathwayRows:
+ @parameterized.expand(
+ [
+ # Bare list of pathway objects.
+ ("bare_list", [{"id": "p1"}, {"id": "p2"}], ["p1", "p2"]),
+ # Wrapped list variants.
+ ("wrapped_pathways", {"pathways": [{"id": "p1"}]}, ["p1"]),
+ ("wrapped_data", {"data": [{"id": "p1"}]}, ["p1"]),
+ # A single bare object (the shape the docs' response example shows).
+ ("single_object", {"id": "p1", "name": "Demo", "nodes": []}, ["p1"]),
+ ]
+ )
+ def test_normalizes_response_shapes(self, _name: str, api_response: Any, expected_ids: list[str]) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ responses = {f"{BASE_URL}/v1/pathway": api_response}
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ batches = list(get_rows("key", "pathways", mock.MagicMock(), _make_manager()))
+ rows = [row for batch in batches for row in batch]
+
+ assert [r["id"] for r in rows] == expected_ids
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_empty_pathway_list_yields_nothing(self, mock_session: mock.MagicMock) -> None:
+ responses: dict[str, Any] = {f"{BASE_URL}/v1/pathway": []}
+ mock_session.return_value.get.side_effect = _url_router(responses)
+
+ assert list(get_rows("key", "pathways", mock.MagicMock(), _make_manager())) == []
+
+
+class TestBlandAISourceResponse:
+ def test_endpoints_inventory(self) -> None:
+ assert ENDPOINTS == ("calls", "call_transcripts", "pathways")
+
+ @parameterized.expand(
+ [
+ ("calls", ["call_id"], ["created_at"]),
+ # The composite key keeps utterances unique table-wide; partitioning uses the parent
+ # call's stable creation time.
+ ("call_transcripts", ["call_id", "id"], ["call_created_at"]),
+ ("pathways", ["id"], None),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_keys: list[str]) -> None:
+ response = bland_ai_source("key", endpoint, mock.MagicMock(), _make_manager())
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == partition_keys
+ assert response.partition_mode == ("datetime" if partition_keys else None)
+ # Call listings request ascending=true&sort_by=created_at.
+ assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai_source.py
new file mode 100644
index 000000000000..c71a4bdf829e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bland_ai/tests/test_bland_ai_source.py
@@ -0,0 +1,156 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.bland_ai import BlandAIResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.source import BlandAISource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BlandAISourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBlandAISource:
+ def setup_method(self):
+ self.source = BlandAISource()
+ self.team_id = 123
+ self.config = BlandAISourceConfig(api_key="key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BLANDAI
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "BlandAI"
+ assert config.label == "Bland AI"
+ assert config.category == DataWarehouseSourceCategory.COMMUNICATION
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/bland_ai.svg"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bland-ai"
+
+ 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) and f.name == "api_key")
+ 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] == ["calls", "call_transcripts", "pathways"]
+
+ @parameterized.expand(
+ [
+ # GET /v1/calls has a server-side `start_date` filter, so both call endpoints are incremental.
+ ("calls", True, True),
+ # Hydrating transcripts costs one request per call, so the table is opt-in.
+ ("call_transcripts", True, False),
+ # Pathways have no timestamp filters at all — full refresh only.
+ ("pathways", False, True),
+ ]
+ )
+ def test_get_schemas_incremental_support(self, endpoint, supports_incremental, should_sync_default):
+ 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.should_sync_default is should_sync_default
+ assert schema.incremental_fields == INCREMENTAL_FIELDS[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=["pathways"])] == ["pathways"]
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.bland.ai/v1/calls?from=0&limit=1000",),
+ ("401 Client Error: Unauthorized for url: https://api.bland.ai/v1/pathway",),
+ ]
+ )
+ 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)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.bland.ai/v1/calls",),
+ ("429 Client Error: Too Many Requests for url: https://api.bland.ai/v1/calls",),
+ ("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)
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid Bland AI API key"),
+ ]
+ )
+ def test_validate_credentials(self, _name, mock_return, expected_valid, expected_message):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.source.validate_bland_ai_credentials"
+ ) as mock_validate:
+ 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 BlandAIResumeConfig
+
+ @parameterized.expand(
+ [
+ ("incremental", True, "2026-01-01"),
+ # The watermark must not leak into a full-refresh run.
+ ("full_refresh", False, None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, _name, should_use_incremental_field, expected_last_value):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.source.bland_ai_source"
+ ) as mock_bland_ai_source:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bland_ai_source.assert_called_once()
+ kwargs = mock_bland_ai_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "calls"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == expected_last_value
+
+ def test_canonical_descriptions_keyed_by_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == 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 dbcf2f966574..c6ce0185347e 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
@@ -487,7 +487,7 @@ class BitlySourceConfig(config.Config):
@config.config
class BlandAISourceConfig(config.Config):
- pass
+ api_key: str
@config.config