: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): implement together_ai import source (#69608)
Tom Owersa01c35c01ee9
diff --git a/frontend/public/services/together_ai.png b/frontend/public/services/together_ai.pngnew file mode 100644index 000000000000..0c305c381010Binary files /dev/null and b/frontend/public/services/together_ai.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 13e1fbca5905..78e7ac513be8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -376,6 +376,7 @@ the row lists both.| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || tmdb | HTTP | requests | ✅ || todoist | HTTP | requests | ✅ |+| together_ai | HTTP | requests | ✅ || trello | HTTP | requests | ✅ || tremendous | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ |@@ -806,7 +807,6 @@ doesn't conflict with concurrent PRs.- tile38- timely- tinyemail-- together_ai- toggl- track_pms- tremendousdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 4628d6f43336..c62ee0172661 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@@ -3765,7 +3765,7 @@ class TodoistSourceConfig(config.Config):@config.configclass TogetherAISourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/canonical_descriptions.pynew file mode 100644index 000000000000..7a951da84de9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/canonical_descriptions.py@@ -0,0 +1,109 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "fine_tunes": {+ "description": "A fine-tuning job: the base model, training data, hyperparameters, progress counters, and price of each fine-tune run on Together AI.",+ "docs_url": "https://docs.together.ai/reference/get-fine-tunes",+ "columns": {+ "id": "Unique identifier for the fine-tuning job (prefixed ft-).",+ "training_file": "ID of the uploaded file used as training data.",+ "validation_file": "ID of the uploaded file used as validation data.",+ "model": "Name of the base model being fine-tuned.",+ "model_output_name": "Name of the resulting fine-tuned model.",+ "n_epochs": "Number of training epochs requested.",+ "n_checkpoints": "Number of intermediate checkpoints to save during training.",+ "n_evals": "Number of evaluation loops to run against the validation set.",+ "batch_size": "Training batch size.",+ "learning_rate": "Learning rate used for training.",+ "training_type": "Training method configuration (full fine-tuning or LoRA).",+ "status": "Current job status (e.g. pending, queued, running, completed, cancelled, error).",+ "created_at": "Timestamp when the job was created.",+ "updated_at": "Timestamp when the job was last updated.",+ "token_count": "Number of tokens in the training dataset.",+ "total_price": "Total price of the fine-tuning job.",+ "total_steps": "Total number of training steps.",+ "steps_completed": "Number of training steps completed so far.",+ "epochs_completed": "Number of epochs completed so far.",+ "events": "Lifecycle events recorded for the job (submission, start, checkpoints, completion).",+ "wandb_url": "Weights & Biases run URL when W&B tracking is enabled.",+ },+ },+ "batches": {+ "description": "A batch inference job: asynchronous bulk processing of requests from an uploaded input file against a model, with progress and output file references.",+ "docs_url": "https://docs.together.ai/reference/batch-list",+ "columns": {+ "id": "Unique identifier for the batch job.",+ "user_id": "ID of the user who created the batch job.",+ "input_file_id": "ID of the uploaded file containing the batch requests.",+ "output_file_id": "ID of the file containing successful results once the job completes.",+ "error_file_id": "ID of the file containing errors for failed requests.",+ "endpoint": "API endpoint the batch requests are executed against (e.g. /v1/chat/completions).",+ "status": "Current job status (e.g. VALIDATING, IN_PROGRESS, COMPLETED, FAILED, EXPIRED, CANCELLED).",+ "progress": "Completion progress of the batch job as a percentage.",+ "model_id": "Model the batch requests are executed against.",+ "file_size_bytes": "Size of the input file in bytes.",+ "job_deadline": "Deadline by which the batch job must complete.",+ "created_at": "Timestamp when the batch job was created.",+ "completed_at": "Timestamp when the batch job completed.",+ },+ },+ "files": {+ "description": "Files uploaded to Together AI, used as training data for fine-tuning or as inputs/outputs of batch inference jobs.",+ "docs_url": "https://docs.together.ai/reference/get-files",+ "columns": {+ "id": "Unique identifier for the file (prefixed file-).",+ "object": "Object type, always 'file'.",+ "filename": "Name of the uploaded file.",+ "purpose": "Purpose of the file (e.g. fine-tune, batch-api).",+ "type": "File format (e.g. jsonl, parquet).",+ "bytes": "Size of the file in bytes.",+ "line_count": "Number of lines in the file, for JSONL files.",+ "created_at": "Unix timestamp when the file was uploaded.",+ },+ },+ "endpoints": {+ "description": "Dedicated model endpoints deployed by the account: the model, hardware configuration, autoscaling settings, and current state of each deployment.",+ "docs_url": "https://docs.together.ai/reference/listendpoints",+ "columns": {+ "id": "Unique identifier for the endpoint (prefixed endpoint-).",+ "object": "Object type, always 'endpoint'.",+ "name": "System name for the endpoint, used to route inference requests.",+ "model": "Model deployed on this endpoint.",+ "type": "Endpoint type (dedicated).",+ "owner": "Owner of the endpoint.",+ "state": "Current state of the endpoint (e.g. PENDING, STARTING, STARTED, STOPPING, STOPPED, FAILED).",+ "created_at": "Timestamp when the endpoint was created.",+ },+ },+ "evaluations": {+ "description": "Model evaluation jobs: classify, score, or compare runs that judge model outputs, with their parameters and aggregate results.",+ "docs_url": "https://docs.together.ai/reference/list-evaluations",+ "columns": {+ "workflow_id": "Unique identifier for the evaluation job.",+ "type": "Evaluation type (classify, score, or compare).",+ "status": "Current status of the evaluation job.",+ "parameters": "Configuration of the evaluation run (models, judge, prompts, input data).",+ "results": "Aggregate results of the evaluation once complete.",+ "created_at": "Timestamp when the evaluation job was created.",+ "updated_at": "Timestamp when the evaluation job was last updated.",+ },+ },+ "models": {+ "description": "The Together AI model catalog: every serverless model available to the account, with type, context length, and per-token pricing.",+ "docs_url": "https://docs.together.ai/reference/models",+ "columns": {+ "id": "Unique model identifier, e.g. meta-llama/Llama-3.3-70B-Instruct-Turbo.",+ "object": "Object type, always 'model'.",+ "created": "Unix timestamp when the model was added.",+ "type": "Model type (e.g. chat, language, image, embedding, rerank, moderation).",+ "display_name": "Human-readable model name.",+ "organization": "Organization that created the model.",+ "license": "License the model is distributed under.",+ "context_length": "Maximum context window size in tokens.",+ "pricing": "Per-token pricing for the model (input, output, hourly rates).",+ "link": "Link to the model resource.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/settings.pynew file mode 100644index 000000000000..2af0015c9fb9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/settings.py@@ -0,0 +1,38 @@+from dataclasses import dataclass, field++# Together AI platform API (https://docs.together.ai/reference). Every list endpoint is a single+# GET under https://api.together.xyz/v1 that returns the whole collection in one response — no+# pagination parameters and no server-side timestamp filters are documented (verified against the+# official Python SDK, which reads each list in one request). That means every table is full+# refresh only; collections are small per account, so a full fetch is cheap.+#+# Response envelopes vary per endpoint: fine-tunes/files/endpoints wrap rows in {"data": [...]},+# while batches/evaluations/models return a bare JSON array. The transport handles both shapes.+++@dataclass+class TogetherAIEndpointConfig:+ name: str+ # Path under the API root, e.g. "/fine-tunes".+ path: str+ # Field to partition Delta files by. Must be a STABLE field (created timestamp, never updated_at).+ partition_key: str = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Static query params sent with the request.+ params: dict[str, str] = field(default_factory=dict)+++TOGETHER_AI_ENDPOINTS: dict[str, TogetherAIEndpointConfig] = {+ "fine_tunes": TogetherAIEndpointConfig(name="fine_tunes", path="/fine-tunes"),+ "batches": TogetherAIEndpointConfig(name="batches", path="/batches"),+ "files": TogetherAIEndpointConfig(name="files", path="/files"),+ # Only the account's dedicated endpoint deployments — the unfiltered list also includes every+ # public serverless model, which duplicates the models table.+ "endpoints": TogetherAIEndpointConfig(name="endpoints", path="/endpoints", params={"type": "dedicated"}),+ "evaluations": TogetherAIEndpointConfig(name="evaluations", path="/evaluations", primary_keys=["workflow_id"]),+ # The serverless model catalog: id, type, pricing, context length per model. Rows carry a+ # `created` unix timestamp instead of `created_at`.+ "models": TogetherAIEndpointConfig(name="models", path="/models", partition_key="created"),+}++ENDPOINTS = tuple(TOGETHER_AI_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/source.pyindex 9b906e7f50a3..e48168832870 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/source.py@@ -1,19 +1,40 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TogetherAISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.settings import (+ ENDPOINTS,+ TOGETHER_AI_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.together_ai import (+ get_status_code,+ together_ai_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass TogetherAISource(SimpleSource[TogetherAISourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TOGETHERAI@@ -24,8 +45,92 @@ class TogetherAISource(SimpleSource[TogetherAISourceConfig]):name=SchemaExternalDataSourceType.TOGETHER_AI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Together AI",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Together AI API key to sync your fine-tuning jobs, batch inference jobs, files, dedicated endpoints, evaluations, and the model catalog into the PostHog Data warehouse.++You can find or create an API key in your [Together AI settings](https://api.together.xyz/settings/api-keys).""",iconPath="/static/services/together_ai.png",- keywords=["ai", "llm", "inference", "fine-tuning"],- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/together-ai",+ keywords=["together", "ai", "llm", "inference", "fine-tuning"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid/revoked key surfaces as a requests HTTPError from `raise_for_status()`.+ # Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.together.xyz": "Your Together AI API key is invalid or has been revoked. Create a new API key in your Together AI settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.together.xyz": "Your Together AI API key does not have permission to access this data. Check the key in your Together AI settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: TogetherAISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Together's list endpoints return the whole collection in one response with no pagination+ # and no server-side timestamp filters (see settings.py), so every table is full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=TOGETHER_AI_ENDPOINTS[endpoint].primary_keys,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: TogetherAISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ status = get_status_code(config.api_key, schema_name)+ except Exception:+ return False, "Could not reach the Together AI API. Check your network connection and try again."++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Together AI API key. Check the key in your Together AI settings, then reconnect."+ if status == 403:+ # Accept a valid-but-restricted key at source-create so the user can still sync the+ # tables the key can reach; only fail the per-schema check.+ if schema_name is None:+ return True, None+ return False, f"Your Together AI API key does not have permission to sync '{schema_name}'."+ return False, f"Unexpected response from the Together AI API (status {status})."++ def source_for_pipeline(self, config: TogetherAISourceConfig, inputs: SourceInputs) -> SourceResponse:+ return together_ai_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai.pynew file mode 100644index 000000000000..9b4fa18db146--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai.py@@ -0,0 +1,211 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai import together_ai+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.settings import TOGETHER_AI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.together_ai import (+ TOGETHER_AI_BASE_URL,+ _extract_rows,+ get_rows,+ get_status_code,+ together_ai_source,+)+++def _collect(monkeypatch: Any, endpoint: str, payload: Any) -> tuple[list[dict], list[dict[str, Any]]]:+ """Feed `payload` from _fetch and return (flattened rows, recorded fetch calls)."""+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, params: Any, headers: dict[str, str], logger: Any) -> Any:+ calls.append({"url": url, "params": params, "headers": headers})+ return payload++ monkeypatch.setattr(together_ai, "_fetch", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(api_key="together_test", endpoint=endpoint, logger=MagicMock()):+ # get_rows yields the collection as a list[dict]; the pipeline batches internally.+ rows.extend(batch)+ return rows, calls+++class TestExtractRows:+ @parameterized.expand(+ [+ ("wrapped_envelope", {"data": [{"id": "ft-1"}, {"id": "ft-2"}]}, [{"id": "ft-1"}, {"id": "ft-2"}]),+ ("bare_array", [{"id": "batch-1"}], [{"id": "batch-1"}]),+ ("empty_envelope", {"data": []}, []),+ ("empty_array", [], []),+ ("non_dict_rows_dropped", ["not-a-row", {"id": "ft-1"}], [{"id": "ft-1"}]),+ ]+ )+ def test_unwraps_both_response_shapes(self, _name: str, payload: Any, expected: list[dict]) -> None:+ assert _extract_rows(payload, "fine_tunes") == expected++ @parameterized.expand(+ [+ ("string_body", "error"),+ ("null_body", None),+ ("dict_without_data_list", {"data": "oops"}),+ ("plain_object", {"id": "ft-1"}),+ ]+ )+ def test_unexpected_shape_raises(self, _name: str, payload: Any) -> None:+ # A silently-swallowed shape change would sync an empty table and look like data loss.+ with pytest.raises(ValueError):+ _extract_rows(payload, "fine_tunes")+++class TestGetRows:+ def test_yields_rows_from_wrapped_endpoint(self, monkeypatch: Any) -> None:+ rows, calls = _collect(monkeypatch, "fine_tunes", {"data": [{"id": "ft-1"}]})+ assert rows == [{"id": "ft-1"}]+ assert calls[0]["url"] == f"{TOGETHER_AI_BASE_URL}/fine-tunes"+ assert calls[0]["headers"]["Authorization"] == "Bearer together_test"++ def test_yields_rows_from_bare_array_endpoint(self, monkeypatch: Any) -> None:+ rows, calls = _collect(monkeypatch, "batches", [{"id": "batch-1"}, {"id": "batch-2"}])+ assert rows == [{"id": "batch-1"}, {"id": "batch-2"}]+ assert calls[0]["url"] == f"{TOGETHER_AI_BASE_URL}/batches"++ def test_endpoints_table_only_requests_dedicated_deployments(self, monkeypatch: Any) -> None:+ # Without the filter the response also contains every public serverless model,+ # flooding the table with rows that duplicate the models catalog.+ _rows, calls = _collect(monkeypatch, "endpoints", {"data": []})+ assert calls[0]["params"] == {"type": "dedicated"}++ def test_top_level_endpoints_send_no_params(self, monkeypatch: Any) -> None:+ _rows, calls = _collect(monkeypatch, "models", [])+ assert calls[0]["params"] is None++ def test_empty_collection_yields_no_batches(self, monkeypatch: Any) -> None:+ rows, _calls = _collect(monkeypatch, "files", {"data": []})+ assert rows == []+++class TestFetchRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),+ ]+ )+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ retryable = MagicMock()+ retryable.status_code = status_code+ retryable.ok = False++ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"data": []}++ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(together_ai._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = together_ai._fetch(session, f"{TOGETHER_AI_BASE_URL}/x", None, {}, MagicMock())++ assert result == {"data": []}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("chunked_encoding", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ]+ )+ def test_transient_transport_errors_are_retried(self, _name: str, transient_error: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = []++ session = MagicMock()+ session.get.side_effect = [transient_error, good]++ with patch.object(together_ai._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = together_ai._fetch(session, f"{TOGETHER_AI_BASE_URL}/x", None, {}, MagicMock())++ assert result == []+ assert session.get.call_count == 2++ def test_client_error_raises_immediately(self) -> None:+ unauthorized = MagicMock()+ unauthorized.status_code = 401+ unauthorized.ok = False+ unauthorized.reason = "Unauthorized"+ unauthorized.url = f"{TOGETHER_AI_BASE_URL}/x?type=dedicated"++ session = MagicMock()+ session.get.return_value = unauthorized++ with pytest.raises(requests.HTTPError) as exc_info:+ together_ai._fetch(session, f"{TOGETHER_AI_BASE_URL}/x", None, {}, MagicMock())++ # The rebuilt error must not leak the query string or response body into stored error state.+ message = str(exc_info.value)+ assert "401 Client Error: Unauthorized" in message+ assert "?type=dedicated" not in message+ assert session.get.call_count == 1+++class TestGetStatusCode:+ def test_default_probe_hits_files_with_bearer_auth(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(together_ai, "make_tracked_session", return_value=session):+ status = get_status_code("together_test")++ assert status == 200+ args, kwargs = session.get.call_args+ assert args[0] == f"{TOGETHER_AI_BASE_URL}/files"+ assert kwargs["headers"]["Authorization"] == "Bearer together_test"++ def test_schema_probe_hits_that_endpoint_with_its_params(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(together_ai, "make_tracked_session", return_value=session):+ get_status_code("together_test", "endpoints")++ args, kwargs = session.get.call_args+ assert args[0] == f"{TOGETHER_AI_BASE_URL}/endpoints"+ assert kwargs["params"] == {"type": "dedicated"}++ def test_unknown_schema_falls_back_to_files_probe(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(together_ai, "make_tracked_session", return_value=session):+ get_status_code("together_test", "not_a_table")++ args, _kwargs = session.get.call_args+ assert args[0] == f"{TOGETHER_AI_BASE_URL}/files"+++class TestTogetherAISourceResponse:+ @parameterized.expand(list(TOGETHER_AI_ENDPOINTS.keys()))+ def test_source_response_uses_endpoint_primary_keys_and_stable_partition(self, endpoint: str) -> None:+ response = together_ai_source(api_key="together_test", endpoint=endpoint, logger=MagicMock())+ cfg = TOGETHER_AI_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == cfg.primary_keys+ # Partition on the stable creation timestamp — never updated_at — so partitions+ # don't rewrite on every sync.+ assert response.partition_keys == [cfg.partition_key]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai_source.pynew file mode 100644index 000000000000..799cb31822ae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/tests/test_together_ai_source.py@@ -0,0 +1,140 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.settings import (+ ENDPOINTS,+ TOGETHER_AI_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.source import TogetherAISource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "together_test") -> Any:+ return source_module.TogetherAISourceConfig(api_key=api_key)+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert TogetherAISource().source_type == ExternalDataSourceType.TOGETHERAI++ def test_config_declares_secret_api_key_field(self) -> None:+ fields = TogetherAISource().get_source_config.fields+ assert [f.name for f in fields] == ["api_key"]+ api_key_field = fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required so the public docs render the table list.+ assert TogetherAISource.lists_tables_without_credentials is True+++class TestGetSchemas:+ def test_returns_all_endpoints_full_refresh_only(self) -> None:+ schemas = TogetherAISource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # No pagination and no server-side timestamp filters, so nothing advertises incremental/append.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)++ def test_names_filter_restricts_output(self) -> None:+ schemas = TogetherAISource().get_schemas(_config(), team_id=1, names=["fine_tunes"])+ assert [s.name for s in schemas] == ["fine_tunes"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = TogetherAISource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ evaluations = next(t for t in tables if t["name"] == "evaluations")+ assert evaluations["primary_keys"] == ["workflow_id"]+ assert "Full refresh" in evaluations["sync_methods"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("forbidden_at_create_is_accepted", 403, None, True),+ ("forbidden_for_schema_is_rejected", 403, "fine_tunes", False),+ ("unexpected", 500, None, False),+ ]+ )+ def test_status_code_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch.object(source_module, "get_status_code", return_value=status):+ ok, _err = TogetherAISource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok++ def test_probes_requested_schema_endpoint(self) -> None:+ with patch.object(source_module, "get_status_code", return_value=200) as mock_probe:+ TogetherAISource().validate_credentials(_config(), team_id=1, schema_name="batches")+ assert mock_probe.call_args.args == ("together_test", "batches")++ def test_transport_failure_returns_actionable_error(self) -> None:+ with patch.object(source_module, "get_status_code", side_effect=Exception("boom")):+ ok, err = TogetherAISource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert err is not None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.together.xyz/v1/fine-tunes",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.together.xyz/v1/endpoints?type=dedicated",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = TogetherAISource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.together.xyz/v1/models",+ ),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.together.xyz/v1/batches",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='api.together.xyz', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_stay_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = TogetherAISource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestSourceForPipeline:+ def test_plumbs_config_and_schema_through(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "fine_tunes"+ with patch.object(source_module, "together_ai_source") as mock_source:+ TogetherAISource().source_for_pipeline(_config(api_key="together_k"), inputs)+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "together_k"+ assert kwargs["endpoint"] == "fine_tunes"+++class TestCanonicalDescriptions:+ def test_every_endpoint_has_a_canonical_description(self) -> None:+ descriptions = TogetherAISource().get_canonical_descriptions()+ for endpoint in TOGETHER_AI_ENDPOINTS:+ assert endpoint in descriptions+ entry = descriptions[endpoint]+ # Primary key columns must be documented so enrichment doesn't fall back to the LLM for them.+ for pk in TOGETHER_AI_ENDPOINTS[endpoint].primary_keys:+ assert pk in entry["columns"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/together_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/together_ai.pynew file mode 100644index 000000000000..5f35fac8f57f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/together_ai/together_ai.py@@ -0,0 +1,131 @@+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.together_ai.settings import TOGETHER_AI_ENDPOINTS++TOGETHER_AI_BASE_URL = "https://api.together.xyz/v1"+++class TogetherAIRetryableError(Exception):+ pass+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type(+ (+ TogetherAIRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: dict[str, str] | None,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Any:+ response = session.get(url, params=params, headers=headers, timeout=60)++ # 429 (rate limit) and 5xx are transient — retry with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise TogetherAIRetryableError(f"Together AI API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Never log response.text or the raw URL: the error body can echo account content and the+ # query string could carry request metadata. Log only status plus scheme/host/path.+ safe = urlsplit(response.url)+ safe_url = f"{safe.scheme}://{safe.netloc}{safe.path}"+ logger.error("Together AI API error", status=response.status_code, url=safe_url)+ # raise_for_status() would embed the full request URL in the exception, which is surfaced as+ # the schema's latest_error. Rebuild the error from scheme/host/path only so no request params+ # or response body reach stored error state. The "<status> Client Error: <reason> for url:+ # https://api.together.xyz" prefix stays stable for get_non_retryable_errors() matching.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}",+ response=response,+ )++ return response.json()+++def _extract_rows(payload: Any, endpoint: str) -> list[dict[str, Any]]:+ """Unwrap a list response body.++ Together's list endpoints are inconsistent: fine-tunes/files/endpoints wrap rows in+ {"data": [...]}, batches/evaluations/models return a bare array. Accept both so an+ envelope change on their side doesn't break the sync.+ """+ if isinstance(payload, list):+ rows = payload+ elif isinstance(payload, dict) and isinstance(payload.get("data"), list):+ rows = payload["data"]+ else:+ raise ValueError(f"Unexpected Together AI response shape for endpoint '{endpoint}': {type(payload).__name__}")++ return [row for row in rows if isinstance(row, dict)]+++def get_rows(api_key: str, endpoint: str, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = TOGETHER_AI_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_key,))++ url = f"{TOGETHER_AI_BASE_URL}{endpoint_config.path}"+ payload = _fetch(session, url, endpoint_config.params or None, _get_headers(api_key), logger)++ rows = _extract_rows(payload, endpoint)+ logger.debug("Together AI: fetched rows", count=len(rows), endpoint=endpoint)+ if rows:+ yield rows+++def together_ai_source(api_key: str, endpoint: str, logger: FilteringBoundLogger) -> SourceResponse:+ endpoint_config = TOGETHER_AI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ )+++def get_status_code(api_key: str, endpoint: str | None = None) -> int:+ """Cheap probe used by credential validation. Returns the HTTP status code."""+ if endpoint is not None and endpoint in TOGETHER_AI_ENDPOINTS:+ endpoint_config = TOGETHER_AI_ENDPOINTS[endpoint]+ path = endpoint_config.path+ params: dict[str, str] | None = endpoint_config.params or None+ else:+ # Files is account-scoped and small — a cheap token check.+ path = "/files"+ params = None++ url = f"{TOGETHER_AI_BASE_URL}{path}"+ response = make_tracked_session(redact_values=(api_key,)).get(+ url, params=params, headers=_get_headers(api_key), timeout=10+ )+ return response.status_code