: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add llama cloud extraction agents, runs and indexes tables (#114531)
Tom Owersa5536a2cef74
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 7c344c30b37f..8e3c69e029a9 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -768,8 +768,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.pydiff --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.mdindex 3d5345df4b30..0f4c22bb6198 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@@ -5238,14 +5238,14 @@ Note: The Akamai/Linode techdocs site serves no spec directly; the authoritative## LlamaCloud — gaps-Today (10): `batches`, `classify_jobs`, `extract_jobs`, `files`, `parse_jobs`, `pipelines`, `projects`, `sheets_jobs`, `split_jobs`, `usage_metrics`+Today (13): `batches`, `classify_jobs`, `extract_jobs`, `extraction_agents`, `extraction_runs`, `files`, `indexes`, `parse_jobs`, `pipelines`, `projects`, `sheets_jobs`, `split_jobs`, `usage_metrics`Diffed against: <https://api.cloud.llamaindex.ai/api/openapi.json>-- [ ] `GET /api/v1/extraction/extraction-agents` — lookup table resolving the extraction-agent id carried on every extract job (high)-- [ ] `GET /api/v1/extraction/runs` — run-level history (status, timings, agent) behind extraction jobs (high)-- [ ] `GET /api/v1/indexes` — top-level index objects; nothing in the current table set exposes them (medium)-- [ ] `GET /api/v1/pipelines/{pipeline_id}/documents/paginated` — per-pipeline document inventory with status, the unit of indexing work (medium)+- [x] `GET /api/v1/extraction/extraction-agents` — lookup table resolving the extraction-agent id carried on every extract job (high). Added as `extraction_agents`, read from `GET /api/v1/beta/extraction-agents`: the v1 listing is deprecated and unpaginated, and the beta listing returns the same agents with page tokens. The v2 `extract_jobs` rows carry a `configuration_id`, not an agent id, so the agents resolve `extraction_runs`, not extract jobs.+- [x] `GET /api/v1/extraction/runs` — run-level history (status, timings, agent) behind extraction jobs (high). Added as `extraction_runs` (fan-out over `extraction_agents`, full refresh). The extracted `data` is not imported.+- [x] `GET /api/v1/indexes` — top-level index objects; nothing in the current table set exposes them (medium). Added as `indexes`.+- ~~`GET /api/v1/pipelines/{pipeline_id}/documents/paginated`~~ — skipped: the vendor spec marks it deprecated, and each document row carries the full document text.- [ ] `GET /api/v1/pipelines/{pipeline_id}/files2` — pipeline-to-file membership join for the files table we already sync (medium)- [ ] `GET /api/v1/beta/batch-processing/{job_id}/items` — per-item rows inside a batch; batches alone give only the job header (medium)- [ ] `GET /api/v1/data-sources` — lookup resolving the data-source ids attached to pipelines (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.pyindex d1c8b1697015..78b29b6b130f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.py@@ -134,6 +134,57 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"purpose": "Purpose the file was uploaded for.",},},+ "extraction_agents": {+ "description": "LlamaExtract extraction agents, one row per agent with the schema and settings it extracts with.",+ "docs_url": "https://developers.llamaindex.ai/cloud-api-reference/",+ "columns": {+ "id": "Unique identifier for the extraction agent.",+ "name": "Name of the extraction agent.",+ "project_id": "Identifier of the LlamaCloud project the agent belongs to.",+ "data_schema": "JSON schema of the fields the agent extracts.",+ "config": "Extraction settings, such as the extraction mode, target, and models.",+ "custom_configuration": "Custom configuration preset applied to the agent, when set.",+ "created_at": "Timestamp when the extraction agent was created.",+ "updated_at": "Timestamp when the extraction agent was last updated.",+ },+ },+ "extraction_runs": {+ "description": "LlamaExtract extraction runs, one row per run of an extraction agent with its status. The extracted data is not imported.",+ "docs_url": "https://developers.llamaindex.ai/cloud-api-reference/",+ "columns": {+ "id": "Unique identifier for the extraction run.",+ "created_at": "Timestamp when the extraction run was created.",+ "updated_at": "Timestamp when the extraction run was last updated.",+ "project_id": "Identifier of the LlamaCloud project the run belongs to.",+ "extraction_agent_id": "Identifier of the extraction agent the run used.",+ "file_id": "Identifier of the file the run extracted from.",+ "job_id": "Identifier of the job that produced the run.",+ "status": "Run status: CREATED, PENDING, SUCCESS, or ERROR.",+ "error": "Error details when the run failed.",+ "from_ui": "Whether the run was started from the LlamaCloud UI.",+ "config": "Extraction settings the run used.",+ },+ },+ "indexes": {+ "description": "LlamaCloud indexes, one row per index with its source and output directories and sync state.",+ "docs_url": "https://developers.llamaindex.ai/cloud-api-reference/category/indexes",+ "columns": {+ "id": "Unique identifier for the index.",+ "created_at": "Timestamp when the index was created.",+ "updated_at": "Timestamp when the index was last updated.",+ "name": "Name of the index.",+ "description": "Description of the index.",+ "project_id": "Identifier of the LlamaCloud project the index belongs to.",+ "source_directory_id": "Identifier of the directory the index reads files from.",+ "output_directory_id": "Identifier of the directory that holds the indexed files.",+ "sync_config_id": "Identifier of the index's sync configuration.",+ "export_config_id": "Identifier of the index's export configuration.",+ "last_synced_at": "Timestamp of the last sync of the index source.",+ "last_exported_at": "Timestamp of the last export of the index.",+ "sync_in_progress": "Whether the index is syncing its source or exporting the result.",+ "metadata": "Build state and diagnostic information. Only a status of ready or failed is stable.",+ },+ },"usage_metrics": {"description": "Per-day usage aggregates with credit consumption across LlamaCloud products.","docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/usage-metrics",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.pyindex b02c6b0718ad..ad0c42751b63 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py@@ -45,9 +45,12 @@ def _project_rows(rows: list[dict[str, Any]], allowed_fields: frozenset[str]) ->return [{key: value for key, value in row.items() if key in allowed_fields} for row in rows][email protected](frozen=True)class LlamaCloudResumeConfig:- next_page_token: str+ next_page_token: str = ""+ # Fan-out endpoints resume from a parent id and a skip offset instead of a page token.+ parent_id: str | None = None+ skip: int = 0def get_base_url(region: str | None) -> str:@@ -165,6 +168,71 @@ def _resolve_organization_id(session: requests.Session, base_url: str, headers:return organization_id+def _list_parent_ids(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ parent: LlamaCloudEndpointConfig,+ resumable_source_manager: ResumableSourceManager[LlamaCloudResumeConfig],+) -> list[str]:+ params: dict[str, Any] = {"page_size": parent.page_size}+ parent_ids: list[str] = []+ while True:+ data = _fetch_page(session, f"{base_url}{parent.path}", headers, params)+ parent_ids.extend(item["id"] for item in data.get("items") or [])+ resumable_source_manager.safe_point()++ next_page_token = data.get("next_page_token")+ if not next_page_token:+ return parent_ids+ params["page_token"] = next_page_token+++def _get_fan_out_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: LlamaCloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LlamaCloudResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ assert config.parent_endpoint is not None and config.parent_id_param is not None+ parent_ids = _list_parent_ids(+ session, base_url, headers, LLAMA_CLOUD_ENDPOINTS[config.parent_endpoint], resumable_source_manager+ )++ start_index, skip = 0, 0+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.parent_id in parent_ids:+ start_index, skip = parent_ids.index(resume_config.parent_id), resume_config.skip+ logger.debug(f"LlamaCloud: resuming {config.name} from {config.parent_id_param}={resume_config.parent_id}")++ url = f"{base_url}{config.path}"+ for index in range(start_index, len(parent_ids)):+ parent_id = parent_ids[index]+ while True:+ data = _fetch_page(+ session, url, headers, {config.parent_id_param: parent_id, "skip": skip, "limit": config.page_size}+ )+ items = data.get("items") or []+ skip += len(items)+ has_more = bool(items) and skip < data.get("total", 0)++ if has_more:+ resumable_source_manager.save_state(LlamaCloudResumeConfig(parent_id=parent_id, skip=skip))+ elif index + 1 < len(parent_ids):+ resumable_source_manager.save_state(LlamaCloudResumeConfig(parent_id=parent_ids[index + 1]))++ if items:+ yield _project_rows(items, config.output_fields) if config.output_fields else items+ else:+ resumable_source_manager.safe_point()++ if not has_more:+ break+ skip = 0++def get_rows(api_key: str,region: str | None,@@ -183,6 +251,10 @@ def get_rows(# sampler observes the upstream body before row projection runs.session = make_tracked_session(capture=config.capture_http_samples)+ if config.parent_endpoint:+ yield from _get_fan_out_rows(session, base_url, headers, config, logger, resumable_source_manager)+ return+if not config.paginated:data = _fetch_page(session, url, headers, {})if data:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.pyindex e6c5b1c3e879..7a3b44b848d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py@@ -40,7 +40,7 @@ JOB_ENDPOINT_DESCRIPTION = ()-@dataclass+@dataclass(frozen=True)class LlamaCloudEndpointConfig:name: strpath: str@@ -53,6 +53,10 @@ class LlamaCloudEndpointConfig:page_size: int = DEFAULT_PAGE_SIZE# False for endpoints that return a bare JSON array with no page_token support.paginated: bool = True+ # Fan-out endpoints are listed once per row of `parent_endpoint`, passing the parent row's+ # id as `parent_id_param`, and paginate with skip/limit instead of page_token.+ parent_endpoint: str | None = None+ parent_id_param: str | None = None# /api/v1/beta/usage-metrics requires organization_id; it's resolved at sync time# from the key's project (see _resolve_organization_id).requires_organization_id: bool = False@@ -182,6 +186,40 @@ LLAMA_CLOUD_ENDPOINTS: dict[str, LlamaCloudEndpointConfig] = {}),),+ "extraction_agents": LlamaCloudEndpointConfig(+ name="extraction_agents",+ # The /api/v1/extraction/extraction-agents listing is deprecated and unpaginated; this+ # listing returns the same agents with page_token pagination. No timestamp filter.+ path="/api/v1/beta/extraction-agents",+ ),+ "extraction_runs": LlamaCloudEndpointConfig(+ name="extraction_runs",+ path="/api/v1/extraction/runs",+ parent_endpoint="extraction_agents",+ parent_id_param="extraction_agent_id",+ # Runs carry the extracted document content (`data`, `extraction_metadata`) and a nested+ # `file` object, so import only the run metadata. Sampling stays off (the fail-closed default).+ output_fields=frozenset(+ {+ "id",+ "created_at",+ "updated_at",+ "project_id",+ "extraction_agent_id",+ "file_id",+ "job_id",+ "status",+ "error",+ "from_ui",+ "config",+ }+ ),+ ),+ "indexes": LlamaCloudEndpointConfig(+ name="indexes",+ path="/api/v1/indexes",+ # The indexes listing has no timestamp filter, so full refresh only.+ ),"usage_metrics": LlamaCloudEndpointConfig(name="usage_metrics",path="/api/v1/beta/usage-metrics",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.pyindex 6e21dc69aa4f..14f1d2465772 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py@@ -66,7 +66,7 @@ class LlamaCloudSource(ResumableSource[LlamaCloudSourceConfig, LlamaCloudResumeCdocsUrl="https://posthog.com/docs/cdp/sources/llama-cloud",iconPath="/static/services/llama_cloud.svg",keywords=["llamaindex", "llamaparse", "document parsing", "rag"],- caption="""Enter a LlamaCloud API key to sync your parsing, extraction, and classification jobs, pipelines, projects, files, and usage metrics.+ caption="""Enter a LlamaCloud API key to sync your parsing, extraction, and classification jobs, extraction agents and runs, pipelines, indexes, projects, files, and usage metrics.You can create an API key in [LlamaCloud](https://cloud.llamaindex.ai) under **Settings → API Keys**. API keys are project-scoped and region-specific, so pick the region your key was created in.""",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.pyindex 87f2cf2b0afd..68a7b56b4af4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.py@@ -222,6 +222,56 @@ class TestLlamaCloudTransport:]]+ def test_get_rows_extraction_runs_fans_out_over_agents(self) -> None:+ session = FakeSession(+ [+ _page([{"id": "agent-1"}, {"id": "agent-2"}], next_page_token="agents-2"),+ _page([{"id": "agent-3"}]),+ {"items": [{"id": "run-1", "status": "SUCCESS", "data": {"total": 42}}], "total": 2},+ {"items": [{"id": "run-2", "status": "ERROR", "extraction_metadata": {"x": 1}}], "total": 2},+ {"items": [], "total": 0},+ {"items": [{"id": "run-3", "status": "PENDING", "file": {"name": "doc.pdf"}}], "total": 1},+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "na", "extraction_runs", MagicMock(), manager))++ assert batches == [+ [{"id": "run-1", "status": "SUCCESS"}],+ [{"id": "run-2", "status": "ERROR"}],+ [{"id": "run-3", "status": "PENDING"}],+ ]+ assert session.calls[0][0] == "https://api.cloud.llamaindex.ai/api/v1/beta/extraction-agents"+ assert session.calls[1][1]["page_token"] == "agents-2"+ assert [params for _, params in session.calls[2:]] == [+ {"extraction_agent_id": "agent-1", "skip": 0, "limit": 100},+ {"extraction_agent_id": "agent-1", "skip": 1, "limit": 100},+ {"extraction_agent_id": "agent-2", "skip": 0, "limit": 100},+ {"extraction_agent_id": "agent-3", "skip": 0, "limit": 100},+ ]+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ LlamaCloudResumeConfig(parent_id="agent-1", skip=1),+ LlamaCloudResumeConfig(parent_id="agent-2"),+ LlamaCloudResumeConfig(parent_id="agent-3"),+ ]++ def test_get_rows_extraction_runs_resumes_from_saved_agent_and_skip(self) -> None:+ session = FakeSession(+ [+ _page([{"id": "agent-1"}, {"id": "agent-2"}]),+ {"items": [{"id": "run-5"}], "total": 6},+ ]+ )+ manager = _make_manager(resume_state=LlamaCloudResumeConfig(parent_id="agent-2", skip=5))++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "na", "extraction_runs", MagicMock(), manager))++ assert batches == [[{"id": "run-5"}]]+ assert session.calls[1][1] == {"extraction_agent_id": "agent-2", "skip": 5, "limit": 100}+@parameterized.expand([(429,), (500,), (503,)])def test_fetch_page_raises_retryable_error(self, status_code: int) -> None:session = MagicMock()