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(bland_ai): sync sms conversations, numbers, personas and voices (#99804)

Tom Owersab28407cc725
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 345086ae0248..d0378eec7cf5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -847,24 +847,24 @@ Diffed against: <https://api-docs.bitrise.io/docs/swagger.json>
## BlandAI — **thin**
-Today (3): `call_transcripts`, `calls`, `pathways`
+Today (8): `call_transcripts`, `calls`, `inbound_numbers`, `pathways`, `personas`, `sms_conversations`, `sms_messages`, `voices`
Diffed against: <https://docs.bland.ai/llms.txt>
-- [ ] `GET /v1/sms/conversations (and /v1/sms/conversations/{id})` — the entire SMS channel is missing; conversations and their messages sit alongside calls (high)
-- [ ] `GET /v1/inbound` — phone number lookup resolving the numbers on every call row (high)
-- [ ] `GET /v1/personas` — lookup resolving the persona that handled a call (high)
+- [x] `GET /v1/sms/conversations (and /v1/sms/conversations/{id})` — the entire SMS channel is missing; conversations and their messages sit alongside calls (high)
+- [x] `GET /v1/inbound` — phone number lookup resolving the numbers on every call row (high)
+- [x] `GET /v1/personas` — lookup resolving the persona that handled a call (high)
- [ ] `GET /v1/calls/{id}/event-stream` — per-call event timeline (node transitions, tool calls) — finer grained than the transcript (medium)
- [ ] `GET /v1/agents` — web agent lookup, the non-phone counterpart to pathways (medium)
- [ ] `GET /v1/pathway_versions` — pathway version history so a call can be attributed to the version that served it (medium)
-- [ ] `GET /v1/voices` — lookup resolving voice IDs referenced by calls (medium)
+- [x] `GET /v1/voices` — lookup resolving voice IDs referenced by calls (medium)
- [ ] `GET /v1/evals/runs and /v1/evals/runs/{id}/call-results` — per-call eval scores, the quality metric for voice agents (medium)
- [ ] `GET /v1/agent-testing/runs (and /agent-testing/scenarios)` — regression test outcomes per pathway over time (medium)
- [ ] `GET /v1/widget/{id}/threads` — web widget conversation threads, another engagement channel (medium)
- [ ] `GET /v1/audit-logs` — account change history for compliance reporting (low)
- [ ] `GET /v1/knowledge` — knowledge base inventory referenced by pathways (low)
-Note: Source directory has no dynamic table discovery — bland_ai.py exposes the three static tables only. Bland's API is very large (200+ documented operations), so 3 tables is a genuinely small fraction.
+Note: Source directory has no dynamic table discovery — bland_ai.py exposes a static table catalog only. Bland's API is very large (200+ documented operations), so the remaining gaps above are still a sizeable fraction.
## Blogger — gaps
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
index 17c61a9e45cf..34d415a20c81 100644
--- 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
@@ -1,3 +1,4 @@
+import json
import dataclasses
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -11,8 +12,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
rest_api_resources,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import TJsonPath
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
+ PageNumberPaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
@@ -26,19 +29,31 @@ BASE_URL = "https://api.bland.ai"
# GET /v1/calls default (and documented maximum) page size.
PAGE_SIZE = 1000
+# GET /v1/sms/conversations pages default to 25 and document no maximum. 100 keeps the request
+# count down, and the paginator terminates on the response's own `totalPages`, so a server-side
+# clamp to a smaller page still paginates correctly.
+SMS_PAGE_SIZE = 100
+# GET /v1/personas documented maximum page size (the default is 20).
+PERSONAS_PAGE_SIZE = 100
+
+
[email protected](frozen=True)
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
- # cursor pointing into the same result set.
+ # Page number (`page` query param) of the next unfetched page of SMS conversations.
+ page: int | None = None
+ # The exact creation-time filter the interrupted run used — `start_date` on the call
+ # endpoints, the `created_at` `gte` filter entry on the SMS endpoints. 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 cursor pointing into the same result set.
start_date: str | None = None
- # Framework fan-out checkpoint for call_transcripts (completed/current child paths plus the
- # in-progress child paginator state). Optional so state saved before this field existed
- # (offset-only) still parses; such state restarts the fan-out fresh under the saved filter.
+ # Framework fan-out checkpoint for call_transcripts and sms_messages (completed/current child
+ # paths plus the in-progress child paginator state). Optional so state saved before this field
+ # existed (offset-only) still parses; such state restarts the fan-out fresh under the saved
+ # filter.
fanout_state: dict[str, Any] | None = None
@@ -90,6 +105,16 @@ class _PathwaysBodySelector(JSONPath):
return [DatumInContext(rows)]
+# Endpoints that return their whole collection in one unpaginated body, keyed to the path and the
+# selector that picks the rows out of it. All three are small account-level collections with no
+# timestamp filters, so they are full refresh only.
+SINGLE_PAGE_ENDPOINTS: dict[str, tuple[str, TJsonPath]] = {
+ "pathways": ("v1/pathway", _PathwaysBodySelector()),
+ "inbound_numbers": ("v1/inbound", "inbound_numbers"),
+ "voices": ("v1/voices", "voices"),
+}
+
+
def _adopt_parent_call_fields(row: dict[str, Any]) -> dict[str, Any]:
# Rename the injected parent fields onto the utterance row: `call_id` (part of the composite
# primary key) and `call_created_at`, the parent call's creation time. Utterance `created_at`s
@@ -120,6 +145,123 @@ def _calls_list_resource(params: dict[str, Any]) -> EndpointResource:
}
+def _adopt_parent_conversation_fields(row: dict[str, Any]) -> dict[str, Any]:
+ # Rename the injected parent fields onto the message row: `conversation_id` (part of the
+ # composite primary key) and `conversation_created_at`, the parent conversation's creation
+ # time. Message `created_at`s aren't monotonic across conversations (a long-running
+ # conversation's messages postdate the next conversation's creation), so
+ # `conversation_created_at` is the field the incremental cursor and partitioning key off.
+ # `pop` without a default on purpose: a silent None here would corrupt partitions and stall
+ # the incremental watermark.
+ row["conversation_id"] = row.pop("_sms_conversations_id")
+ row["conversation_created_at"] = row.pop("_sms_conversations_created_at")
+ return row
+
+
+def _sms_list_params(created_at_floor: str | None) -> dict[str, Any]:
+ params: dict[str, Any] = {
+ "pageSize": SMS_PAGE_SIZE,
+ # The endpoint defaults to newest-first; ascending creation order lets the pipeline's
+ # incremental watermark checkpoint after every batch.
+ "sortBy": "created_at",
+ "sortDir": "asc",
+ }
+ if created_at_floor:
+ # `filters` is a JSON-encoded array of {field, operator, value} objects. `gte` is
+ # inclusive; the boundary row is re-fetched and deduped by merge.
+ params["filters"] = json.dumps([{"field": "created_at", "operator": "gte", "value": created_at_floor}])
+ return params
+
+
+def _sms_conversations_list_resource(params: dict[str, Any]) -> EndpointResource:
+ return {
+ "name": "sms_conversations",
+ "endpoint": {
+ "path": "v1/sms/conversations",
+ "params": params,
+ "data_selector": "data",
+ # Page-number pagination starting at 1, with the page count in the response body.
+ "paginator": PageNumberPaginator(
+ base_page=1,
+ page_param="page",
+ total_path="extra.pagination.totalPages",
+ ),
+ },
+ }
+
+
+def _sms_resource(
+ rest_config: RESTAPIConfig,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> Resource:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ created_at_floor = resume.start_date
+ else:
+ created_at_floor = _format_start_date(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ list_params = _sms_list_params(created_at_floor)
+
+ if endpoint == "sms_conversations":
+ initial_paginator_state = {"page": resume.page} if resume is not None and resume.page is not None else None
+
+ def save_conversations_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when a next page remains; the hook fires AFTER a page is yielded so a
+ # crash re-yields the last page (merge dedupes) rather than skipping it. The exact
+ # filter is saved alongside so a resume continues the same result set.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(
+ BlandAIResumeConfig(page=int(state["page"]), start_date=created_at_floor)
+ )
+
+ rest_config["resources"] = [_sms_conversations_list_resource(list_params)]
+ return rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_conversations_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ # sms_messages: the conversation list carries only a message count and the last message body,
+ # so list conversations (same pagination/filtering as `sms_conversations`) and hydrate each via
+ # GET /v1/sms/conversations/{id}, emitting one row per message.
+ def save_messages_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(BlandAIResumeConfig(start_date=created_at_floor, fanout_state=state))
+
+ rest_config["resources"] = [
+ _sms_conversations_list_resource(list_params),
+ {
+ "name": "sms_messages",
+ "include_from_parent": ["id", "created_at"],
+ "data_map": _adopt_parent_conversation_fields,
+ "endpoint": {
+ "path": "v1/sms/conversations/{id}",
+ "params": {"id": {"type": "resolve", "resource": "sms_conversations", "field": "id"}},
+ # A conversation with no messages yet is a legit zero-row detail.
+ "data_selector": "data.messages",
+ "paginator": SinglePagePaginator(),
+ },
+ },
+ ]
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_messages_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume is not None else None,
+ )
+ return next(r for r in resources if r.name == "sms_messages")
+
+
def bland_ai_source(
api_key: str,
endpoint: str,
@@ -143,20 +285,43 @@ def bland_ai_source(
}
resource: Resource
- if endpoint == "pathways":
- # Small (name/description/nodes/edges per pathway), no timestamp filters — a single
- # unordered page on a full-refresh-only endpoint.
+ if endpoint in SINGLE_PAGE_ENDPOINTS:
+ path, data_selector = SINGLE_PAGE_ENDPOINTS[endpoint]
rest_config["resources"] = [
{
- "name": "pathways",
+ "name": endpoint,
"endpoint": {
- "path": "v1/pathway",
- "data_selector": _PathwaysBodySelector(),
+ "path": path,
+ "data_selector": data_selector,
"paginator": SinglePagePaginator(),
},
}
]
resource = rest_api_resource(rest_config, team_id, job_id, None)
+ elif endpoint == "personas":
+ rest_config["resources"] = [
+ {
+ "name": "personas",
+ "endpoint": {
+ "path": "v1/personas",
+ "params": {"limit": PERSONAS_PAGE_SIZE},
+ "data_selector": "data",
+ # The body carries no page count, so pagination stops on the first empty page.
+ "paginator": PageNumberPaginator(base_page=1, page_param="page"),
+ },
+ }
+ ]
+ resource = rest_api_resource(rest_config, team_id, job_id, None)
+ elif endpoint in ("sms_conversations", "sms_messages"):
+ resource = _sms_resource(
+ rest_config,
+ endpoint,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
else:
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None:
@@ -237,7 +402,8 @@ def bland_ai_source(
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.
+ # Call endpoints request `ascending=true&sort_by=created_at` and the SMS endpoints
+ # `sortBy=created_at&sortDir=asc`; the lookup endpoints are single unordered pages on
+ # full-refresh-only tables, so the value never drives a watermark for them.
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
index 8301cbc6e201..9b87ff43c3de 100644
--- 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
@@ -79,4 +79,123 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"edges": "Data about the connections between nodes, including the labels and conditions for taking each edge.",
},
},
+ "sms_conversations": {
+ "description": (
+ "A messaging conversation handled by a Bland AI agent over SMS, RCS or WhatsApp. One row "
+ "per conversation, with the numbers involved, the pathway driving it, and the outcome. "
+ "Message bodies live in the sms_messages table."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/sms-conversations",
+ "columns": {
+ "id": "The unique identifier of the conversation.",
+ "created_at": "The timestamp when the conversation was created.",
+ "updated_at": "The timestamp when the conversation was last updated.",
+ "user_number": "The user-facing phone number in the conversation.",
+ "agent_number": "The assistant's phone number in the conversation.",
+ "variables": "Arbitrary variables associated with the conversation.",
+ "current_node_id": "The identifier of the current node in the conversational pathway.",
+ "curr_pathway_id": "The identifier of the pathway currently driving the conversation.",
+ "curr_pathway_version": "The version of the pathway currently driving the conversation.",
+ "timed_out_at": "The timestamp when the conversation timed out due to inactivity, if it did.",
+ "is_active": "Whether the conversation is still active.",
+ "message_count": "The number of messages in the conversation.",
+ "last_message": "The content of the most recent message.",
+ "last_message_at": "The timestamp of the most recent message.",
+ "pathway_tags": "Tags from the pathway nodes visited during the conversation.",
+ "effective_channel": "The resolved delivery channel: sms, rcs, or whatsapp.",
+ "summary": "AI-generated summary of the conversation, if a summary prompt was configured.",
+ "citation_variables": "Citation variable values extracted from the conversation, if citation schemas were configured.",
+ "disposition_tag": "The first successful outcome result tag, if outcomes were configured.",
+ },
+ },
+ "sms_messages": {
+ "description": (
+ "A single message sent or received during a Bland AI messaging conversation. One row per "
+ "message, joined to the sms_conversations table via conversation_id. Fetched from the "
+ "per-conversation detail endpoint since the conversation list returns only a message count."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/sms-conversations-id",
+ "columns": {
+ "id": "The identifier of the message within the conversation.",
+ "created_at": "The timestamp when the message was created.",
+ "message": "The message body.",
+ "from": "The sending phone number.",
+ "to": "The receiving phone number.",
+ "sender": "Who sent the message: USER or AGENT.",
+ "status": "Delivery status of the message: pending, queued, sent, delivered, read, failed, or undelivered.",
+ "error_code": "The Twilio error code if the message failed.",
+ "conversation_id": "The unique identifier of the conversation this message belongs to.",
+ "conversation_created_at": "The timestamp when the parent conversation was created.",
+ },
+ },
+ "inbound_numbers": {
+ "description": (
+ "An inbound phone number configured on your Bland AI account, with the agent settings that "
+ "apply to calls it receives."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/inbound",
+ "columns": {
+ "phone_number": "The inbound phone number.",
+ "created_at": "The timestamp when the number was added to the account.",
+ "prompt": "The prompt the agent follows when the number receives a call.",
+ "webhook": "The URL called with the call details once a call on this number ends.",
+ "voice_id": "The voice the agent uses on calls to this number.",
+ "dynamic_data": "API requests the agent makes mid-call on this number.",
+ "interruption_threshold": "How long the agent waits before treating the caller as interrupting.",
+ "first_sentence": "The sentence the agent opens the call with.",
+ "reduce_latency": "Whether latency reduction is enabled for calls to this number.",
+ "transfer_phone_number": "The number calls are transferred to when the agent hands off.",
+ "voice_settings": "Synthesis overrides applied to the agent's voice on this number.",
+ "record": "Whether calls to this number are recorded.",
+ "max_duration": "The maximum length a call to this number may last, in minutes.",
+ },
+ },
+ "personas": {
+ "description": (
+ "A persona in your Bland AI organization — a reusable agent identity that phone numbers "
+ "attach to, carrying its own prompts, pathway routing, and call configuration."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/personas",
+ "columns": {
+ "id": "The unique identifier of the persona.",
+ "name": "The display name of the persona.",
+ "role": "The role assigned to the persona.",
+ "description": "A description of the persona's purpose.",
+ "tags": "Tags associated with the persona.",
+ "image_url": "The URL of the persona's profile image.",
+ "created_at": "The timestamp when the persona was created.",
+ "updated_at": "The timestamp when the persona was last modified.",
+ "deleted_at": "The timestamp when the persona was deleted, or null while it is active.",
+ "user_id": "The identifier of the user who owns the persona.",
+ "current_production_version_id": "The identifier of the persona's current production version.",
+ "current_draft_version_id": "The identifier of the persona's current draft version.",
+ "inbound_numbers": "The inbound phone numbers attached to the persona.",
+ "current_production_version": "The full production version object, including its prompts, pathway conditions, and call config.",
+ "current_draft_version": "The full draft version object, in the same shape as the production version.",
+ },
+ },
+ "voices": {
+ "description": (
+ "A voice your Bland AI account can use on calls: a Bland curated voice, a voice you cloned, "
+ "or one added from the public library. Resolves the voice_id referenced by calls."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/voices",
+ "columns": {
+ "id": "The unique identifier of the voice, passed as voice_id when sending a call.",
+ "name": "The display name of the voice.",
+ "description": "A short human-readable description of the voice.",
+ "public": "True for shared library and Bland curated voices, false for voices private to your organization.",
+ "tags": "Labels describing the voice, such as language, style, and source.",
+ "user_id": "The identifier of the owner, or null for Bland curated voices.",
+ "voice_id": "The underlying model identifier. The format varies by engine.",
+ "service": "The synthesis engine: BTTS, BTTS_V2, BTTS_V3, or LEGACY.",
+ "finetuned": "Whether the voice has been fine-tuned past the base clone.",
+ "is_creator_voice": "Whether the voice is in the Bland creator program, which may add a per-character fee.",
+ "ratings": "The total number of ratings the voice has received.",
+ "total_ratings": "Alias of ratings, returned for backwards compatibility.",
+ "average_rating": "The average rating of the voice, from 0 to 5.",
+ "my_rating": "Your own rating for the voice, or null if you have not rated it.",
+ "creator_display_name": "The creator's name for voices in the creator program.",
+ },
+ },
}
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
index 0fa4f50f3adc..18cfa5cb0499 100644
--- 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
@@ -43,6 +43,34 @@ class BlandAIEndpointConfig:
#
# - `pathways` — GET /v1/pathway. Small (name/description/nodes/edges per pathway), no timestamp
# filters, so full refresh only.
+#
+# - `sms_conversations` — GET /v1/sms/conversations. The messaging counterpart to `calls`: one row
+# per SMS/RCS/WhatsApp conversation. Page-number pagination (`page` + `pageSize`) with
+# `extra.pagination.totalPages` in the response. `sortBy=created_at&sortDir=asc` plus a
+# `filters` entry of `{"field": "created_at", "operator": "gte", "value": <iso>}` give a genuine
+# server-side incremental cursor on `created_at`. `updated_at` is filterable too, but it moves
+# whenever a message lands, which would rewrite partitions every sync.
+#
+# - `sms_messages` — the individual messages of a conversation. The list endpoint returns only
+# `message_count` and `last_message`, so this endpoint lists conversations (same
+# pagination/filtering as `sms_conversations`) and hydrates each via
+# GET /v1/sms/conversations/{id}, emitting one row per message. One extra request per
+# conversation, so it's off by default. Rows carry the parent `conversation_id` (message ids are
+# documented per conversation, hence the composite key) and `conversation_created_at`, the
+# parent conversation's creation time — the incremental/partition field, since a long-running
+# conversation's messages can postdate the next conversation's creation.
+#
+# - `inbound_numbers` — GET /v1/inbound. The phone numbers configured on the account, resolving the
+# `to`/`from` numbers on call rows. A handful of rows per account, no pagination or timestamp
+# filters, so full refresh with no partitioning.
+#
+# - `personas` — GET /v1/personas. The agent identities attached to inbound numbers, including
+# their production and draft version configs. Page-number pagination (`page` + `limit`, max 100)
+# and no timestamp filters, so full refresh only.
+#
+# - `voices` — GET /v1/voices. Every voice the account can use (Bland curated, cloned, and library
+# voices), resolving the `voice_id` referenced by calls and persona call configs. Single
+# unpaginated page, no timestamp filters, so full refresh only.
BLAND_AI_ENDPOINTS: dict[str, BlandAIEndpointConfig] = {
"calls": BlandAIEndpointConfig(
name="calls",
@@ -90,6 +118,69 @@ BLAND_AI_ENDPOINTS: dict[str, BlandAIEndpointConfig] = {
"Full refresh only (the API has no timestamp filters for pathways)."
),
),
+ "sms_conversations": BlandAIEndpointConfig(
+ name="sms_conversations",
+ primary_keys=["id"],
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ description=(
+ "One row per SMS, RCS or WhatsApp conversation: the numbers involved, the pathway "
+ "driving it, message counts, and the outcome. Message bodies live in sms_messages. "
+ "SMS is an Enterprise-only Bland feature."
+ ),
+ ),
+ "sms_messages": BlandAIEndpointConfig(
+ name="sms_messages",
+ primary_keys=["conversation_id", "id"],
+ partition_key="conversation_created_at",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "conversation_created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "conversation_created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ should_sync_default=False,
+ description=(
+ "One row per message sent or received in an SMS conversation, with its delivery status. "
+ "Requires one extra API request per conversation (the conversation list returns only a "
+ "message count), so syncs are slower than the sms_conversations table."
+ ),
+ ),
+ "inbound_numbers": BlandAIEndpointConfig(
+ name="inbound_numbers",
+ primary_keys=["phone_number"],
+ description=(
+ "The inbound phone numbers configured on your account and their agent settings. Join to "
+ "calls on the number that received the call. Full refresh only."
+ ),
+ ),
+ "personas": BlandAIEndpointConfig(
+ name="personas",
+ primary_keys=["id"],
+ description=(
+ "Your personas — the reusable agent identities attached to phone numbers, with their "
+ "production and draft version configuration. Full refresh only."
+ ),
+ ),
+ "voices": BlandAIEndpointConfig(
+ name="voices",
+ primary_keys=["id"],
+ description=(
+ "Every voice your account can use, including Bland's curated voices, your clones, and "
+ "library voices. Resolves the voice_id referenced by calls. Full refresh only."
+ ),
+ ),
}
ENDPOINTS = tuple(BLAND_AI_ENDPOINTS.keys())
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
index 7b49556172da..769ea92fd5d0 100644
--- 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
@@ -10,6 +10,8 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.bland_ai import (
BASE_URL,
PAGE_SIZE,
+ PERSONAS_PAGE_SIZE,
+ SMS_PAGE_SIZE,
BlandAIResumeConfig,
_format_start_date,
bland_ai_source,
@@ -430,9 +432,285 @@ class TestPathways:
assert _rows(_source("pathways", _make_manager())) == []
+def _conversations_page(ids: list[str], total_pages: int, created_at: str = "2026-01-01T00:00:00.000Z") -> Response:
+ return _response(
+ {
+ "data": [{"id": i, "created_at": created_at} for i in ids],
+ "errors": None,
+ "extra": {"pagination": {"totalItems": 0, "totalPages": total_pages, "currentPage": 1, "pageSize": 100}},
+ }
+ )
+
+
+class TestSmsConversations:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_by_page_number_until_total_pages(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_conversations_page(["v1"], 2), _conversations_page(["v2"], 2)])
+
+ rows = _rows(_source("sms_conversations", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["v1", "v2"]
+ # Reaching totalPages terminates without paying for an extra empty page.
+ assert session.send.call_count == 2
+ assert snapshots[0]["url"] == f"{BASE_URL}/v1/sms/conversations"
+ assert snapshots[0]["params"]["page"] == 1
+ assert snapshots[0]["params"]["pageSize"] == SMS_PAGE_SIZE
+ # The endpoint defaults to newest-first; the watermark needs ascending creation order.
+ assert snapshots[0]["params"]["sortBy"] == "created_at"
+ assert snapshots[0]["params"]["sortDir"] == "asc"
+ assert snapshots[1]["params"]["page"] == 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_sends_no_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_conversations_page(["v1"], 1)])
+
+ _rows(_source("sms_conversations", _make_manager()))
+
+ assert "filters" not in snapshots[0]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_watermark_becomes_created_at_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_conversations_page(["v1"], 1)])
+
+ rows = _rows(
+ _source(
+ "sms_conversations",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),
+ )
+ )
+
+ assert [r["id"] for r in rows] == ["v1"]
+ # `filters` is a JSON-encoded array of {field, operator, value} objects.
+ assert json.loads(snapshots[0]["params"]["filters"]) == [
+ {"field": "created_at", "operator": "gte", "value": "2026-01-05T00:00:00+00:00"}
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_state_after_each_page_with_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_conversations_page(["v1"], 2), _conversations_page(["v2"], 2)])
+
+ manager = _make_manager()
+ _rows(
+ _source(
+ "sms_conversations",
+ 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 is the last) and carries both the next page
+ # 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.page == 2
+ assert saved.start_date == "2026-01-05T00:00:00+00:00"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page_and_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ saved_filter = "2026-01-05T00:00:00+00:00"
+ snapshots = _wire(session, [_conversations_page(["v3"], 3)])
+
+ manager = _make_manager(BlandAIResumeConfig(page=3, start_date=saved_filter))
+ rows = _rows(
+ _source(
+ "sms_conversations",
+ 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 page points at other rows.
+ db_incremental_field_last_value=datetime(2026, 1, 7, tzinfo=UTC),
+ )
+ )
+
+ assert [r["id"] for r in rows] == ["v3"]
+ assert snapshots[0]["params"]["page"] == 3
+ assert json.loads(snapshots[0]["params"]["filters"])[0]["value"] == saved_filter
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_account_yields_nothing(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_conversations_page([], 0)])
+
+ manager = _make_manager()
+ assert _rows(_source("sms_conversations", manager)) == []
+ manager.save_state.assert_not_called()
+
+
+class TestSmsMessages:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_hydrates_each_conversation_and_injects_parent_keys(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response(
+ {
+ "data": [
+ {"id": "v1", "created_at": "2026-01-01T00:00:00.000Z"},
+ {"id": "v2", "created_at": "2026-01-02T00:00:00.000Z"},
+ ],
+ "extra": {"pagination": {"totalPages": 1}},
+ }
+ ),
+ _response(
+ {
+ "data": {
+ "id": "v1",
+ "messages": [
+ {"id": 100001, "message": "hey", "sender": "USER", "status": "delivered"},
+ {"id": 100002, "message": "hi", "sender": "AGENT", "status": "sent"},
+ ],
+ }
+ }
+ ),
+ # A conversation with no messages yet must not break the batch.
+ _response({"data": {"id": "v2", "messages": None}}),
+ ],
+ )
+
+ rows = _rows(_source("sms_messages", _make_manager()))
+
+ assert [r["id"] for r in rows] == [100001, 100002]
+ # Rows carry the parent conversation id (composite primary key) and the parent's creation
+ # time (the incremental/partition field — message timestamps aren't monotonic across
+ # conversations).
+ assert all(r["conversation_id"] == "v1" for r in rows)
+ assert all(r["conversation_created_at"] == "2026-01-01T00:00:00.000Z" for r in rows)
+ assert rows[0]["message"] == "hey"
+ # One list request plus one hydration request per listed conversation.
+ assert [s["url"] for s in snapshots] == [
+ f"{BASE_URL}/v1/sms/conversations",
+ f"{BASE_URL}/v1/sms/conversations/v1",
+ f"{BASE_URL}/v1/sms/conversations/v2",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_checkpoints_fanout_state_with_filter(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _conversations_page(["v1"], 1, created_at="2026-01-05T00:00:00.000Z"),
+ _response({"data": {"id": "v1", "messages": [{"id": 1}]}}),
+ ],
+ )
+
+ manager = _make_manager()
+ _rows(
+ _source(
+ "sms_messages",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 5, tzinfo=UTC),
+ )
+ )
+
+ assert manager.save_state.call_count > 0
+ saved = manager.save_state.call_args.args[0]
+ assert saved.fanout_state["completed"] == ["v1/sms/conversations/v1"]
+ assert saved.fanout_state["current"] is None
+ assert saved.start_date == "2026-01-05T00:00:00+00:00"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_already_hydrated_conversations(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response(
+ {
+ "data": [
+ {"id": "v1", "created_at": "2026-01-01T00:00:00.000Z"},
+ {"id": "v2", "created_at": "2026-01-02T00:00:00.000Z"},
+ ],
+ "extra": {"pagination": {"totalPages": 1}},
+ }
+ ),
+ _response({"data": {"id": "v2", "messages": [{"id": 7, "message": "yo"}]}}),
+ ],
+ )
+
+ manager = _make_manager(
+ BlandAIResumeConfig(
+ start_date=None,
+ fanout_state={"completed": ["v1/sms/conversations/v1"], "current": None, "child_state": None},
+ )
+ )
+ rows = _rows(_source("sms_messages", manager))
+
+ # v1 was fully hydrated before the interruption — only v2 is fetched again.
+ assert [r["id"] for r in rows] == [7]
+ assert all(r["conversation_id"] == "v2" for r in rows)
+ assert [s["url"] for s in snapshots] == [
+ f"{BASE_URL}/v1/sms/conversations",
+ f"{BASE_URL}/v1/sms/conversations/v2",
+ ]
+
+
+class TestLookupEndpoints:
+ @parameterized.expand(
+ [
+ # The response wrapper key differs per endpoint; a wrong selector silently yields
+ # zero rows instead of failing.
+ ("inbound_numbers", "v1/inbound", {"inbound_numbers": [{"phone_number": "+15550001111"}]}, "phone_number"),
+ ("voices", "v1/voices", {"voices": [{"id": "voice-1", "name": "Karen"}]}, "id"),
+ ]
+ )
+ def test_single_page_lookup_selects_rows(
+ self, endpoint: str, path: str, api_response: dict[str, Any], key: str
+ ) -> None:
+ with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response(api_response)])
+
+ rows = _rows(_source(endpoint, _make_manager()))
+
+ assert len(rows) == 1
+ assert rows[0][key] == api_response[endpoint][0][key]
+ assert session.send.call_count == 1
+ assert snapshots[0]["url"] == f"{BASE_URL}/{path}"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_personas_paginate_until_empty_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"data": [{"id": "p1", "name": "Support"}], "errors": None}),
+ # The body carries no page count, so an empty page is what ends pagination.
+ _response({"data": [], "errors": None}),
+ ],
+ )
+
+ rows = _rows(_source("personas", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["p1"]
+ assert snapshots[0]["url"] == f"{BASE_URL}/v1/personas"
+ assert snapshots[0]["params"]["page"] == 1
+ assert snapshots[0]["params"]["limit"] == PERSONAS_PAGE_SIZE
+ assert snapshots[1]["params"]["page"] == 2
+
+
class TestBlandAISourceResponse:
def test_endpoints_inventory(self) -> None:
- assert ENDPOINTS == ("calls", "call_transcripts", "pathways")
+ assert ENDPOINTS == (
+ "calls",
+ "call_transcripts",
+ "pathways",
+ "sms_conversations",
+ "sms_messages",
+ "inbound_numbers",
+ "personas",
+ "voices",
+ )
@parameterized.expand(
[
@@ -441,6 +719,14 @@ class TestBlandAISourceResponse:
# call's stable creation time.
("call_transcripts", ["call_id", "id"], ["call_created_at"]),
("pathways", ["id"], None),
+ ("sms_conversations", ["id"], ["created_at"]),
+ # The composite key keeps messages unique table-wide; partitioning uses the parent
+ # conversation's stable creation time.
+ ("sms_messages", ["conversation_id", "id"], ["conversation_created_at"]),
+ # Small account-level lookups — no partitioning.
+ ("inbound_numbers", ["phone_number"], None),
+ ("personas", ["id"], None),
+ ("voices", ["id"], None),
]
)
def test_source_response_shape(
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
index b19536be96d3..0d234d9d5e1f 100644
--- 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
@@ -22,7 +22,16 @@ class TestBlandAISource:
# 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"]
+ assert [t["name"] for t in documented] == [
+ "calls",
+ "call_transcripts",
+ "pathways",
+ "sms_conversations",
+ "sms_messages",
+ "inbound_numbers",
+ "personas",
+ "voices",
+ ]
@parameterized.expand(
[
@@ -32,6 +41,14 @@ class TestBlandAISource:
("call_transcripts", True, False),
# Pathways have no timestamp filters at all — full refresh only.
("pathways", False, True),
+ # GET /v1/sms/conversations filters on `created_at` with a `gte` operator.
+ ("sms_conversations", True, True),
+ # Hydrating messages costs one request per conversation, so the table is opt-in.
+ ("sms_messages", True, False),
+ # Account-level lookups with no timestamp filters — full refresh only.
+ ("inbound_numbers", False, True),
+ ("personas", False, True),
+ ("voices", False, True),
]
)
def test_get_schemas_incremental_support(self, endpoint, supports_incremental, should_sync_default):