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(llma): custom parsing recipes for trace normalization (#61698)

Carlos Marchal81db546127a2
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index a0b523285dfd..e3e5a37f493c 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -175,6 +175,7 @@ rules:
|NotificationEvent
|Notebook
|ObjectMediaPreview
+ |ParserRecipe
|PluginConfig
|ProductTour
|ProjectSecretAPIKey
@@ -405,6 +406,7 @@ rules:
|NotificationEvent
|Notebook
|ObjectMediaPreview
+ |ParserRecipe
|PluginConfig
|ProductTour
|ProjectSecretAPIKey
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index b99ae0d3521b..1d73bd89654e 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -1,5 +1,6 @@
import { LemonBanner, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { LLMProviderKeysSettings } from '@posthog/products-ai-observability/frontend/settings/LLMProviderKeysSettings'
+import { ParserRecipesSettings } from '@posthog/products-ai-observability/frontend/settings/ParserRecipesSettings'
import { ErrorTrackingAlerting } from '@posthog/products-error-tracking/frontend/scenes/ErrorTrackingConfigurationScene/alerting/ErrorTrackingAlerting'
import { AssignmentRules } from '@posthog/products-error-tracking/frontend/scenes/ErrorTrackingConfigurationScene/assignment_rules/AssignmentRules'
import { GroupingRules } from '@posthog/products-error-tracking/frontend/scenes/ErrorTrackingConfigurationScene/grouping_rules/GroupingRules'
@@ -354,6 +355,15 @@ export const SETTINGS_MAP: SettingSection[] = [
docsUrl: 'https://posthog.com/docs/ai-evals/evaluations',
keywords: ['llm', 'provider', 'api key', 'openai', 'anthropic', 'gemini', 'playground'],
},
+ {
+ id: 'ai-observability-parser-recipes',
+ title: 'Custom parsing',
+ description:
+ "Add recipes that normalize provider message shapes the built-in recipes don't cover. They apply when rendering traces.",
+ component: <ParserRecipesSettings />,
+ flag: 'LLM_ANALYTICS_RECIPE_NORMALIZER',
+ keywords: ['parser', 'recipe', 'normalize', 'trace', 'provider', 'custom parsing', 'content'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 550c73f6d059..171c5f9f1345 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -91,6 +91,7 @@ export type SettingId =
| 'activity-log-org-level-settings'
| 'activity-log-settings'
| 'ai-observability-byok'
+ | 'ai-observability-parser-recipes'
| 'allow-impersonation'
| 'approval-policies'
| 'authentication-domains'
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 25c661943154..4a0253a7f245 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -9,6 +9,7 @@ from .evaluation_summary import LLMEvaluationSummaryViewSet
from .evaluations import EvaluationViewSet
from .models import LLMModelsViewSet
from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
+from .parser_recipes import ParserRecipeViewSet
from .personal_spend import PersonalSpendViewSet
from .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSet
from .proxy import SUPPORTED_MODELS_WITH_THINKING, LLMProxyViewSet
@@ -48,4 +49,5 @@ __all__ = [
"PersonalSpendViewSet",
"TaggerViewSet",
"TraceReviewViewSet",
+ "ParserRecipeViewSet",
]
diff --git a/products/ai_observability/backend/api/parser_recipes.py b/products/ai_observability/backend/api/parser_recipes.py
new file mode 100644
index 000000000000..4a4b0dfee5ce
--- /dev/null
+++ b/products/ai_observability/backend/api/parser_recipes.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from typing import cast
+
+from django.db.models import QuerySet
+
+from rest_framework import serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.models import User
+from posthog.permissions import AccessControlPermission
+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+
+from products.ai_observability.backend.models.parser_recipe import ParserRecipe
+
+
+class ParserRecipeSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="User who created the recipe.",
+ )
+
+ class Meta:
+ model = ParserRecipe
+ fields = [
+ "id",
+ "name",
+ "source",
+ "created_by",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = ["id", "created_by", "created_at", "updated_at"]
+ extra_kwargs = {
+ "name": {"help_text": "Human-readable recipe name shown in the editor."},
+ "source": {
+ # Preserve the YAML verbatim
+ "trim_whitespace": False,
+ "help_text": "Raw YAML recipe source, compiled and validated client-side.",
+ },
+ }
+
+
+class ParserRecipeViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ viewsets.ModelViewSet,
+):
+ scope_object = "llm_analytics"
+ permission_classes = [IsAuthenticated, AccessControlPermission]
+ serializer_class = ParserRecipeSerializer
+ # Fail-closed manager raises if `.all()` runs at import; the real per-request
+ # scoping happens in safely_get_queryset.
+ queryset = ParserRecipe.objects.unscoped()
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
+
+ def safely_get_queryset(self, queryset: QuerySet[ParserRecipe]) -> QuerySet[ParserRecipe]:
+ return ParserRecipe.objects.for_team(self.team_id).select_related("created_by").order_by("created_at", "id")
+
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
+ serializer.save(team=self.team, created_by=cast(User, self.request.user))
diff --git a/products/ai_observability/backend/api/test/test_parser_recipes.py b/products/ai_observability/backend/api/test/test_parser_recipes.py
new file mode 100644
index 000000000000..532cf49e1268
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_parser_recipes.py
@@ -0,0 +1,84 @@
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership, Project, Team, User
+
+from products.ai_observability.backend.models.parser_recipe import ParserRecipe
+
+VALID_SOURCE = "id: my_recipe\nrules: []\n"
+
+
+class TestParserRecipesApi(APIBaseTest):
+ def _endpoint(self) -> str:
+ return f"/api/projects/{self.team.id}/llm_analytics/parser_recipes/"
+
+ def test_non_admin_member_can_write(self):
+ # Managing recipes is intentionally not admin-only — a plain member can create.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(self._endpoint(), {"name": "Member recipe", "source": VALID_SOURCE})
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ def test_create_persists_recipe_and_sets_created_by(self):
+ response = self.client.post(self._endpoint(), {"name": "My recipe", "source": VALID_SOURCE})
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ data = response.json()
+ self.assertEqual(data["name"], "My recipe")
+ self.assertEqual(data["source"], VALID_SOURCE)
+ self.assertEqual(data["created_by"]["id"], self.user.id)
+
+ recipe = ParserRecipe.objects.for_team(self.team.id).get(id=data["id"])
+ self.assertEqual(recipe.team_id, self.team.id)
+
+ def test_list_returns_only_this_teams_recipes(self):
+ ParserRecipe.objects.unscoped().create(team=self.team, name="mine", source=VALID_SOURCE)
+ other_team = self._other_team()
+ ParserRecipe.objects.unscoped().create(team=other_team, name="theirs", source=VALID_SOURCE)
+
+ response = self.client.get(self._endpoint())
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ names = [row["name"] for row in response.json()["results"]]
+ self.assertEqual(names, ["mine"])
+
+ def test_cannot_retrieve_another_teams_recipe(self):
+ other_team = self._other_team()
+ other_recipe = ParserRecipe.objects.unscoped().create(team=other_team, name="theirs", source=VALID_SOURCE)
+
+ response = self.client.get(f"{self._endpoint()}{other_recipe.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_patch_updates_name_and_source(self):
+ recipe = ParserRecipe.objects.unscoped().create(team=self.team, name="old", source=VALID_SOURCE)
+ new_source = "id: changed\nrules: []\n"
+
+ response = self.client.patch(
+ f"{self._endpoint()}{recipe.id}/", {"name": "new", "source": new_source}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ recipe.refresh_from_db()
+ self.assertEqual(recipe.name, "new")
+ self.assertEqual(recipe.source, new_source)
+
+ def test_delete_removes_recipe(self):
+ recipe = ParserRecipe.objects.unscoped().create(team=self.team, name="doomed", source=VALID_SOURCE)
+
+ response = self.client.delete(f"{self._endpoint()}{recipe.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(ParserRecipe.objects.for_team(self.team.id).filter(id=recipe.id).exists())
+
+ def _other_team(self) -> Team:
+ org = Organization.objects.create(name="other")
+ project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=org)
+ team = Team.objects.create(id=project.id, project=project, organization=org, api_token=str(uuid4()))
+ User.objects.create_and_join(org, "[email protected]", "testpassword123")
+ return team
diff --git a/products/ai_observability/backend/migrations/0004_parserrecipe.py b/products/ai_observability/backend/migrations/0004_parserrecipe.py
new file mode 100644
index 000000000000..2cf3139030d2
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0004_parserrecipe.py
@@ -0,0 +1,52 @@
+# Generated by Django 5.2.14 on 2026-06-04 12:27
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0003_normalize_evaluation_conditions"),
+ ("posthog", "1207_migrate_ai_observability_models"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ParserRecipe",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("source", models.TextField()),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index e5f46d276434..2763f38a008a 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_normalize_evaluation_conditions
+0004_parserrecipe
diff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.py
index 324758bf24e7..8cfd844f4f9b 100644
--- a/products/ai_observability/backend/models/__init__.py
+++ b/products/ai_observability/backend/models/__init__.py
@@ -7,6 +7,7 @@ from .evaluations import Evaluation
from .llm_prompt import LLMPrompt
from .llm_traces_summaries import LLMTraceSummary
from .model_configuration import LLMModelConfiguration
+from .parser_recipe import ParserRecipe
from .provider_keys import LLMProvider, LLMProviderKey
from .review_queues import ReviewQueue, ReviewQueueItem
from .score_definitions import ScoreDefinition, ScoreDefinitionVersion
@@ -25,6 +26,7 @@ __all__ = [
"DatasetItem",
"LLMModelConfiguration",
"LLMPrompt",
+ "ParserRecipe",
"LLMProvider",
"LLMProviderKey",
"LLMTraceSummary",
diff --git a/products/ai_observability/backend/models/parser_recipe.py b/products/ai_observability/backend/models/parser_recipe.py
new file mode 100644
index 000000000000..81b919205e1c
--- /dev/null
+++ b/products/ai_observability/backend/models/parser_recipe.py
@@ -0,0 +1,19 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+
+class ParserRecipe(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
+ """A team's net-new custom recipe for the message normalizer.
+
+ Content-only storage. Custom recipes run before the builtin catch-all in the
+ trace view; the frontend owns the merge against its bundled defaults.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ name = models.CharField(max_length=255)
+ source = models.TextField()
+
+ def __str__(self) -> str:
+ return self.name
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index 5be76d1ca972..3d3f47b1de79 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -21,6 +21,7 @@ from products.ai_observability.backend.api import (
LLMProviderKeyValidationViewSet,
LLMProviderKeyViewSet,
LLMProxyViewSet,
+ ParserRecipeViewSet,
PersonalSpendViewSet,
ReviewQueueItemViewSet,
ReviewQueueViewSet,
@@ -38,6 +39,9 @@ def register_routes(routers: RouterRegistry) -> None:
if CLOUD_DEPLOYMENT == "US" or DEBUG or TEST:
routers.root.register(r"llm_analytics/@me/spend", PersonalSpendViewSet, "personal_spend")
+ routers.projects.register(
+ r"llm_analytics/parser_recipes", ParserRecipeViewSet, "project_llm_analytics_parser_recipes", ["team_id"]
+ )
routers.register_legacy_dual_route(r"llm_skills", LLMSkillViewSet, "project_llm_skills", ["team_id"])
routers.register_legacy_dual_route(r"datasets", DatasetViewSet, "environment_datasets", ["team_id"])
routers.register_legacy_dual_route(r"dataset_items", DatasetItemViewSet, "environment_dataset_items", ["team_id"])
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 0b1dff939ee1..62b9c4064247 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -20,6 +20,7 @@ import { AnyPropertyFilter, Breadcrumb } from '~/types'
import type { aiObservabilitySharedLogicType } from './aiObservabilitySharedLogicType'
import { AI_OBSERVABILITY_CLUSTER_URL_PATTERN } from './clusters/constants'
+import { parserRecipesLogic } from './settings/parserRecipesLogic'
export const AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID = 'ai-observability-data'
@@ -110,6 +111,9 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
`${props?.personId || 'aiObservabilityScene'}::${props?.tabId || ''}`
),
connect(() => ({
+ // Mount the parser-recipe logic so a team's custom recipes reach the trace-rendering
+ // normalizer on any AI observability page, not just the settings scene.
+ logic: [parserRecipesLogic],
values: [
sceneLogic,
['sceneKey'],
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 04ad4654aa0a..dde5d5086a2d 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1139,6 +1139,47 @@ export interface OfflineExperimentItemsResponseApi {
results: unknown[][]
}
+export interface ParserRecipeApi {
+ readonly id: string
+ /**
+ * Human-readable recipe name shown in the editor.
+ * @maxLength 255
+ */
+ name: string
+ /** Raw YAML recipe source, compiled and validated client-side. */
+ source: string
+ /** User who created the recipe. */
+ readonly created_by: UserBasicApi | null
+ readonly created_at: string
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedParserRecipeListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ParserRecipeApi[]
+}
+
+export interface PatchedParserRecipeApi {
+ readonly id?: string
+ /**
+ * Human-readable recipe name shown in the editor.
+ * @maxLength 255
+ */
+ name?: string
+ /** Raw YAML recipe source, compiled and validated client-side. */
+ source?: string
+ /** User who created the recipe. */
+ readonly created_by?: UserBasicApi | null
+ readonly created_at?: string
+ /** @nullable */
+ readonly updated_at?: string | null
+}
+
export interface PaginatedLLMProviderKeyListApi {
count: number
/** @nullable */
@@ -2708,6 +2749,17 @@ export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate400 = { [key: str
export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown }
+export type LlmAnalyticsParserRecipesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type LlmAnalyticsProviderKeyValidationsCreate200 = { [key: string]: unknown }
export type LlmAnalyticsProviderKeysListParams = {
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index 7ba11f61140a..8c71b4b66839 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -45,6 +45,7 @@ import type {
LlmAnalyticsEvaluationReportsListParams,
LlmAnalyticsEvaluationReportsRunsListParams,
LlmAnalyticsModelsRetrieveParams,
+ LlmAnalyticsParserRecipesListParams,
LlmAnalyticsPersonalSpendListParams,
LlmAnalyticsProviderKeyValidationsCreate200,
LlmAnalyticsProviderKeysListParams,
@@ -72,11 +73,13 @@ import type {
PaginatedLLMPromptListListApi,
PaginatedLLMProviderKeyListApi,
PaginatedLLMSkillListListApi,
+ PaginatedParserRecipeListApi,
PaginatedReviewQueueItemListApi,
PaginatedReviewQueueListApi,
PaginatedScoreDefinitionListApi,
PaginatedTaggerListApi,
PaginatedTraceReviewListApi,
+ ParserRecipeApi,
PatchedClusteringJobApi,
PatchedDatasetApi,
PatchedDatasetItemApi,
@@ -85,6 +88,7 @@ import type {
PatchedLLMPromptPublishApi,
PatchedLLMProviderKeyApi,
PatchedLLMSkillPublishApi,
+ PatchedParserRecipeApi,
PatchedReviewQueueItemUpdateApi,
PatchedReviewQueueUpdateApi,
PatchedScoreDefinitionMetadataApi,
@@ -1029,6 +1033,101 @@ export const llmAnalyticsOfflineEvaluationsExperimentItemsCreate = async (
)
}
+export const getLlmAnalyticsParserRecipesListUrl = (
+ projectId: string,
+ params?: LlmAnalyticsParserRecipesListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/llm_analytics/parser_recipes/?${stringifiedParams}`
+ : `/api/projects/${projectId}/llm_analytics/parser_recipes/`
+}
+
+export const llmAnalyticsParserRecipesList = async (
+ projectId: string,
+ params?: LlmAnalyticsParserRecipesListParams,
+ options?: RequestInit
+): Promise<PaginatedParserRecipeListApi> => {
+ return apiMutator<PaginatedParserRecipeListApi>(getLlmAnalyticsParserRecipesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getLlmAnalyticsParserRecipesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/llm_analytics/parser_recipes/`
+}
+
+export const llmAnalyticsParserRecipesCreate = async (
+ projectId: string,
+ parserRecipeApi: NonReadonly<ParserRecipeApi>,
+ options?: RequestInit
+): Promise<ParserRecipeApi> => {
+ return apiMutator<ParserRecipeApi>(getLlmAnalyticsParserRecipesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(parserRecipeApi),
+ })
+}
+
+export const getLlmAnalyticsParserRecipesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/llm_analytics/parser_recipes/${id}/`
+}
+
+export const llmAnalyticsParserRecipesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ParserRecipeApi> => {
+ return apiMutator<ParserRecipeApi>(getLlmAnalyticsParserRecipesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getLlmAnalyticsParserRecipesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/llm_analytics/parser_recipes/${id}/`
+}
+
+export const llmAnalyticsParserRecipesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedParserRecipeApi?: NonReadonly<PatchedParserRecipeApi>,
+ options?: RequestInit
+): Promise<ParserRecipeApi> => {
+ return apiMutator<ParserRecipeApi>(getLlmAnalyticsParserRecipesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedParserRecipeApi),
+ })
+}
+
+export const getLlmAnalyticsParserRecipesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/llm_analytics/parser_recipes/${id}/`
+}
+
+export const llmAnalyticsParserRecipesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getLlmAnalyticsParserRecipesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getLlmAnalyticsProviderKeyValidationsCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/llm_analytics/provider_key_validations/`
}
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 525dac9f1459..bfd47bd6ad6f 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -976,6 +976,27 @@ export const LlmAnalyticsOfflineEvaluationsExperimentItemsCreateBody = /* @__PUR
.describe('Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.'),
})
+export const llmAnalyticsParserRecipesCreateBodyNameMax = 255
+
+export const LlmAnalyticsParserRecipesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(llmAnalyticsParserRecipesCreateBodyNameMax)
+ .describe('Human-readable recipe name shown in the editor.'),
+ source: zod.string().describe('Raw YAML recipe source, compiled and validated client-side.'),
+})
+
+export const llmAnalyticsParserRecipesPartialUpdateBodyNameMax = 255
+
+export const LlmAnalyticsParserRecipesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(llmAnalyticsParserRecipesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable recipe name shown in the editor.'),
+ source: zod.string().optional().describe('Raw YAML recipe source, compiled and validated client-side.'),
+})
+
export const llmAnalyticsProviderKeysCreateBodyNameMax = 255
export const llmAnalyticsProviderKeysCreateBodyApiVersionMax = 20
diff --git a/products/ai_observability/frontend/messageNormalization.ts b/products/ai_observability/frontend/messageNormalization.ts
index 046ee7c85f51..7c4ad5d3a727 100644
--- a/products/ai_observability/frontend/messageNormalization.ts
+++ b/products/ai_observability/frontend/messageNormalization.ts
@@ -3,7 +3,7 @@ import posthog, { JsonType } from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { objectsEqual, removeUndefinedAndNull } from 'lib/utils'
-import { RecipeNormalizer } from './normalizer'
+import { mergeRecipes, RecipeNormalizer, StoredRecipe } from './normalizer'
import { CompatMessage } from './types'
import { normalizeMessage as legacyNormalizeMessage, normalizeMessages as legacyNormalizeMessages } from './utils'
@@ -11,6 +11,17 @@ import { normalizeMessage as legacyNormalizeMessage, normalizeMessages as legacy
// construction would dwarf the work we're measuring.
const recipeNormalizer = new RecipeNormalizer()
+// Swap the live normalizer over to a team's custom recipe set. Called wherever traces
+// render once the team's recipes load (and after every edit). Wrapped so a malformed
+// config can never break trace rendering — we keep the prior set on error.
+export function applyTeamParserRecipes(stored: StoredRecipe[]): void {
+ try {
+ recipeNormalizer.setRecipes(mergeRecipes(stored))
+ } catch {
+ // keep whatever set is currently active
+ }
+}
+
// Normalization runs once per rendered message; sample so timing doesn't flood ingestion.
const DEFAULT_TIMING_SAMPLE_RATE = 0.01
diff --git a/products/ai_observability/frontend/normalizer/index.ts b/products/ai_observability/frontend/normalizer/index.ts
index 0fbaeb838b2c..aa82ccd27bc1 100644
--- a/products/ai_observability/frontend/normalizer/index.ts
+++ b/products/ai_observability/frontend/normalizer/index.ts
@@ -3,3 +3,6 @@
// module is also exercised directly by the parity test suite.
export { RecipeNormalizer } from './recipe/recipeNormalizer'
+export { mergeRecipes } from './recipe/merge'
+export type { StoredRecipe } from './recipe/merge'
+export { compileRecipe } from './recipe/compile/compiler'
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
index c59887e3a133..34d8f2189b8c 100644
--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
@@ -46,11 +46,14 @@ const OPERATORS = new Set([
const BARE_FIELD_RE = /^[A-Za-z_]\w*$/
-export function compileRecipe(raw: unknown): Recipe {
+// `fallbackId` is the identity to use when the yaml omits `id:` — custom recipes are
+// keyed by their database id, so their source never needs to declare one. Bundled
+// recipes pass no fallback and must declare their id.
+export function compileRecipe(raw: unknown, fallbackId?: string): Recipe {
if (!isObject(raw)) {
throw new Error(`Recipe YAML must be a mapping at top level`)
}
- const id = stringField(raw, 'id')
+ const id = stringField(raw, 'id') ?? fallbackId
if (!id) {
throw new Error(`Recipe is missing an 'id' key`)
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.test.ts b/products/ai_observability/frontend/normalizer/recipe/merge.test.ts
new file mode 100644
index 000000000000..f9b6c90cd94d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/merge.test.ts
@@ -0,0 +1,36 @@
+import { mergeRecipes, StoredRecipe } from './merge'
+import { loadRecipes } from './registry'
+
+const ids = (recipes: { id: string }[]): string[] => recipes.map((r) => r.id)
+const builtinIds = (): string[] => ids(loadRecipes())
+
+describe('mergeRecipes', () => {
+ it('returns the bundled defaults in order when the team has no customs', () => {
+ expect(ids(mergeRecipes([]))).toEqual(builtinIds())
+ })
+
+ it('identifies customs by their database id, not any id in the source, before the catch-all', () => {
+ const customs: StoredRecipe[] = [
+ { id: 'db-first', source: 'rules: []\n' },
+ { id: 'db-second', source: 'id: ignored\nrules: []\n' },
+ ]
+ const merged = ids(mergeRecipes(customs))
+ const cajoleIndex = merged.indexOf('cajole')
+ expect(merged.slice(cajoleIndex - 2, cajoleIndex)).toEqual(['db-first', 'db-second'])
+ expect(merged[merged.length - 1]).toBe('cajole')
+ })
+
+ it('keeps every builtin present alongside the customs', () => {
+ const merged = ids(mergeRecipes([{ id: 'db-custom', source: 'rules: []\n' }]))
+ for (const builtin of builtinIds()) {
+ expect(merged).toContain(builtin)
+ }
+ expect(merged).toContain('db-custom')
+ expect(loadRecipes().find((r) => r.id === 'openai_chat')!.rules.length).toBeGreaterThan(0)
+ })
+
+ it('skips a custom recipe that fails to compile', () => {
+ const broken: StoredRecipe = { id: 'db-custom', source: 'not: [valid' }
+ expect(ids(mergeRecipes([broken]))).toEqual(builtinIds())
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.ts b/products/ai_observability/frontend/normalizer/recipe/merge.ts
new file mode 100644
index 000000000000..11d690cc091e
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/merge.ts
@@ -0,0 +1,35 @@
+import { parse as parseYaml } from 'yaml'
+
+import { compileRecipe } from './compile/compiler'
+import { loadRecipes } from './registry'
+import { Recipe } from './spec/recipe'
+
+// A team's net-new custom recipe. Mirrors the `ParserRecipe` API row, narrowed to
+// what the merge needs so the normalizer stays decoupled from generated API types.
+export interface StoredRecipe {
+ id: string
+ source: string
+}
+
+// Resolve a team's custom recipes into the ordered set the pipeline runs: the bundled
+// builtins in their dispatch order, with the team's customs spliced in (in their stored
+// order) right before the last builtin (`cajole`, the last-resort catch-all) so they get
+// a shot at inputs the specific builtins miss while never shadowing them. A custom that
+// fails to compile is skipped — there's no builtin to fall back to — so a bad edit can
+// never break trace rendering. The catch-all must stay last in the bundled order.
+export function mergeRecipes(stored: StoredRecipe[]): Recipe[] {
+ const builtins = loadRecipes()
+ const customs = stored.map(tryCompile).filter((recipe): recipe is Recipe => recipe !== undefined)
+
+ const insertAt = builtins.length - 1
+ return [...builtins.slice(0, insertAt), ...customs, ...builtins.slice(insertAt)]
+}
+
+function tryCompile(recipe: StoredRecipe): Recipe | undefined {
+ try {
+ // The database id is the recipe's identity, regardless of any `id:` in the source.
+ return { ...compileRecipe(parseYaml(recipe.source), recipe.id), id: recipe.id }
+ } catch {
+ return undefined
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
index 62bea28a6151..ab028e80f704 100644
--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
@@ -2,12 +2,17 @@ import { CompatMessage } from '../../types'
import { AVAILABLE_TOOLS_ROLE } from '../../utils'
import { loadRecipes } from './registry'
import { NO_MATCH, RecipePipeline } from './runtime/pipeline'
+import { Recipe } from './spec/recipe'
export class RecipeNormalizer {
- private readonly pipeline: RecipePipeline
+ private pipeline: RecipePipeline
- constructor() {
- this.pipeline = new RecipePipeline(loadRecipes())
+ constructor(recipes: Recipe[] = loadRecipes()) {
+ this.pipeline = new RecipePipeline(recipes)
+ }
+
+ setRecipes(recipes: Recipe[]): void {
+ this.pipeline = new RecipePipeline(recipes)
}
normalizeMessage(input: unknown, defaultRole: string): CompatMessage[] {
diff --git a/products/ai_observability/frontend/settings/ParserRecipesSettings.tsx b/products/ai_observability/frontend/settings/ParserRecipesSettings.tsx
new file mode 100644
index 000000000000..fe83afcbdc3f
--- /dev/null
+++ b/products/ai_observability/frontend/settings/ParserRecipesSettings.tsx
@@ -0,0 +1,122 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal, LemonTextArea, Spinner } from '@posthog/lemon-ui'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+
+import { CustomRecipeItem, parserRecipesLogic } from './parserRecipesLogic'
+
+export function ParserRecipesSettings(): JSX.Element {
+ const { customItems, storedRecipesLoading } = useValues(parserRecipesLogic)
+ const { openEditorForNew } = useActions(parserRecipesLogic)
+
+ if (storedRecipesLoading) {
+ return <Spinner />
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ {customItems.length === 0 ? (
+ <p className="text-muted">
+ No custom recipes yet. Add one to normalize a provider shape the built-in recipes miss.
+ </p>
+ ) : (
+ <div className="flex flex-col gap-1">
+ {customItems.map((item) => (
+ <RecipeRow key={item.id} item={item} />
+ ))}
+ </div>
+ )}
+ <div>
+ <LemonButton type="primary" onClick={openEditorForNew}>
+ Add recipe
+ </LemonButton>
+ </div>
+ <RecipeEditorModal />
+ </div>
+ )
+}
+
+function RecipeRow({ item }: { item: CustomRecipeItem }): JSX.Element {
+ const { openEditorForItem, deleteItem } = useActions(parserRecipesLogic)
+
+ return (
+ <div className="flex items-center gap-2 border rounded p-2 bg-bg-light">
+ <span className="font-medium flex-1 ph-no-capture">{item.name}</span>
+ <LemonButton size="small" type="secondary" onClick={() => openEditorForItem(item)}>
+ Edit
+ </LemonButton>
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Delete recipe?',
+ description: `This permanently deletes "${item.name}". This cannot be undone.`,
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteItem(item),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ >
+ Delete
+ </LemonButton>
+ </div>
+ )
+}
+
+function RecipeEditorModal(): JSX.Element {
+ const { editor, savingEditor, editorCompileError } = useValues(parserRecipesLogic)
+ const { closeEditor, setEditorName, setEditorSource, submitEditor } = useActions(parserRecipesLogic)
+
+ const nameMissing = !editor?.name.trim()
+
+ return (
+ <LemonModal
+ isOpen={!!editor}
+ onClose={closeEditor}
+ title={editor?.rowId ? 'Edit recipe' : 'New recipe'}
+ width={720}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeEditor}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={submitEditor}
+ loading={savingEditor}
+ disabledReason={
+ nameMissing
+ ? 'Recipe name is required'
+ : editorCompileError
+ ? 'Recipe YAML does not compile'
+ : undefined
+ }
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
+ {editor && (
+ <div className="flex flex-col gap-2 w-full">
+ <LemonInput placeholder="Recipe name" value={editor.name} onChange={setEditorName} />
+ <LemonTextArea
+ className="font-mono"
+ value={editor.source}
+ onChange={setEditorSource}
+ minRows={12}
+ placeholder="Recipe YAML"
+ />
+ {editorCompileError && <p className="text-danger text-sm m-0">{editorCompileError}</p>}
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts b/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts
new file mode 100644
index 000000000000..b37b4700d3c1
--- /dev/null
+++ b/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts
@@ -0,0 +1,105 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ llmAnalyticsParserRecipesCreate,
+ llmAnalyticsParserRecipesDestroy,
+ llmAnalyticsParserRecipesList,
+} from '../generated/api'
+import { parserRecipesLogic } from './parserRecipesLogic'
+
+jest.mock('../generated/api', () => ({
+ llmAnalyticsParserRecipesList: jest.fn(),
+ llmAnalyticsParserRecipesCreate: jest.fn(),
+ llmAnalyticsParserRecipesPartialUpdate: jest.fn(),
+ llmAnalyticsParserRecipesDestroy: jest.fn(),
+}))
+
+const mockList = llmAnalyticsParserRecipesList as jest.MockedFunction<typeof llmAnalyticsParserRecipesList>
+const mockCreate = llmAnalyticsParserRecipesCreate as jest.MockedFunction<typeof llmAnalyticsParserRecipesCreate>
+const mockDestroy = llmAnalyticsParserRecipesDestroy as jest.MockedFunction<typeof llmAnalyticsParserRecipesDestroy>
+
+const FLAG = FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER
+
+describe('parserRecipesLogic', () => {
+ let logic: ReturnType<typeof parserRecipesLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockList.mockResolvedValue({ results: [] } as any)
+ initKeaTests()
+ featureFlagLogic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ const enableFlag = (): void => featureFlagLogic.actions.setFeatureFlags([FLAG], { [FLAG]: true })
+
+ it('does not fetch recipes while the feature flag is off', async () => {
+ logic = parserRecipesLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockList).not.toHaveBeenCalled()
+ expect(logic.values.storedRecipes).toEqual([])
+ })
+
+ it('fetches recipes when the flag is on and maps them for the list and the merge', async () => {
+ enableFlag()
+ mockList.mockResolvedValue({ results: [{ id: 'r1', name: 'First', source: 'rules: []\n' }] } as any)
+ logic = parserRecipesLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadRecipesSuccess'])
+ expect(mockList).toHaveBeenCalled()
+ expect(logic.values.customItems).toEqual([{ id: 'r1', name: 'First', source: 'rules: []\n' }])
+ expect(logic.values.storedForMerge).toEqual([{ id: 'r1', source: 'rules: []\n' }])
+ })
+
+ it('surfaces a compile error for invalid editor source and clears it on close', () => {
+ logic = parserRecipesLogic()
+ logic.mount()
+ logic.actions.openEditorForNew()
+ expect(logic.values.editorCompileError).toBeNull()
+ logic.actions.setEditorSource('not: [valid')
+ expect(logic.values.editorCompileError).not.toBeNull()
+ logic.actions.closeEditor()
+ expect(logic.values.editor).toBeNull()
+ expect(logic.values.editorCompileError).toBeNull()
+ })
+
+ it('rejects submit with an empty name and makes no request', async () => {
+ logic = parserRecipesLogic()
+ logic.mount()
+ logic.actions.openEditorForNew()
+ await expectLogic(logic, () => logic.actions.submitEditor()).toFinishAllListeners()
+ expect(mockCreate).not.toHaveBeenCalled()
+ expect(logic.values.savingEditor).toBe(false)
+ })
+
+ it('creates a recipe and closes the editor on submit', async () => {
+ mockCreate.mockResolvedValue({ id: 'new' } as any)
+ logic = parserRecipesLogic()
+ logic.mount()
+ logic.actions.openEditorForNew()
+ logic.actions.setEditorName('My recipe')
+ logic.actions.setEditorSource('rules: []\n')
+ await expectLogic(logic, () => logic.actions.submitEditor()).toFinishAllListeners()
+ expect(mockCreate).toHaveBeenCalledWith(expect.any(String), { name: 'My recipe', source: 'rules: []\n' })
+ expect(logic.values.editor).toBeNull()
+ })
+
+ it('deletes a recipe', async () => {
+ mockDestroy.mockResolvedValue(undefined as any)
+ logic = parserRecipesLogic()
+ logic.mount()
+ await expectLogic(logic, () =>
+ logic.actions.deleteItem({ id: 'r1', name: 'X', source: 'rules: []\n' })
+ ).toFinishAllListeners()
+ expect(mockDestroy).toHaveBeenCalledWith(expect.any(String), 'r1')
+ })
+})
diff --git a/products/ai_observability/frontend/settings/parserRecipesLogic.ts b/products/ai_observability/frontend/settings/parserRecipesLogic.ts
new file mode 100644
index 000000000000..49253f00a99d
--- /dev/null
+++ b/products/ai_observability/frontend/settings/parserRecipesLogic.ts
@@ -0,0 +1,173 @@
+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+import { parse as parseYaml } from 'yaml'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ llmAnalyticsParserRecipesCreate,
+ llmAnalyticsParserRecipesDestroy,
+ llmAnalyticsParserRecipesList,
+ llmAnalyticsParserRecipesPartialUpdate,
+} from '../generated/api'
+import { ParserRecipeApi } from '../generated/api.schemas'
+import { applyTeamParserRecipes } from '../messageNormalization'
+import { compileRecipe, StoredRecipe } from '../normalizer'
+import type { parserRecipesLogicType } from './parserRecipesLogicType'
+
+export interface CustomRecipeItem {
+ id: string
+ name: string
+ source: string
+}
+
+export interface RecipeEditorState {
+ rowId: string | null
+ name: string
+ source: string
+}
+
+const NEW_CUSTOM_SOURCE = 'rules:\n - on:\n $: { exists: true }\n emit:\n content: $\n'
+
+export function sourceCompileError(source: string): string | null {
+ try {
+ // The id is supplied from the database at merge time, so a missing one is fine here.
+ compileRecipe(parseYaml(source), 'preview')
+ return null
+ } catch (err) {
+ return err instanceof Error ? err.message : String(err)
+ }
+}
+
+// Owns the team's custom recipes end to end: loads them (flag-gated), pushes them into
+// the live trace-rendering normalizer, and backs the settings editor. Mounted on every
+// AI observability view via aiObservabilitySharedLogic so customizations apply even when
+// the settings scene was never opened; the editor parts stay dormant outside settings.
+export const parserRecipesLogic = kea<parserRecipesLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'settings', 'parserRecipesLogic']),
+ connect(() => ({ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']] })),
+ actions({
+ openEditorForNew: true,
+ openEditorForItem: (item: CustomRecipeItem) => ({ item }),
+ closeEditor: true,
+ setEditorName: (name: string) => ({ name }),
+ setEditorSource: (source: string) => ({ source }),
+ submitEditor: true,
+ submitEditorDone: true,
+ deleteItem: (item: CustomRecipeItem) => ({ item }),
+ }),
+ loaders(({ values }) => ({
+ storedRecipes: [
+ [] as ParserRecipeApi[],
+ {
+ loadRecipes: async () => {
+ if (!values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER]) {
+ return []
+ }
+ return (await llmAnalyticsParserRecipesList(String(values.currentTeamId), { limit: 1000 })).results
+ },
+ },
+ ],
+ })),
+ reducers({
+ editor: [
+ null as RecipeEditorState | null,
+ {
+ closeEditor: () => null,
+ openEditorForNew: () => ({ rowId: null, name: '', source: NEW_CUSTOM_SOURCE }),
+ openEditorForItem: (_, { item }) => ({ rowId: item.id, name: item.name, source: item.source }),
+ setEditorName: (state, { name }) => (state ? { ...state, name } : state),
+ setEditorSource: (state, { source }) => (state ? { ...state, source } : state),
+ },
+ ],
+ savingEditor: [
+ false,
+ {
+ submitEditor: () => true,
+ submitEditorDone: () => false,
+ closeEditor: () => false,
+ },
+ ],
+ }),
+ selectors({
+ storedForMerge: [
+ (s) => [s.storedRecipes],
+ (rows): StoredRecipe[] => rows.map((row) => ({ id: row.id, source: row.source })),
+ ],
+ customItems: [
+ (s) => [s.storedRecipes],
+ (rows: ParserRecipeApi[]): CustomRecipeItem[] =>
+ rows.map((row) => ({ id: row.id, name: row.name, source: row.source })),
+ ],
+ editorCompileError: [
+ (s) => [s.editor],
+ (editor): string | null => (editor ? sourceCompileError(editor.source) : null),
+ ],
+ // The team whose recipes should be loaded, or null when the feature is off.
+ // Re-fetches on team switch and when the flag flips on (see subscriptions).
+ loadKey: [
+ (s) => [s.currentTeamId, s.featureFlags],
+ (currentTeamId, featureFlags): number | null =>
+ featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER] ? currentTeamId : null,
+ ],
+ }),
+ subscriptions(({ actions }) => ({
+ // Fires on mount with the initial value, then on every change — so this covers
+ // the first load, project switches, and the flag turning on.
+ loadKey: (loadKey: number | null) => {
+ if (loadKey !== null) {
+ actions.loadRecipes()
+ }
+ },
+ })),
+ listeners(({ actions, values }) => ({
+ loadRecipesSuccess: () => applyTeamParserRecipes(values.storedForMerge),
+ submitEditor: async () => {
+ const editor = values.editor
+ if (!editor) {
+ return
+ }
+ const name = editor.name.trim()
+ if (!name) {
+ lemonToast.error('Recipe name is required')
+ actions.submitEditorDone()
+ return
+ }
+ if (values.editorCompileError) {
+ lemonToast.error(`Recipe does not compile: ${values.editorCompileError}`)
+ actions.submitEditorDone()
+ return
+ }
+ try {
+ if (editor.rowId) {
+ await llmAnalyticsParserRecipesPartialUpdate(String(values.currentTeamId), editor.rowId, {
+ name,
+ source: editor.source,
+ })
+ } else {
+ await llmAnalyticsParserRecipesCreate(String(values.currentTeamId), { name, source: editor.source })
+ }
+ actions.loadRecipes()
+ actions.closeEditor()
+ lemonToast.success('Recipe saved')
+ } catch {
+ lemonToast.error('Could not save recipe')
+ actions.submitEditorDone()
+ }
+ },
+ deleteItem: async ({ item }) => {
+ try {
+ await llmAnalyticsParserRecipesDestroy(String(values.currentTeamId), item.id)
+ actions.loadRecipes()
+ lemonToast.success('Recipe deleted')
+ } catch {
+ lemonToast.error('Could not delete recipe')
+ }
+ },
+ })),
+])
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index 577a87c34d60..b80208abd22c 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -17,6 +17,21 @@ tools:
llm-analytics-offline-evaluations-experiment-items-create:
operation: llm_analytics_offline_evaluations_experiment_items_create
enabled: false
+ llm-analytics-parser-recipes-create:
+ operation: llm_analytics_parser_recipes_create
+ enabled: false
+ llm-analytics-parser-recipes-destroy:
+ operation: llm_analytics_parser_recipes_destroy
+ enabled: false
+ llm-analytics-parser-recipes-list:
+ operation: llm_analytics_parser_recipes_list
+ enabled: false
+ llm-analytics-parser-recipes-partial-update:
+ operation: llm_analytics_parser_recipes_partial_update
+ enabled: false
+ llm-analytics-parser-recipes-retrieve:
+ operation: llm_analytics_parser_recipes_retrieve
+ enabled: false
llm-analytics-sentiment-generations-create:
operation: llm_analytics_sentiment_generations_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b684c1bcdb5e..f552cf2aff76 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24143,6 +24143,31 @@ export namespace Schemas {
results: OrganizationOAuthApplication[];
}
+ export interface ParserRecipe {
+ readonly id: string;
+ /**
+ * Human-readable recipe name shown in the editor.
+ * @maxLength 255
+ */
+ name: string;
+ /** Raw YAML recipe source, compiled and validated client-side. */
+ source: string;
+ /** User who created the recipe. */
+ readonly created_by: UserBasic | null;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
+ export interface PaginatedParserRecipeList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ParserRecipe[];
+ }
+
export interface PauseStateResponse {
/**
* The timestamp the pipeline is paused until, or null if not paused/not running.
@@ -30081,6 +30106,22 @@ export namespace Schemas {
readonly last_login?: string;
}
+ export interface PatchedParserRecipe {
+ readonly id?: string;
+ /**
+ * Human-readable recipe name shown in the editor.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Raw YAML recipe source, compiled and validated client-side. */
+ source?: string;
+ /** User who created the recipe. */
+ readonly created_by?: UserBasic | null;
+ readonly created_at?: string;
+ /** @nullable */
+ readonly updated_at?: string | null;
+ }
+
export interface PatchedPersistedFolder {
readonly id?: string;
/** Which persisted folder this is for the user (home, pinned, custom_products).
@@ -49142,6 +49183,17 @@ export namespace Schemas {
export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown };
+ export type LlmAnalyticsParserRecipesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type LlmAnalyticsProviderKeyValidationsCreate200 = { [key: string]: unknown };
export type LlmAnalyticsProviderKeysListParams = {