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): add 5 missing tables to the BlandAI source (#118970)

Tom Owers3c670e16d369
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 962aa517b573..f94fd8e2c637 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
@@ -1682,18 +1682,18 @@ Diffed against: <https://api-docs.bitrise.io/docs/swagger.json>
## BlandAI — **thin**
-Today (8): `call_transcripts`, `calls`, `inbound_numbers`, `pathways`, `personas`, `sms_conversations`, `sms_messages`, `voices`
+Today (13): `call_events`, `call_transcripts`, `calls`, `eval_call_results`, `eval_runs`, `inbound_numbers`, `pathway_versions`, `pathways`, `personas`, `sms_conversations`, `sms_messages`, `voices`, `web_agents`
Diffed against: <https://docs.bland.ai/llms.txt>
- [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)
+- [x] `GET /v1/calls/{id}/event-stream` — per-call event timeline (node transitions, tool calls) — finer grained than the transcript (medium)
+- [x] `GET /v1/agents` — web agent lookup, the non-phone counterpart to pathways (medium)
+- [x] `GET /v1/pathway_versions` — pathway version history so a call can be attributed to the version that served it (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)
+- [x] `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)
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 34d415a20c81..02bd8a2c3e73 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
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
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 (
+ JSONResponseCursorPaginator,
OffsetPaginator,
PageNumberPaginator,
SinglePagePaginator,
@@ -37,6 +38,10 @@ SMS_PAGE_SIZE = 100
# GET /v1/personas documented maximum page size (the default is 20).
PERSONAS_PAGE_SIZE = 100
+# GET /v1/evals/runs and /v1/evals/runs/{run_id}/call-results documented maximum page size (the
+# default is 25).
+EVALS_PAGE_SIZE = 100
+
@dataclasses.dataclass(frozen=True)
class BlandAIResumeConfig:
@@ -44,13 +49,15 @@ class BlandAIResumeConfig:
offset: int = 0
# Page number (`page` query param) of the next unfetched page of SMS conversations.
page: int | None = None
+ # `starting_after` cursor of the next unfetched page of eval runs.
+ cursor: str | 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 and sms_messages (completed/current child
+ # Framework fan-out checkpoint for the fan-out endpoints (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.
@@ -105,21 +112,48 @@ class _PathwaysBodySelector(JSONPath):
return [DatumInContext(rows)]
+class _EventStreamSelector(JSONPath):
+ """Data selector for GET /v1/event_stream/{call_id}, numbering each event in the stream.
+
+ The docs only describe the shape of one event, so accept a bare list or a common list wrapper.
+ Events carry no id; their position in the chronological stream keys the row.
+ """
+
+ def find(self, data: Any) -> list[DatumInContext]:
+ if isinstance(data, list):
+ events = data
+ elif isinstance(data, dict):
+ events = next((data[key] for key in ("events", "data") if isinstance(data.get(key), list)), [])
+ else:
+ events = []
+ rows = [{**event, "event_index": index} for index, event in enumerate(events) if isinstance(event, dict)]
+ 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
+# selector that picks the rows out of it. All 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"),
+ "web_agents": ("v1/agents", "agents"),
+}
+
+# Endpoints that list calls and hydrate each one, keyed to the per-call path and the selector that
+# picks the child rows out of the per-call body.
+CALL_FANOUT_ENDPOINTS: dict[str, tuple[str, TJsonPath]] = {
+ # A call with no transcripts (e.g. unanswered) is a legit zero-row detail.
+ "call_transcripts": ("v1/calls/{call_id}", "transcripts"),
+ "call_events": ("v1/event_stream/{call_id}", _EventStreamSelector()),
}
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
- # aren't monotonic across calls (a long call's utterances postdate the next call's creation),
- # so `call_created_at` is the field the incremental cursor and partitioning key off.
+ # Rename the injected parent fields onto the utterance or event row: `call_id` (part of the
+ # composite primary key) and `call_created_at`, the parent call's creation time. Child
+ # timestamps aren't monotonic across calls (a long call's utterances postdate the next call's
+ # creation), so `call_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["call_id"] = row.pop("_calls_call_id")
@@ -145,6 +179,130 @@ def _calls_list_resource(params: dict[str, Any]) -> EndpointResource:
}
+def _adopt_parent_pathway_id(row: dict[str, Any]) -> dict[str, Any]:
+ row["pathway_id"] = row.pop("_pathways_id")
+ return row
+
+
+def _evals_cursor_paginator() -> JSONResponseCursorPaginator:
+ # The list sits under `data.data`; `data.next_cursor` is null on the last page.
+ return JSONResponseCursorPaginator(cursor_path="data.next_cursor", cursor_param="starting_after")
+
+
+def _eval_runs_list_resource() -> EndpointResource:
+ return {
+ "name": "eval_runs",
+ "endpoint": {
+ "path": "v1/evals/runs",
+ "params": {"limit": EVALS_PAGE_SIZE},
+ "data_selector": "data.data",
+ "paginator": _evals_cursor_paginator(),
+ },
+ }
+
+
+def _pathway_versions_resource(
+ rest_config: RESTAPIConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+) -> Resource:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(BlandAIResumeConfig(fanout_state=state))
+
+ rest_config["resources"] = [
+ {
+ "name": "pathways",
+ "endpoint": {
+ "path": "v1/pathway",
+ "data_selector": _PathwaysBodySelector(),
+ "paginator": SinglePagePaginator(),
+ },
+ },
+ {
+ "name": "pathway_versions",
+ "include_from_parent": ["id"],
+ "data_map": _adopt_parent_pathway_id,
+ "endpoint": {
+ "path": "v1/pathway/{pathway_id}/versions",
+ "params": {"pathway_id": {"type": "resolve", "resource": "pathways", "field": "id"}},
+ # The documented body is a bare list of versions.
+ "data_selector": "$",
+ "paginator": SinglePagePaginator(),
+ },
+ },
+ ]
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume is not None else None,
+ )
+ return next(r for r in resources if r.name == "pathway_versions")
+
+
+def _evals_resource(
+ rest_config: RESTAPIConfig,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BlandAIResumeConfig],
+) -> Resource:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if endpoint == "eval_runs":
+ initial_paginator_state = {"cursor": resume.cursor} if resume is not None and resume.cursor else None
+
+ def save_runs_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(BlandAIResumeConfig(cursor=str(state["cursor"])))
+
+ rest_config["resources"] = [_eval_runs_list_resource()]
+ return rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_runs_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ # eval_call_results: each row already carries its `eval_run_id`, so no parent field is injected.
+ def save_results_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(BlandAIResumeConfig(fanout_state=state))
+
+ rest_config["resources"] = [
+ _eval_runs_list_resource(),
+ {
+ "name": "eval_call_results",
+ "endpoint": {
+ "path": "v1/evals/runs/{run_id}/call-results",
+ "params": {
+ "run_id": {"type": "resolve", "resource": "eval_runs", "field": "id"},
+ "limit": EVALS_PAGE_SIZE,
+ },
+ "data_selector": "data.data",
+ "paginator": _evals_cursor_paginator(),
+ },
+ },
+ ]
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_results_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume is not None else None,
+ )
+ return next(r for r in resources if r.name == "eval_call_results")
+
+
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
@@ -312,6 +470,10 @@ def bland_ai_source(
}
]
resource = rest_api_resource(rest_config, team_id, job_id, None)
+ elif endpoint == "pathway_versions":
+ resource = _pathway_versions_resource(rest_config, team_id, job_id, resumable_source_manager)
+ elif endpoint in ("eval_runs", "eval_call_results"):
+ resource = _evals_resource(rest_config, endpoint, team_id, job_id, resumable_source_manager)
elif endpoint in ("sms_conversations", "sms_messages"):
resource = _sms_resource(
rest_config,
@@ -360,25 +522,26 @@ def bland_ai_source(
resume_hook=save_calls_checkpoint,
initial_paginator_state=initial_paginator_state,
)
- else: # 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.
- def save_transcripts_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ else: # call_transcripts, call_events
+ # Transcripts are excluded from the list endpoint for size reasons, and events live on
+ # their own endpoint, so these list calls (same pagination/filtering as `calls`) and
+ # hydrate each one, emitting one row per utterance or event.
+ child_path, child_selector = CALL_FANOUT_ENDPOINTS[endpoint]
+
+ def save_call_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
if state is not None:
resumable_source_manager.save_state(BlandAIResumeConfig(start_date=start_date, fanout_state=state))
rest_config["resources"] = [
_calls_list_resource(list_params),
{
- "name": "call_transcripts",
+ "name": endpoint,
"include_from_parent": ["call_id", "created_at"],
"data_map": _adopt_parent_call_fields,
"endpoint": {
- "path": "v1/calls/{call_id}",
+ "path": child_path,
"params": {"call_id": {"type": "resolve", "resource": "calls", "field": "call_id"}},
- # A call with no transcripts (e.g. unanswered) is a legit zero-row detail.
- "data_selector": "transcripts",
+ "data_selector": child_selector,
"paginator": SinglePagePaginator(),
},
},
@@ -388,10 +551,10 @@ def bland_ai_source(
team_id,
job_id,
None,
- resume_hook=save_transcripts_checkpoint,
+ resume_hook=save_call_fanout_checkpoint,
initial_paginator_state=resume.fanout_state if resume is not None else None,
)
- resource = next(r for r in resources if r.name == "call_transcripts")
+ resource = next(r for r in resources if r.name == endpoint)
return SourceResponse(
name=endpoint,
@@ -403,7 +566,7 @@ def bland_ai_source(
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` 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.
+ # `sortBy=created_at&sortDir=asc`; the other endpoints are 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 9b87ff43c3de..3e3a4134f5b1 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
@@ -198,4 +198,102 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"creator_display_name": "The creator's name for voices in the creator program.",
},
},
+ "call_events": {
+ "description": (
+ "A single event logged during a Bland AI call, from the call's event stream. One row per "
+ "event, joined to the calls table via call_id."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/event-stream",
+ "columns": {
+ "call_id": "The unique identifier for the call.",
+ "event_index": "The position of the event in the call's event stream, starting at 0.",
+ "call_created_at": "The creation time of the parent call.",
+ "level": "The level of the event: queue or call.",
+ "message": "The message of the event.",
+ "category": "The category of the event: info, performance or error.",
+ "timestamp": "When the event occurred.",
+ },
+ },
+ "web_agents": {
+ "description": "A web agent: a voice agent that talks to visitors in a browser instead of over the phone.",
+ "docs_url": "https://docs.bland.ai/api-v1/get/agents",
+ "columns": {
+ "agent_id": "The unique identifier for the agent.",
+ "webhook": "The webhook URL for the agent.",
+ "dynamic_data": "Dynamic data objects the agent loads.",
+ "interruption_threshold": "The threshold for agent interruption.",
+ "first_sentence": "The first sentence the agent will say.",
+ "model": "The model used by the agent.",
+ "voice_settings": "The voice settings for the agent.",
+ "voice": "The voice used by the agent.",
+ "prompt": "The prompt for the agent.",
+ "temperature": "The temperature setting for the agent.",
+ "max_duration": "The maximum call duration for the agent.",
+ "language": "The language used by the agent.",
+ "tools": "The custom tools the agent can use.",
+ },
+ },
+ "pathway_versions": {
+ "description": "A version of a conversational pathway. Joined to the pathways table via pathway_id.",
+ "docs_url": "https://docs.bland.ai/api-v1/get/pathway_versions",
+ "columns": {
+ "pathway_id": "The ID of the pathway this version belongs to.",
+ "id": "The unique identifier of the pathway version.",
+ "version_number": "The version number of this pathway version.",
+ "created_at": "The timestamp when this version was created.",
+ "name": "The name of this pathway version.",
+ "is_latest": "Whether this is the latest version of the pathway.",
+ },
+ },
+ "eval_runs": {
+ "description": "An eval run: a batch of calls scored by one or more LLM judges (eval agents).",
+ "docs_url": "https://docs.bland.ai/api-v1/get/evals-runs",
+ "columns": {
+ "id": "Unique identifier for the eval run.",
+ "status": "Current status of the run: PENDING, QUEUED, RUNNING, COMPLETE, PARTIAL, FAILED or CANCELLED.",
+ "triggered_by": "How the run was triggered: manual, auto or backfill.",
+ "run_mode": "The scoring modality used: text, audio or full.",
+ "resolved_call_count": "Number of calls resolved for the run.",
+ "resolved_agent_count": "Number of eval agents resolved for the run.",
+ "resolved_atom_count": "Total number of call-by-agent evaluations in the run.",
+ "completed_atom_count": "Number of evaluations that have completed.",
+ "summary": "Aggregate scoring summary for the run, or null if not yet available.",
+ "billable_cost_usd": "Billable cost for this run in USD.",
+ "workbench_setup_id": "The workbench setup the run was started from, if any.",
+ "workbench_setup_version_id": "The pinned workbench setup version used, if any.",
+ "metadata": "Key-value metadata attached to the run.",
+ "created_at": "ISO 8601 timestamp when the run was created.",
+ "started_at": "ISO 8601 timestamp when the run started, or null if not yet started.",
+ "completed_at": "ISO 8601 timestamp when the run completed, or null if not yet complete.",
+ },
+ },
+ "eval_call_results": {
+ "description": (
+ "The result of scoring one call in an eval run. Joined to eval_runs via eval_run_id and to "
+ "calls via call_id."
+ ),
+ "docs_url": "https://docs.bland.ai/api-v1/get/evals-runs-id-call-results",
+ "columns": {
+ "id": "Unique identifier for this call result.",
+ "org_id": "The organization that owns this result.",
+ "eval_run_id": "The eval run this result belongs to.",
+ "call_id": "The ID of the call that was scored.",
+ "call_display_name": "Display name of the call, if available.",
+ "call_started_at": "ISO 8601 timestamp when the call started.",
+ "call_duration_seconds": "Duration of the call in seconds.",
+ "call_ended_by": "Which party ended the call.",
+ "transcript_snapshot_ref": "Reference to the transcript snapshot used for scoring.",
+ "transcript_snapshot_expires_at": "ISO 8601 timestamp when the transcript snapshot expires.",
+ "status": "Status of this call's evaluation: PENDING, QUEUED, RUNNING, COMPLETE, FAILED or INSUFFICIENT_EVIDENCE.",
+ "started_at": "ISO 8601 timestamp when scoring started for this call.",
+ "completed_at": "ISO 8601 timestamp when scoring completed for this call.",
+ "overall_score_normalized_0_100": "Overall weighted score for this call, normalized 0-100.",
+ "text_score_normalized_0_100": "Text-modality score for this call, normalized 0-100.",
+ "audio_score_normalized_0_100": "Audio-modality score for this call, normalized 0-100.",
+ "failed_agent_count": "Number of agent evaluations that failed for this call.",
+ "insufficient_evidence_agent_count": "Number of agent evaluations that returned insufficient evidence.",
+ "agent_results": "Per-agent verdicts for this call. Empty, because the sync does not request them inline.",
+ "created_at": "ISO 8601 timestamp when this call result was created.",
+ },
+ },
}
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 18cfa5cb0499..96ac75a37321 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
@@ -71,6 +71,28 @@ class BlandAIEndpointConfig:
# - `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.
+#
+# - `call_events` — GET /v1/event_stream/{call_id}. The queue- and call-level event log of a call
+# (info, performance and error messages). Lists calls like `call_transcripts` and hydrates each,
+# one extra request per call, so it's off by default. Events carry no id, so rows are keyed on
+# the parent `call_id` plus `event_index`, the event's position in the call's chronological
+# stream. Incremental/partitioned on `call_created_at` for the same reason as `call_transcripts`.
+#
+# - `web_agents` — GET /v1/agents. The web (browser) agents on the account, the non-phone
+# counterpart to inbound numbers. Single unpaginated page, no timestamp filters, so full refresh.
+#
+# - `pathway_versions` — GET /v1/pathway/{pathway_id}/versions, fanned out over GET /v1/pathway.
+# Version ids aren't documented as globally unique, so rows carry the parent `pathway_id` in a
+# composite key. No timestamp filters, so full refresh only.
+#
+# - `eval_runs` — GET /v1/evals/runs. Batches of calls scored by LLM judges, with the aggregate
+# score summary. Cursor pagination (`starting_after` + `data.next_cursor`) and no timestamp
+# filters, so full refresh only. Off by default: Evals must be enabled on the organization.
+#
+# - `eval_call_results` — GET /v1/evals/runs/{run_id}/call-results, fanned out over the eval runs.
+# One row per scored call per run, with the normalized scores. Same cursor pagination as
+# `eval_runs`; rows carry their own `eval_run_id`, which goes in the composite key. Off by
+# default for the same reason as `eval_runs`.
BLAND_AI_ENDPOINTS: dict[str, BlandAIEndpointConfig] = {
"calls": BlandAIEndpointConfig(
name="calls",
@@ -181,6 +203,65 @@ BLAND_AI_ENDPOINTS: dict[str, BlandAIEndpointConfig] = {
"library voices. Resolves the voice_id referenced by calls. Full refresh only."
),
),
+ "call_events": BlandAIEndpointConfig(
+ name="call_events",
+ primary_keys=["call_id", "event_index"],
+ partition_key="call_created_at",
+ 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 event logged during a call: queue and call events with their category "
+ "(info, performance or error). Requires one extra API request per call, so syncs are "
+ "slower than the calls table."
+ ),
+ ),
+ "web_agents": BlandAIEndpointConfig(
+ name="web_agents",
+ primary_keys=["agent_id"],
+ description=(
+ "Your web agents — the voice agents that talk to visitors in a browser instead of over "
+ "the phone — with their prompt, voice and model settings. Full refresh only."
+ ),
+ ),
+ "pathway_versions": BlandAIEndpointConfig(
+ name="pathway_versions",
+ primary_keys=["pathway_id", "id"],
+ partition_key="created_at",
+ description=(
+ "The version history of each conversational pathway: version number, name, creation "
+ "time and whether it is the latest. Full refresh only."
+ ),
+ ),
+ "eval_runs": BlandAIEndpointConfig(
+ name="eval_runs",
+ primary_keys=["id"],
+ partition_key="created_at",
+ should_sync_default=False,
+ description=(
+ "Your eval runs — batches of calls scored by LLM judges — with their status, cost and "
+ "aggregate score summary. Requires Evals to be enabled on your Bland organization. "
+ "Full refresh only."
+ ),
+ ),
+ "eval_call_results": BlandAIEndpointConfig(
+ name="eval_call_results",
+ primary_keys=["eval_run_id", "id"],
+ partition_key="created_at",
+ should_sync_default=False,
+ description=(
+ "One row per call scored in an eval run, with its overall, text and audio scores "
+ "normalized to 0-100. Requires Evals to be enabled on your Bland organization. "
+ "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 aa6c4cfc6608..de84d4b8d09f 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
@@ -6,6 +6,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.bland_ai.bland_ai import (
BASE_URL,
+ EVALS_PAGE_SIZE,
PAGE_SIZE,
SMS_PAGE_SIZE,
BlandAIResumeConfig,
@@ -120,6 +121,43 @@ class TestCallTranscripts:
# One list request plus one hydration request per listed call.
assert result.paths == ["/v1/calls", "/v1/calls/c1", "/v1/calls/c2"]
+ @parameterized.expand(
+ [
+ ("bare_list", lambda events: events),
+ ("wrapped_events", lambda events: {"events": events}),
+ ("wrapped_data", lambda events: {"data": events, "errors": None}),
+ ]
+ )
+ def test_call_events_hydrates_each_call_and_numbers_events(self, _name: str, wrap: Any) -> None:
+ events = [
+ {"level": "queue", "message": "Call queued", "category": "info", "timestamp": "2026-01-01T00:00:00Z"},
+ {"level": "call", "message": "LLM 420ms", "category": "performance", "timestamp": "2026-01-01T00:00:02Z"},
+ ]
+ result = _driver().run(
+ "call_events",
+ [
+ ScriptedResponse(
+ json={
+ "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"},
+ ],
+ }
+ ),
+ ScriptedResponse(json=wrap(events)),
+ ScriptedResponse(json=wrap([])),
+ ],
+ )
+
+ assert result.raised is None
+ # Events carry no id; the position in the stream completes the composite key.
+ assert [(row["call_id"], row["event_index"]) for row in result.rows] == [("c1", 0), ("c1", 1)]
+ assert [row["category"] for row in result.rows] == ["info", "performance"]
+ assert all(row["call_created_at"] == "2026-01-01T00:00:00+00:00" for row in result.rows)
+ assert result.paths == ["/v1/calls", "/v1/event_stream/c1", "/v1/event_stream/c2"]
+
def test_old_format_resume_state_restarts_fanout_under_saved_filter(self) -> None:
saved_filter = "2026-01-05T00:00:00+00:00"
# State saved before fanout_state existed (offset-only): the fan-out restarts from the top
@@ -282,21 +320,100 @@ class TestLookupEndpoints:
[
# 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"),
+ ("inbound_numbers", "v1/inbound", "inbound_numbers", {"phone_number": "+15550001111"}, "phone_number"),
+ ("voices", "v1/voices", "voices", {"id": "voice-1", "name": "Karen"}, "id"),
+ ("web_agents", "v1/agents", "agents", {"agent_id": "agent-1", "voice": "Karen"}, "agent_id"),
]
)
def test_single_page_lookup_selects_rows(
- self, endpoint: str, path: str, api_response: dict[str, Any], key: str
+ self, endpoint: str, path: str, wrapper: str, row: dict[str, Any], key: str
) -> None:
- result = _driver().run(endpoint, [ScriptedResponse(json=api_response)])
+ result = _driver().run(endpoint, [ScriptedResponse(json={wrapper: [row]})])
assert result.raised is None
assert len(result.rows) == 1
- assert result.rows[0][key] == api_response[endpoint][0][key]
+ assert result.rows[0][key] == row[key]
assert result.paths == [f"/{path}"]
+class TestPathwayVersions:
+ def test_fans_out_over_pathways_and_injects_pathway_id(self) -> None:
+ result = _driver().run(
+ "pathway_versions",
+ [
+ ScriptedResponse(json=[{"id": "p1"}, {"id": "p2"}]),
+ ScriptedResponse(
+ json=[
+ {"id": "v1", "version_number": 1, "created_at": "2026-01-01T00:00:00Z", "is_latest": False},
+ {"id": "v2", "version_number": 2, "created_at": "2026-01-02T00:00:00Z", "is_latest": True},
+ ]
+ ),
+ # A single version still parses as one row, not as a list of keys.
+ ScriptedResponse(json=[{"id": "v1", "version_number": 1, "created_at": "2026-01-03T00:00:00Z"}]),
+ ],
+ )
+
+ assert result.raised is None
+ # Version ids repeat across pathways, so the parent id must reach every row.
+ assert [(row["pathway_id"], row["id"]) for row in result.rows] == [("p1", "v1"), ("p1", "v2"), ("p2", "v1")]
+ assert result.paths == ["/v1/pathway", "/v1/pathway/p1/versions", "/v1/pathway/p2/versions"]
+
+
+def _evals_page(rows: list[dict[str, Any]], next_cursor: str | None) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={
+ "data": {"object": "list", "data": rows, "has_more": next_cursor is not None, "next_cursor": next_cursor},
+ "errors": None,
+ }
+ )
+
+
+class TestEvals:
+ @parameterized.expand(
+ [
+ ("fresh", None, [None, "r2"]),
+ ("resumed", BlandAIResumeConfig(cursor="r0"), ["r0", "r2"]),
+ ]
+ )
+ def test_eval_runs_walk_cursor_pages(
+ self, _name: str, resume_state: BlandAIResumeConfig | None, expected_cursors: list[str | None]
+ ) -> None:
+ result = _driver().run(
+ "eval_runs",
+ [_evals_page([{"id": "r1"}, {"id": "r2"}], "r2"), _evals_page([{"id": "r3"}], None)],
+ resume_state=resume_state,
+ )
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["r1", "r2", "r3"]
+ # A null next_cursor ends the walk without a third request.
+ assert result.paths == ["/v1/evals/runs", "/v1/evals/runs"]
+ assert result.params("starting_after") == expected_cursors
+ assert result.params("limit") == [str(EVALS_PAGE_SIZE)] * 2
+
+ def test_eval_call_results_paginate_per_run(self) -> None:
+ result = _driver().run(
+ "eval_call_results",
+ [
+ _evals_page([{"id": "r1"}, {"id": "r2"}], None),
+ _evals_page([{"id": "cr1", "eval_run_id": "r1", "overall_score_normalized_0_100": 88.0}], "cr1"),
+ _evals_page([{"id": "cr2", "eval_run_id": "r1"}], None),
+ _evals_page([{"id": "cr3", "eval_run_id": "r2"}], None),
+ ],
+ )
+
+ assert result.raised is None
+ assert [(row["eval_run_id"], row["id"]) for row in result.rows] == [("r1", "cr1"), ("r1", "cr2"), ("r2", "cr3")]
+ assert result.paths == [
+ "/v1/evals/runs",
+ "/v1/evals/runs/r1/call-results",
+ "/v1/evals/runs/r1/call-results",
+ "/v1/evals/runs/r2/call-results",
+ ]
+ # The first run's cursor must not leak into the second run's first request.
+ assert result.params("starting_after") == [None, None, "cr1", None]
+
+
class TestBlandAISourceResponse:
@parameterized.expand(
[