: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
fix(aio): chunk eval summary to avoid ai-gateway 30s timeout (#70918)
posthog[bot]52acffded31e
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 6cfc3df291a7..fda982cee67c 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -696,21 +696,21 @@ class AIObservabilitySentimentSustainedThrottle(PersonalApiKeyRateThrottle):rate = "600/hour"-class AIObservabilitySummarizationBurstThrottle(PersonalApiKeyRateThrottle):+class AIObservabilitySummarizationBurstThrottle(PersonalApiKeyOrUserRateThrottle):# Rate limit for LLM-powered summarization endpoint# Conservative limits to control OpenAI API costsscope = "llm_analytics_summarization_burst"rate = "50/minute"-class AIObservabilitySummarizationSustainedThrottle(PersonalApiKeyRateThrottle):+class AIObservabilitySummarizationSustainedThrottle(PersonalApiKeyOrUserRateThrottle):# Rate limit for LLM-powered summarization endpoint# Conservative limits to control OpenAI API costsscope = "llm_analytics_summarization_sustained"rate = "200/hour"-class AIObservabilitySummarizationDailyThrottle(PersonalApiKeyRateThrottle):+class AIObservabilitySummarizationDailyThrottle(PersonalApiKeyOrUserRateThrottle):# Daily cap for LLM-powered summarization endpoint# Hard limit to prevent runaway costsscope = "llm_analytics_summarization_daily"diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.pyindex 733076558163..9b32e0d04acf 100644--- a/posthog/test/test_rate_limit.py+++ b/posthog/test/test_rate_limit.py@@ -7,6 +7,7 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import ANY, Mock, call, patchfrom django.core.cache import cache+from django.test import SimpleTestCasefrom django.utils.timezone import nowfrom parameterized import parameterized@@ -859,6 +860,39 @@ class TestPersonalOrProjectSecretApiKeyRateThrottle(APIBaseTest):self.assertTrue(_PSAKThrottleForTest().get_cache_key(self._psak_request(key_id=42), Mock()).endswith("psak:42"))+class TestAIObservabilitySummarizationRateThrottle(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()++ def tearDown(self) -> None:+ cache.clear()++ @parameterized.expand(+ [+ ("burst", rate_limit.AIObservabilitySummarizationBurstThrottle),+ ("sustained", rate_limit.AIObservabilitySummarizationSustainedThrottle),+ ("daily", rate_limit.AIObservabilitySummarizationDailyThrottle),+ ]+ )+ @patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False)+ @patch("posthog.rate_limit.PersonalAPIKeyAuthentication.find_key_with_source", return_value=None)+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_session_requests_are_rate_limited(+ self,+ _name: str,+ throttle_class: type[rate_limit.PersonalApiKeyRateThrottle],+ _rate_limit_enabled: Mock,+ _find_personal_api_key: Mock,+ _team_can_bypass: Mock,+ ) -> None:+ request = Mock(user=Mock(is_authenticated=True), path="/api/projects/1/llm_analytics/evaluation_summary/")+ view = Mock(team_id=1)++ with patch.object(throttle_class, "rate", "1/minute"):+ self.assertTrue(throttle_class().allow_request(request, view))+ self.assertFalse(throttle_class().allow_request(request, view))++class _PSAKTeamThrottleForTest(rate_limit.ProjectSecretApiKeyTeamRateThrottle):scope = "test_psak_team"rate = "100/minute"diff --git a/products/ai_observability/backend/api/evaluation_summary.py b/products/ai_observability/backend/api/evaluation_summary.pyindex 0db3f37b6432..c822f1fd731f 100644--- a/products/ai_observability/backend/api/evaluation_summary.py+++ b/products/ai_observability/backend/api/evaluation_summary.py@@ -92,6 +92,13 @@ class EvaluationSummaryResponseSerializer(serializers.Serializer):statistics = EvaluationSummaryStatisticsSerializer()+class EvaluationSummaryThrottleResponseSerializer(serializers.Serializer):+ type = serializers.CharField(help_text="Error category")+ code = serializers.CharField(help_text="Machine-readable error code")+ detail = serializers.CharField(help_text="Why the request was throttled")+ attr = serializers.CharField(allow_null=True, help_text="Related request field, when applicable")++def _fetch_evaluation_runs(team: Team,evaluation_id: str,@@ -269,6 +276,7 @@ class LLMEvaluationSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe400: OpenApiTypes.OBJECT,403: OpenApiTypes.OBJECT,404: OpenApiTypes.OBJECT,+ 429: EvaluationSummaryThrottleResponseSerializer,500: OpenApiTypes.OBJECT,},examples=[@@ -452,7 +460,7 @@ Data is fetched server-side by evaluation ID to ensure data integrity.return Response(result, status=status.HTTP_200_OK)- except exceptions.ValidationError:+ except exceptions.APIException:raiseexcept Exception as e:logger.exception(diff --git a/products/ai_observability/backend/api/test/test_evaluation_summary.py b/products/ai_observability/backend/api/test/test_evaluation_summary.pyindex 58bf1cc84df2..39af37b09081 100644--- a/products/ai_observability/backend/api/test/test_evaluation_summary.py+++ b/products/ai_observability/backend/api/test/test_evaluation_summary.py@@ -5,9 +5,9 @@ Tests for evaluation summary API endpoint.import uuidfrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patch-from rest_framework import status+from rest_framework import exceptions, statusfrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.summarization.constants import EVALUATION_SUMMARY_MAX_RUNS@@ -183,6 +183,35 @@ class TestEvaluationSummaryAPI(APIBaseTest):assert data["statistics"]["fail_count"] == 1assert data["statistics"]["na_count"] == 0+ @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")+ @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")+ def test_concurrent_summary_returns_throttled_response(+ self, mock_fetch_runs: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()++ mock_fetch_runs.return_value = [+ {"generation_id": "gen_001", "result": True, "reasoning": "Good response"},+ ]+ mock_async_to_sync.return_value.side_effect = exceptions.Throttled(+ detail="An evaluation summary is already being generated for this project. Try again when it finishes."+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",+ {+ "evaluation_id": str(self.evaluation.id),+ "filter": "all",+ "force_refresh": True,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert response.data["code"] == "throttled"+ assert "already being generated for this project" in response.data["detail"]+@patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")@patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")def test_filter_parameter_passed_to_fetch(self, mock_fetch_runs, mock_async_to_sync):diff --git a/products/ai_observability/backend/summarization/constants.py b/products/ai_observability/backend/summarization/constants.pyindex 05d6c7c9ba6e..ed0e2345bb77 100644--- a/products/ai_observability/backend/summarization/constants.py+++ b/products/ai_observability/backend/summarization/constants.py@@ -11,3 +11,13 @@ SUMMARIZATION_TIMEOUT = 120# Evaluation summary limitsEVALUATION_SUMMARY_MAX_RUNS = 250++# Large or verbose inputs are summarized as a bounded concurrent map-reduce so no+# individual ai-gateway request approaches its ~30s hard timeout.+EVALUATION_SUMMARY_CHUNK_SIZE = 20+EVALUATION_SUMMARY_PROMPT_MAX_CHARS = 20_000+EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS = 4_000+EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS = 2_000+EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS = 5+EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS = 10 * 60+EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT = 4diff --git a/products/ai_observability/backend/summarization/llm/evaluation_schema.py b/products/ai_observability/backend/summarization/llm/evaluation_schema.pyindex f3e0be3dc516..3c125f2a2d59 100644--- a/products/ai_observability/backend/summarization/llm/evaluation_schema.py+++ b/products/ai_observability/backend/summarization/llm/evaluation_schema.py@@ -2,8 +2,12 @@Pydantic schema for structured evaluation summary outputs."""+from typing import Annotated, Literal+from pydantic import BaseModel, ConfigDict, Field+from ..constants import EVALUATION_SUMMARY_CHUNK_SIZE, EVALUATION_SUMMARY_MAX_RUNS+class EvaluationPattern(BaseModel):"""A pattern identified across evaluation results."""@@ -41,3 +45,33 @@ class EvaluationSummaryResponse(BaseModel):na_patterns: list[EvaluationPattern]recommendations: list[str]statistics: EvaluationSummaryStatistics+++class EvaluationPatternCandidate(BaseModel):+ model_config = ConfigDict(extra="forbid")++ result: Literal["pass", "fail", "na"] = Field(description="Result category for this candidate theme")+ title: str = Field(max_length=60, description="Short title for the candidate theme (3-5 words)")+ occurrence_count: int = Field(+ ge=1,+ le=EVALUATION_SUMMARY_MAX_RUNS,+ description="Exact number of evaluation runs represented by this theme",+ )+ example_reasoning: str = Field(+ max_length=240,+ description="Concise reasoning from one run that demonstrates this candidate theme",+ )+ example_generation_ids: list[Annotated[str, Field(max_length=64)]] = Field(+ min_length=1,+ max_length=3,+ description="List of 1-3 generation IDs that exemplify this theme",+ )+++class EvaluationSummaryMapResponse(BaseModel):+ model_config = ConfigDict(extra="forbid")++ patterns: list[EvaluationPatternCandidate] = Field(+ max_length=EVALUATION_SUMMARY_CHUNK_SIZE,+ description="Candidate themes representing evaluation runs",+ )diff --git a/products/ai_observability/backend/summarization/llm/evaluation_summary.py b/products/ai_observability/backend/summarization/llm/evaluation_summary.pyindex cb21d1b2d18b..c902b44725f7 100644--- a/products/ai_observability/backend/summarization/llm/evaluation_summary.py+++ b/products/ai_observability/backend/summarization/llm/evaluation_summary.py@@ -1,21 +1,555 @@"""Evaluation summary generation, routed through the internal Go ai-gateway when-configured, else the Python LLM gateway."""+configured, else the Python LLM gateway.-from typing import Any, cast+Large evaluations use a concurrent hierarchical map-reduce because one LLM call over all+runs can trip the ai-gateway's ~30s hard timeout.+"""++import json+import asyncio+import contextlib+from collections.abc import AsyncIterator+from typing import Any, Literal, TypeVar, castimport structlog+from openai import AsyncOpenAIfrom openai.types.chat import ChatCompletionMessageParam+from pydantic import BaseModel+from redis.exceptions import LockErrorfrom rest_framework import exceptions+from posthog import redis as posthog_redisfrom posthog.llm.gateway_client import build_async_openai_client-from ..constants import SUMMARIZATION_TIMEOUT+from ..constants import (+ EVALUATION_SUMMARY_CHUNK_SIZE,+ EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS,+ EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS,+ EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS,+ EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS,+ EVALUATION_SUMMARY_PROMPT_MAX_CHARS,+ EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT,+ SUMMARIZATION_TIMEOUT,+)from ..models import OpenAIModelfrom ..utils import load_summarization_template-from .evaluation_schema import EvaluationSummaryResponse+from .evaluation_schema import (+ EvaluationPatternCandidate,+ EvaluationSummaryMapResponse,+ EvaluationSummaryResponse,+ EvaluationSummaryStatistics,+)logger = structlog.get_logger(__name__)+StructuredResponse = TypeVar("StructuredResponse", bound=BaseModel)+ResultCategory = Literal["pass", "fail", "na"]+++async def _team_generation_lock(team_id: int) -> AsyncIterator[None]:+ lock = posthog_redis.get_async_client().lock(+ f"llm_eval_summary_generation_lock:{team_id}",+ timeout=EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS,+ blocking=False,+ )+ if not await lock.acquire(blocking=False):+ raise exceptions.Throttled(+ detail="An evaluation summary is already being generated for this project. Try again when it finishes."+ )++ try:+ yield+ finally:+ try:+ await lock.release()+ except LockError:+ logger.warning("evaluation_summary_generation_lock_release_failed", team_id=team_id)+++def _result_label(result: bool | None) -> str:+ if result is None:+ return "N/A"+ return "PASS" if result else "FAIL"+++def _result_category(result: bool | None) -> ResultCategory:+ if result is None:+ return "na"+ return "pass" if result else "fail"+++def _compute_statistics(evaluation_runs: list[dict]) -> EvaluationSummaryStatistics:+ return EvaluationSummaryStatistics(+ total_analyzed=len(evaluation_runs),+ pass_count=sum(1 for run in evaluation_runs if run["result"] is True),+ fail_count=sum(1 for run in evaluation_runs if run["result"] is False),+ na_count=sum(1 for run in evaluation_runs if run["result"] is None),+ )+++def _build_runs_prompt(evaluation_runs: list[dict]) -> str:+ runs_text = "\n\n".join(+ f"- Generation ID: {run['generation_id']}\n Result: {_result_label(run['result'])}\n Reasoning: {run['reasoning']}"+ for run in evaluation_runs+ )++ stats = _compute_statistics(evaluation_runs)+ stats_parts = []+ if stats.pass_count > 0:+ stats_parts.append(f"{stats.pass_count} passed")+ if stats.fail_count > 0:+ stats_parts.append(f"{stats.fail_count} failed")+ if stats.na_count > 0:+ stats_parts.append(f"{stats.na_count} N/A")+ stats_text = ", ".join(stats_parts) if stats_parts else "no results"++ return f"""Analyze these {len(evaluation_runs)} evaluation results ({stats_text}):++{runs_text}"""+++def _available_user_prompt_chars(system_prompt: str) -> int:+ available_characters = EVALUATION_SUMMARY_PROMPT_MAX_CHARS - len(system_prompt)+ if available_characters < EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS:+ raise exceptions.ValidationError(+ "The evaluation context is too long to summarize. Shorten the evaluation prompt or description and try again."+ )+ return available_characters+++def _prompt_fits(system_prompt: str, user_prompt: str) -> bool:+ return len(system_prompt) + len(user_prompt) <= EVALUATION_SUMMARY_PROMPT_MAX_CHARS+++def _truncate_reasoning(reasoning: str) -> str:+ if len(reasoning) <= EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS:+ return reasoning++ marker = "\n...[truncated]...\n"+ available_characters = EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS - len(marker)+ prefix_length = (available_characters + 1) // 2+ suffix_length = available_characters // 2+ return f"{reasoning[:prefix_length]}{marker}{reasoning[-suffix_length:]}"+++def _build_bounded_chunks(evaluation_runs: list[dict], max_prompt_chars: int) -> list[list[dict]]:+ chunks: list[list[dict]] = []+ current_chunk: list[dict] = []++ for run in evaluation_runs:+ bounded_run = {**run, "reasoning": _truncate_reasoning(run["reasoning"])}+ proposed_chunk = [*current_chunk, bounded_run]+ proposed_prompt = _build_runs_prompt(proposed_chunk)++ if current_chunk and (+ len(proposed_chunk) > EVALUATION_SUMMARY_CHUNK_SIZE or len(proposed_prompt) > max_prompt_chars+ ):+ chunks.append(current_chunk)+ current_chunk = [bounded_run]+ else:+ current_chunk = proposed_chunk++ if len(_build_runs_prompt(current_chunk)) > max_prompt_chars:+ raise exceptions.ValidationError(+ "An evaluation result is too long to summarize. Shorten its reasoning and try again."+ )++ if current_chunk:+ chunks.append(current_chunk)++ return chunks+++def _map_response_schema(max_candidates: int, max_occurrences: int) -> dict[str, Any]:+ schema = EvaluationSummaryMapResponse.model_json_schema()+ schema["properties"]["patterns"]["maxItems"] = max_candidates+ schema["$defs"]["EvaluationPatternCandidate"]["properties"]["occurrence_count"]["maximum"] = max_occurrences+ return schema+++def _candidate_counts(candidates: list[EvaluationPatternCandidate]) -> dict[str, int]:+ counts = {"pass": 0, "fail": 0, "na": 0}+ for candidate in candidates:+ counts[candidate.result] += candidate.occurrence_count+ return counts+++def _run_counts(evaluation_runs: list[dict]) -> dict[str, int]:+ statistics = _compute_statistics(evaluation_runs)+ return {+ "pass": statistics.pass_count,+ "fail": statistics.fail_count,+ "na": statistics.na_count,+ }+++def _validate_map_response(response: EvaluationSummaryMapResponse, evaluation_runs: list[dict]) -> None:+ expected_counts = _run_counts(evaluation_runs)+ actual_counts = _candidate_counts(response.patterns)+ if actual_counts != expected_counts:+ raise ValueError(f"candidate counts {actual_counts} do not match run counts {expected_counts}")++ generation_results = {run["generation_id"]: _result_category(run["result"]) for run in evaluation_runs}+ if any(+ generation_results.get(generation_id) != candidate.result+ for candidate in response.patterns+ for generation_id in candidate.example_generation_ids+ ):+ raise ValueError("candidate response contains a generation ID from the wrong result category")+++def _validate_reduce_response(+ response: EvaluationSummaryMapResponse, input_candidates: list[EvaluationPatternCandidate]+) -> None:+ input_counts = _candidate_counts(input_candidates)+ output_counts = _candidate_counts(response.patterns)+ if output_counts != input_counts:+ raise ValueError("reduced candidate counts do not match the input counts")++ generation_results = {+ generation_id: candidate.result+ for candidate in input_candidates+ for generation_id in candidate.example_generation_ids+ }+ if any(+ generation_results.get(generation_id) != candidate.result+ for candidate in response.patterns+ for generation_id in candidate.example_generation_ids+ ):+ raise ValueError("reduced response contains a generation ID from the wrong result category")+++def _build_candidates_prompt(+ candidates: list[EvaluationPatternCandidate], statistics: EvaluationSummaryStatistics+) -> str:+ candidate_payload = json.dumps(+ [candidate.model_dump() for candidate in candidates],+ separators=(",", ":"),+ )+ return f"""Ground-truth statistics for the complete evaluation:+{statistics.model_dump_json()}++Candidate themes to consolidate:+{candidate_payload}"""+++def _build_bounded_candidate_groups(+ candidates: list[EvaluationPatternCandidate],+ statistics: EvaluationSummaryStatistics,+ max_prompt_chars: int,+) -> list[list[EvaluationPatternCandidate]]:+ groups: list[list[EvaluationPatternCandidate]] = []+ current_group: list[EvaluationPatternCandidate] = []++ for candidate in candidates:+ proposed_group = [*current_group, candidate]+ if current_group and len(_build_candidates_prompt(proposed_group, statistics)) > max_prompt_chars:+ groups.append(current_group)+ current_group = [candidate]+ else:+ current_group = proposed_group++ if len(_build_candidates_prompt(current_group, statistics)) > max_prompt_chars:+ raise exceptions.APIException(+ "Couldn't fit evaluation evidence within the summary prompt limit. Reduce the number of runs and try again."+ )++ if current_group:+ groups.append(current_group)++ return groups+++async def _run_structured_completion(+ client: AsyncOpenAI,+ model: OpenAIModel,+ system_prompt: str,+ user_prompt: str,+ team_id: int,+ user_distinct_id: str,+ response_model: type[StructuredResponse],+ schema_name: str,+ response_schema: dict[str, Any] | None = None,+) -> StructuredResponse:+ messages: list[ChatCompletionMessageParam] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]++ response = await client.chat.completions.create(+ model=str(model),+ messages=messages,+ user=user_distinct_id or "llma-evaluation-summarization",+ timeout=SUMMARIZATION_TIMEOUT,+ response_format=cast(+ Any,+ {+ "type": "json_schema",+ "json_schema": {+ "name": schema_name,+ "strict": True,+ "schema": response_schema or response_model.model_json_schema(),+ },+ },+ ),+ )++ content = response.choices[0].message.content+ if not content:+ logger.error("evaluation_summary_empty_response", team_id=team_id, model=str(model))+ raise exceptions.APIException("Failed to generate evaluation summary: empty response")++ return response_model.model_validate_json(content)+++async def _run_map_completion(+ client: AsyncOpenAI,+ model: OpenAIModel,+ system_prompt: str,+ evaluation_runs: list[dict],+ team_id: int,+ user_distinct_id: str,+) -> EvaluationSummaryMapResponse:+ last_error: ValueError | None = None+ for attempt in range(2):+ response = await _run_structured_completion(+ client=client,+ model=model,+ system_prompt=system_prompt,+ user_prompt=_build_runs_prompt(evaluation_runs),+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ response_model=EvaluationSummaryMapResponse,+ schema_name="evaluation_summary_candidates",+ response_schema=_map_response_schema(+ max_candidates=len(evaluation_runs),+ max_occurrences=len(evaluation_runs),+ ),+ )+ try:+ _validate_map_response(response, evaluation_runs)+ return response+ except ValueError as error:+ last_error = error+ logger.warning(+ "evaluation_summary_map_response_invalid",+ team_id=team_id,+ model=str(model),+ attempt=attempt + 1,+ error=str(error),+ )++ raise exceptions.APIException("Couldn't generate a complete evaluation summary. Try again.") from last_error+++async def _run_reduce_completion(+ client: AsyncOpenAI,+ model: OpenAIModel,+ system_prompt: str,+ input_candidates: list[EvaluationPatternCandidate],+ statistics: EvaluationSummaryStatistics,+ team_id: int,+ user_distinct_id: str,+) -> EvaluationSummaryMapResponse:+ result_category_count = sum(count > 0 for count in _candidate_counts(input_candidates).values())+ max_candidates = min(+ EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT * result_category_count,+ max(result_category_count, len(input_candidates) - 1),+ )+ max_occurrences = sum(candidate.occurrence_count for candidate in input_candidates)+ last_error: ValueError | None = None++ for attempt in range(2):+ response = await _run_structured_completion(+ client=client,+ model=model,+ system_prompt=system_prompt,+ user_prompt=_build_candidates_prompt(input_candidates, statistics),+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ response_model=EvaluationSummaryMapResponse,+ schema_name="evaluation_summary_reduced_candidates",+ response_schema=_map_response_schema(+ max_candidates=max_candidates,+ max_occurrences=max_occurrences,+ ),+ )+ try:+ _validate_reduce_response(response, input_candidates)+ return response+ except ValueError as error:+ last_error = error+ logger.warning(+ "evaluation_summary_reduce_response_invalid",+ team_id=team_id,+ model=str(model),+ attempt=attempt + 1,+ error=str(error),+ )++ raise exceptions.APIException("Couldn't consolidate the evaluation summary. Try again.") from last_error+++async def _reduce_candidates_to_budget(+ client: AsyncOpenAI,+ model: OpenAIModel,+ candidates: list[EvaluationPatternCandidate],+ statistics: EvaluationSummaryStatistics,+ final_system_prompt: str,+ prompt_context: dict[str, Any],+ team_id: int,+ user_distinct_id: str,+ llm_call_semaphore: asyncio.Semaphore,+) -> list[EvaluationPatternCandidate]:+ final_user_prompt_chars = _available_user_prompt_chars(final_system_prompt)+ reduce_system_prompt = load_summarization_template(+ "prompts/evaluation_summary_reduce.djt",+ {+ **prompt_context,+ "max_candidates_per_result": EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT,+ },+ )+ reduce_user_prompt_chars = _available_user_prompt_chars(reduce_system_prompt)+ reduced_candidates = candidates++ while len(_build_candidates_prompt(reduced_candidates, statistics)) > final_user_prompt_chars:+ groups = _build_bounded_candidate_groups(+ reduced_candidates,+ statistics,+ reduce_user_prompt_chars,+ )++ async def reduce_group(group: list[EvaluationPatternCandidate]) -> EvaluationSummaryMapResponse:+ if len(group) == 1:+ return EvaluationSummaryMapResponse(patterns=group)+ async with llm_call_semaphore:+ return await _run_reduce_completion(+ client=client,+ model=model,+ system_prompt=reduce_system_prompt,+ input_candidates=group,+ statistics=statistics,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ )++ reduced_groups = await asyncio.gather(*(reduce_group(group) for group in groups))+ next_candidates = [candidate for group in reduced_groups for candidate in group.patterns]+ if len(next_candidates) >= len(reduced_candidates):+ raise exceptions.APIException(+ "Couldn't reduce the evaluation evidence enough to generate a summary. Reduce the number of runs and try again."+ )+ reduced_candidates = next_candidates++ return reduced_candidates+++async def _merge_summaries(+ client: AsyncOpenAI,+ model: OpenAIModel,+ batch_candidates: list[EvaluationSummaryMapResponse],+ statistics: EvaluationSummaryStatistics,+ prompt_context: dict[str, Any],+ team_id: int,+ user_distinct_id: str,+ llm_call_semaphore: asyncio.Semaphore,+) -> EvaluationSummaryResponse:+ merge_system_prompt = load_summarization_template("prompts/evaluation_summary_merge.djt", prompt_context)+ candidates = [candidate for batch in batch_candidates for candidate in batch.patterns]+ candidates = await _reduce_candidates_to_budget(+ client=client,+ model=model,+ candidates=candidates,+ statistics=statistics,+ final_system_prompt=merge_system_prompt,+ prompt_context=prompt_context,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ llm_call_semaphore=llm_call_semaphore,+ )+ merge_user_prompt = _build_candidates_prompt(candidates, statistics)++ return await _run_structured_completion(+ client=client,+ model=model,+ system_prompt=merge_system_prompt,+ user_prompt=merge_user_prompt,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ response_model=EvaluationSummaryResponse,+ schema_name="evaluation_summary",+ )+++async def _generate_evaluation_summary(+ evaluation_runs: list[dict],+ team_id: int,+ model: OpenAIModel,+ filter_type: str,+ evaluation_name: str,+ evaluation_description: str,+ evaluation_prompt: str,+ user_distinct_id: str,+) -> EvaluationSummaryResponse:+ statistics = _compute_statistics(evaluation_runs)+ prompt_context = {+ "filter": filter_type,+ "evaluation_name": evaluation_name,+ "evaluation_description": evaluation_description,+ "evaluation_prompt": evaluation_prompt,+ "max_candidates": EVALUATION_SUMMARY_CHUNK_SIZE,+ }+ client = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")+ if len(evaluation_runs) <= EVALUATION_SUMMARY_CHUNK_SIZE:+ single_system_prompt = load_summarization_template("prompts/evaluation_summary.djt", prompt_context)+ single_user_prompt = _build_runs_prompt(evaluation_runs)+ if _prompt_fits(single_system_prompt, single_user_prompt):+ summary = await _run_structured_completion(+ client=client,+ model=model,+ system_prompt=single_system_prompt,+ user_prompt=single_user_prompt,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ response_model=EvaluationSummaryResponse,+ schema_name="evaluation_summary",+ )+ summary.statistics = statistics+ return summary++ map_system_prompt = load_summarization_template("prompts/evaluation_summary_map.djt", prompt_context)+ chunks = _build_bounded_chunks(+ evaluation_runs,+ max_prompt_chars=_available_user_prompt_chars(map_system_prompt),+ )+ llm_call_semaphore = asyncio.Semaphore(EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS)++ async def summarize_chunk(chunk: list[dict]) -> EvaluationSummaryMapResponse:+ async with llm_call_semaphore:+ return await _run_map_completion(+ client=client,+ model=model,+ system_prompt=map_system_prompt,+ evaluation_runs=chunk,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ )++ batch_candidates = list(await asyncio.gather(*(summarize_chunk(chunk) for chunk in chunks)))+ summary = await _merge_summaries(+ client=client,+ model=model,+ batch_candidates=batch_candidates,+ statistics=statistics,+ prompt_context=prompt_context,+ team_id=team_id,+ user_distinct_id=user_distinct_id,+ llm_call_semaphore=llm_call_semaphore,+ )+ summary.statistics = statistics+ return summary+async def summarize_evaluation_runs(evaluation_runs: list[dict],@@ -30,6 +564,9 @@ async def summarize_evaluation_runs("""Generate summary of evaluation runs using LLM gateway with structured outputs.+ Runs are summarized in a single call when small. Larger sets use bounded map+ calls and hierarchical reduction so each request stays below the prompt limit.+Args:evaluation_runs: List of dicts with 'generation_id' (str), 'result' (bool or None), and 'reasoning' (str)team_id: Team ID for logging and tracking@@ -46,88 +583,20 @@ async def summarize_evaluation_runs(if not evaluation_runs:raise exceptions.ValidationError("No evaluation runs provided")- def result_label(result: bool | None) -> str:- if result is None:- return "N/A"- return "PASS" if result else "FAIL"-- # Format the evaluation runs for the prompt (include generation_id so LLM can reference them)- runs_text = "\n\n".join(- [- f"- Generation ID: {run['generation_id']}\n Result: {result_label(run['result'])}\n Reasoning: {run['reasoning']}"- for run in evaluation_runs- ]- )-- # Count statistics for the prompt- pass_count = sum(1 for run in evaluation_runs if run["result"] is True)- fail_count = sum(1 for run in evaluation_runs if run["result"] is False)- na_count = sum(1 for run in evaluation_runs if run["result"] is None)-- system_prompt = load_summarization_template(- "prompts/evaluation_summary.djt",- {- "filter": filter_type,- "evaluation_name": evaluation_name,- "evaluation_description": evaluation_description,- "evaluation_prompt": evaluation_prompt,- },- )- stats_parts = []- if pass_count > 0:- stats_parts.append(f"{pass_count} passed")- if fail_count > 0:- stats_parts.append(f"{fail_count} failed")- if na_count > 0:- stats_parts.append(f"{na_count} N/A")- stats_text = ", ".join(stats_parts) if stats_parts else "no results"-- user_prompt = f"""Analyze these {len(evaluation_runs)} evaluation results ({stats_text}):--{runs_text}"""-- client = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")-- messages: list[ChatCompletionMessageParam] = [- {"role": "system", "content": system_prompt},- {"role": "user", "content": user_prompt},- ]-try:- response = await client.chat.completions.create(- model=str(model),- messages=messages,- user=user_distinct_id or "llma-evaluation-summarization",- timeout=SUMMARIZATION_TIMEOUT,- response_format=cast(- Any,- {- "type": "json_schema",- "json_schema": {- "name": "evaluation_summary",- "strict": True,- "schema": EvaluationSummaryResponse.model_json_schema(),- },- },- ),- )-- content = response.choices[0].message.content- if not content:- logger.error(- "evaluation_summary_empty_response",+ async with _team_generation_lock(team_id):+ return await _generate_evaluation_summary(+ evaluation_runs=evaluation_runs,team_id=team_id,- model=str(model),+ model=model,+ filter_type=filter_type,+ evaluation_name=evaluation_name,+ evaluation_description=evaluation_description,+ evaluation_prompt=evaluation_prompt,+ user_distinct_id=user_distinct_id,)- raise exceptions.APIException("Failed to generate evaluation summary: empty response")-- return EvaluationSummaryResponse.model_validate_json(content)-- except Exception as e:- logger.exception(- "evaluation_summary_failed",- team_id=team_id,- model=str(model),- error=str(e),- )- raise exceptions.APIException("Failed to generate evaluation summary") from e+ except exceptions.APIException:+ raise+ except Exception as error:+ logger.exception("evaluation_summary_failed", team_id=team_id, model=str(model), error=str(error))+ raise exceptions.APIException("Failed to generate evaluation summary") from errordiff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djtnew file mode 100644index 000000000000..09b5198d8856--- /dev/null+++ b/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djt@@ -0,0 +1,40 @@+You are analyzing one batch from a larger AI observability evaluation. Extract evidence-rich candidate themes for a later reducer to consolidate across all batches.++## Evaluation Context++**Evaluation Name:** {{ evaluation_name }}+{% if evaluation_description %}+**Description:** {{ evaluation_description }}+{% endif %}++**Evaluation criteria:**+```+{{ evaluation_prompt }}+```++## Your task++Partition the runs in this batch into semantically equivalent candidate themes. Each run must contribute to exactly one candidate in its result category, so occurrence counts remain additive and the number of candidates never exceeds the number of runs.++For every candidate:+- Set result to "pass", "fail", or "na" based on the runs in that candidate.+- Include the exact number of matching runs in occurrence_count.+- Preserve 1-3 real generation IDs and one concise representative reasoning example.+- Keep the title concise enough for comparison with candidates from other batches.+- Include every distinct candidate supported by the batch, even when only one run supports it. A theme that is rare locally may be common across the complete evaluation.++Return at most {{ max_candidates }} candidates total.++Do not write an overall assessment, recommendations, global frequency labels, or statistics. The reducer derives those from candidates across every batch.++{% if filter == 'all' %}+Extract pass, fail, and N/A candidates where present.+{% elif filter == 'pass' %}+Every candidate must have result "pass".+{% elif filter == 'fail' %}+Every candidate must have result "fail".+{% elif filter == 'na' %}+Every candidate must have result "na".+{% endif %}++Do not invent generation IDs or evidence that is not present in this batch.diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djtnew file mode 100644index 000000000000..17df141c25e5--- /dev/null+++ b/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djt@@ -0,0 +1,39 @@+You are an expert at analyzing AI observability evaluation results. One or more reduction steps have produced evidence-rich candidate themes. Consolidate them into a single coherent summary of the whole evaluation.++## Evaluation Context++**Evaluation Name:** {{ evaluation_name }}+{% if evaluation_description %}+**Description:** {{ evaluation_description }}+{% endif %}++**Evaluation criteria:**+```+{{ evaluation_prompt }}+```++## Your task++You are given ground-truth statistics for the complete evaluation and candidate themes selected across all batches. Every candidate has a result category, an occurrence_count, example reasoning, and real generation IDs.++Consolidate them into ONE final summary:+- Merge candidates that describe the same underlying theme, even when their wording differs. Sum their occurrence_count values and combine representative generation IDs (keep 1-5 per pattern).+- Judge each merged pattern's frequency from its summed occurrence count relative to the complete number of runs in that result category: "common" (majority), "occasional" (several but not a majority), or "rare" (few). Do not infer frequency from the number of batches containing it.+- Write a single overall_assessment (1-2 sentences) reflecting the full evaluation, not any single batch.+- Derive the 2-4 most important actionable recommendations from the merged evidence.++{% if filter == 'all' %}+Keep patterns in all three categories (pass, fail, N/A) where present.+{% elif filter == 'pass' %}+Only pass_patterns are relevant. Leave fail_patterns and na_patterns as empty arrays.+{% elif filter == 'fail' %}+Only fail_patterns are relevant. Leave pass_patterns and na_patterns as empty arrays.+{% elif filter == 'na' %}+Only na_patterns are relevant. Leave pass_patterns and fail_patterns as empty arrays.+{% endif %}++IMPORTANT GUIDELINES:+- Limit to 0-4 patterns per category after merging.+- Preserve real example_generation_ids and example reasoning from the candidates; do not invent new evidence.+- Recommendations should be specific and actionable (2-4 total).+- The statistics you return are not used and may be left as zeros; the caller computes the ground-truth counts.diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djtnew file mode 100644index 000000000000..344e36459831--- /dev/null+++ b/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djt@@ -0,0 +1,21 @@+You are consolidating candidate themes from several batches of an AI observability evaluation. Produce a smaller set of evidence-rich candidates for another reduction step.++## Evaluation context++**Evaluation name:** {{ evaluation_name }}+{% if evaluation_description %}+**Description:** {{ evaluation_description }}+{% endif %}++**Evaluation criteria:**+```+{{ evaluation_prompt }}+```++## Your task++Merge candidates that describe the same underlying theme, even when their wording differs. Sum occurrence_count for merged candidates and preserve 1-3 real generation IDs plus one representative reasoning example.++Return at most {{ max_candidates_per_result }} candidates per result category. Every input occurrence_count must contribute to exactly one output candidate in the same result category. When distinct themes cannot all be retained, combine the lower-priority themes under a broader candidate instead of dropping their counts.++Do not write an overall assessment, recommendations, frequency labels, or statistics. Do not invent generation IDs or evidence.diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.pyindex 045b10415b94..39a42906e274 100644--- a/products/ai_observability/backend/summarization/tests/test_providers.py+++ b/products/ai_observability/backend/summarization/tests/test_providers.py@@ -1,12 +1,18 @@+import reimport jsonimport asyncio+from typing import Anyimport pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom rest_framework import exceptions-from products.ai_observability.backend.summarization.constants import SUMMARIZATION_TIMEOUT+from products.ai_observability.backend.summarization.constants import (+ EVALUATION_SUMMARY_MAX_RUNS,+ EVALUATION_SUMMARY_PROMPT_MAX_CHARS,+ SUMMARIZATION_TIMEOUT,+)from products.ai_observability.backend.summarization.llm.evaluation_summary import summarize_evaluation_runsfrom products.ai_observability.backend.summarization.llm.openai import summarize_with_openaifrom products.ai_observability.backend.summarization.llm.schema import SummarizationResponse@@ -198,6 +204,191 @@ class TestSummarizeEvaluationRuns:)mock_builder.assert_called_once_with("llma_eval_summary", ai_product="aio_eval_summary")- # timeout moved off the client constructor onto the per-call create()assert mock_client.chat.completions.create.call_args.kwargs["timeout"] == SUMMARIZATION_TIMEOUTassert result.overall_assessment == "Mostly passing."++ def test_concurrent_requests_are_limited_per_team(self, valid_evaluation_summary_json: str) -> None:+ mock_response = MagicMock()+ mock_response.choices = [MagicMock()]+ mock_response.choices[0].message.content = valid_evaluation_summary_json++ async def run_summaries() -> None:+ first_call_started = asyncio.Event()+ release_first_call = asyncio.Event()+ completion_count = 0++ async def completion(**_kwargs: Any) -> MagicMock:+ nonlocal completion_count+ completion_count += 1+ if completion_count == 1:+ first_call_started.set()+ await release_first_call.wait()+ return mock_response++ with patch(+ "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"+ ) as mock_builder:+ mock_client = MagicMock()+ mock_client.chat.completions.create = AsyncMock(side_effect=completion)+ mock_builder.return_value = mock_client++ first_summary = asyncio.create_task(+ summarize_evaluation_runs(+ evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],+ team_id=1,+ model=OpenAIModel.GPT_4_1_MINI,+ )+ )+ await first_call_started.wait()++ try:+ with pytest.raises(exceptions.Throttled, match="already being generated"):+ await summarize_evaluation_runs(+ evaluation_runs=[{"generation_id": "g2", "result": True, "reasoning": "also good"}],+ team_id=1,+ model=OpenAIModel.GPT_4_1_MINI,+ )++ different_team_result = await summarize_evaluation_runs(+ evaluation_runs=[{"generation_id": "g3", "result": True, "reasoning": "good"}],+ team_id=2,+ model=OpenAIModel.GPT_4_1_MINI,+ )+ assert different_team_result.overall_assessment == "Mostly passing."+ finally:+ release_first_call.set()+ await first_summary++ assert mock_client.chat.completions.create.await_count == 2++ asyncio.run(run_summaries())++ def test_large_run_set_bounds_every_request_and_retries_incomplete_maps(self) -> None:+ def response_with_content(content: str) -> MagicMock:+ response = MagicMock()+ response.choices = [MagicMock()]+ response.choices[0].message.content = content+ return response++ merged_response = response_with_content(+ json.dumps(+ {+ "overall_assessment": "The only failures were unsupported factual claims.",+ "pass_patterns": [],+ "fail_patterns": [],+ "na_patterns": [],+ "recommendations": ["Require citations for factual claims."],+ "statistics": {"total_analyzed": 0, "pass_count": 0, "fail_count": 0, "na_count": 0},+ }+ )+ )++ run_count = EVALUATION_SUMMARY_MAX_RUNS+ runs = [+ {+ "generation_id": f"g{i}",+ "result": i % 2 == 0,+ "reasoning": f"Distinct reasoning for run {i}. " + "r" * 2_000,+ }+ for i in range(run_count)+ ]++ returned_incomplete_map = False++ def completion_response(**kwargs: Any) -> MagicMock:+ nonlocal returned_incomplete_map+ schema_name = kwargs["response_format"]["json_schema"]["name"]+ if schema_name == "evaluation_summary":+ return merged_response++ user_prompt = kwargs["messages"][1]["content"]+ if schema_name == "evaluation_summary_candidates":+ if not returned_incomplete_map:+ returned_incomplete_map = True+ return response_with_content(json.dumps({"patterns": []}))++ prompt_runs = re.findall(r"- Generation ID: (.+)\n Result: (PASS|FAIL|N/A)", user_prompt)+ return response_with_content(+ json.dumps(+ {+ "patterns": [+ {+ "result": {"PASS": "pass", "FAIL": "fail", "N/A": "na"}[result],+ "title": f"Theme for {generation_id}".ljust(60, "x"),+ "occurrence_count": 1,+ "example_reasoning": f"Reasoning for {generation_id}".ljust(240, "r"),+ "example_generation_ids": [generation_id],+ }+ for generation_id, result in prompt_runs+ ]+ }+ )+ )++ candidates = json.loads(user_prompt.split("Candidate themes to consolidate:\n", 1)[1])+ reduced_candidates = []+ for result in ("pass", "fail", "na"):+ matching_candidates = [candidate for candidate in candidates if candidate["result"] == result]+ if matching_candidates:+ representative = {+ **matching_candidates[0],+ "occurrence_count": sum(candidate["occurrence_count"] for candidate in matching_candidates),+ "example_generation_ids": [+ generation_id+ for candidate in matching_candidates+ for generation_id in candidate["example_generation_ids"]+ ][:3],+ }+ reduced_candidates.append(representative)+ return response_with_content(json.dumps({"patterns": reduced_candidates}))++ with patch(+ "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"+ ) as mock_builder:+ mock_client = MagicMock()+ mock_client.chat.completions.create = AsyncMock(side_effect=completion_response)+ mock_builder.return_value = mock_client++ result = asyncio.run(+ summarize_evaluation_runs(+ evaluation_runs=runs,+ team_id=1,+ model=OpenAIModel.GPT_4_1_MINI,+ )+ )++ all_calls = mock_client.chat.completions.create.await_args_list+ map_calls = [+ call+ for call in all_calls+ if call.kwargs["response_format"]["json_schema"]["name"] == "evaluation_summary_candidates"+ ]+ reduce_calls = [+ call+ for call in all_calls+ if call.kwargs["response_format"]["json_schema"]["name"] == "evaluation_summary_reduced_candidates"+ ]++ assert returned_incomplete_map+ assert len(map_calls) == len({call.kwargs["messages"][1]["content"] for call in map_calls}) + 1+ assert reduce_calls+ for completion_call in all_calls:+ messages = completion_call.kwargs["messages"]+ assert sum(len(message["content"]) for message in messages) <= EVALUATION_SUMMARY_PROMPT_MAX_CHARS++ for map_call in map_calls:+ user_prompt = map_call.kwargs["messages"][1]["content"]+ response_schema = map_call.kwargs["response_format"]["json_schema"]["schema"]+ candidate_properties = response_schema["$defs"]["EvaluationPatternCandidate"]["properties"]++ assert response_schema["properties"]["patterns"]["maxItems"] == user_prompt.count("- Generation ID:")+ assert candidate_properties["occurrence_count"]["maximum"] == user_prompt.count("- Generation ID:")+ assert "maxLength" in candidate_properties["title"]+ assert "maxLength" in candidate_properties["example_reasoning"]+ assert "maxItems" in candidate_properties["example_generation_ids"]++ merge_user_prompt = all_calls[-1].kwargs["messages"][1]["content"]+ assert f'"total_analyzed":{run_count}' in merge_user_prompt+ assert result.statistics.total_analyzed == run_count+ assert result.statistics.pass_count == run_count // 2+ assert result.statistics.fail_count == run_count // 2diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 584dec3829ab..e00e548f5d97 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1498,6 +1498,20 @@ export interface EvaluationSummaryResponseApi {statistics: EvaluationSummaryStatisticsApi}+export interface EvaluationSummaryThrottleResponseApi {+ /** Error category */+ type: string+ /** Machine-readable error code */+ code: string+ /** Why the request was throttled */+ detail: string+ /**+ * Related request field, when applicable+ * @nullable+ */+ attr: string | null+}+export interface LLMModelInfoApi {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 727af513418f..e619ee4aef2e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26321,6 +26321,20 @@ export namespace Schemas {statistics: EvaluationSummaryStatistics;}+ export interface EvaluationSummaryThrottleResponse {+ /** Error category */+ type: string;+ /** Machine-readable error code */+ code: string;+ /** Why the request was throttled */+ detail: string;+ /**+ * Related request field, when applicable+ * @nullable+ */+ attr: string | null;+ }+export interface EventDefinitionBasic {id: string;name: string;