:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): let gemini judges watch video (#126429)
Bernat Torresad2b8c07a665
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex 214f93384d47..5829646c31a7 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -47,6 +47,7 @@ Then each image becomes an `[image N]` marker and each PDF a `[file N]` marker iThe attachment labels sent next to the transcript sit outside the 150,000-character limit, but they are bounded: at most 20 attachments, plus one summary line for the rest.PDFs reach only OpenAI, Anthropic and Gemini judges, up to 10 MB each.WAV and MP3 audio becomes an `[audio N]` marker and reaches Gemini judges and OpenAI audio models, always inline.+MP4, MPEG, QuickTime and WebM video becomes a `[video N]` marker and reaches Gemini judges only, up to 15 MB each.Attachments a judge can't read take none of its 20 slots, and one summary line counts them.Generation evaluation and LLM tagger user prompts repair UTF-16 surrogate sequences after sampling.diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 9cb5a12ddbf9..f75364bfcfcd 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -450,6 +450,12 @@ def _build_unparsable_response_skip_result(_IMAGE_REJECTION_STATUSES = frozenset({400, 413, 415, 422})+_ATTACHMENTS_NOT_SENT_NOTE = (+ "The model provider rejected the attachments in this transcript, so none are attached. "+ "Judge from the text only, and don't guess what an attachment contains."+)++class JudgeAttachmentsRejectedError(Exception):"""Reported without the provider's message, which can quote a live presigned link."""@@ -891,15 +897,17 @@ def call_llm_judge("provider": provider,"model": model,"status": status,- "sent_pdfs": any(isinstance(part, AttachmentPart) and part.is_pdf for part in content),+ "sent_types": sorted({part.mime_type for part in content if isinstance(part, AttachmentPart)}),}logger.warning("judge_attachments_rejected", **context)if not is_byok:# On a PostHog key this can mean broken presigned links or a refused PDF, so keep it visible.capture_exception(- JudgeAttachmentsRejectedError(f"Provider rejected judge images ({status})"), context+ JudgeAttachmentsRejectedError(f"Provider rejected judge attachments ({status})"), context)- response = client.complete(replace(request, messages=[{"role": "user", "content": user_prompt}]))+ # Without the note a judge reads the transcript's [image] or [file] and guesses what it shows.+ retry_prompt = f"{_ATTACHMENTS_NOT_SENT_NOTE}\n\n{user_prompt}"+ response = client.complete(replace(request, messages=[{"role": "user", "content": retry_prompt}]))except (DecisionEndpointBlockedError, ProviderConfigurationError) as e:increment_user_errors("endpoint_blocked", provider=provider)return terminal_user_error_result(diff --git a/posthog/temporal/ai_observability/judge_attachments.py b/posthog/temporal/ai_observability/judge_attachments.pyindex ec6b971083e9..056f94dcf3eb 100644--- a/posthog/temporal/ai_observability/judge_attachments.py+++ b/posthog/temporal/ai_observability/judge_attachments.py@@ -20,9 +20,12 @@ from products.ai_observability.backend.llm.attachments import (IMAGE_MIME_TYPES,MAX_IMAGE_BYTES,MAX_PDF_BYTES,+ MAX_VIDEO_BYTES,PDF_MIME_TYPE,+ VIDEO_MIME_TYPES,AttachmentPart,attachment_transport,+ max_videos,)from products.ai_observability.backend.text_repr.formatters.media_blocks import MediaBlock, MediaMarker@@ -34,6 +37,8 @@ JUDGE_ATTACHMENTS_FLAG = "llm-analytics-judge-images"MAX_ATTACHMENTS = 20# Bytes sent inline in one judge request. Links don't count: the provider downloads them.MAX_INLINE_BYTES = 15_000_000+# Raw bytes per attachment for every provider. Audio only has the inline budget.+_BYTE_LIMITS = {"file": MAX_PDF_BYTES, "video": MAX_VIDEO_BYTES}# Covers the judge call and its retries. Sign right before the call: a link signed with temporary# AWS credentials stops working when the credentials expire.PRESIGNED_URL_SECONDS = 15 * 60@@ -46,7 +51,7 @@ _NOT_ATTACHED_LABELS: dict[Outcome, str] = {}-_NUMBERED_MARKER_RE = re.compile(r"\[(image|file|audio) \d+\]")+_NUMBERED_MARKER_RE = re.compile(r"\[(image|file|audio|video) \d+\]")@frozen@@ -70,7 +75,7 @@ class _Attachment:@frozenclass _Media:- kind: Literal["image", "file", "audio"]+ kind: Literal["image", "file", "audio", "video"]number: intmime_type: str# An offloaded image has a pointer, a small one stays inline as base64.@@ -128,15 +133,29 @@ class JudgeAttachments:readable = [image for image in images if attachment_transport(provider, model, image.mime_type) is not None]# Keep the images referenced last: the newest input and the graded output, even when it repeats an old image.ranked = sorted(readable, key=lambda image: user_prompt.rfind(image.marker))+ # Gemini rejects a request over its video limit, and the text-only retry would drop everything else too.+ video_slots = max_videos(model)+ kept: list[_Media] = []+ for image in reversed(ranked):+ if len(kept) == MAX_ATTACHMENTS:+ break+ if image.kind == "video":+ if video_slots == 0:+ continue+ video_slots -= 1+ kept.append(image)attachments: dict[str, _Attachment] = {}inline_bytes = 0- for image in reversed(ranked[-MAX_ATTACHMENTS:]):+ for image in kept:attachment = self._attach(image, provider, model, MAX_INLINE_BYTES - inline_bytes)inline_bytes += attachment.inline_bytesattachments[image.marker] = attachmentparts: list[Any] = [- {"type": "text", "text": "The transcript refers to these attachments as [image N], [file N] or [audio N]."}+ {+ "type": "text",+ "text": "The transcript refers to these attachments as [image N], [file N], [audio N] or [video N].",+ }]outcomes: Counter[str] = Counter()for image in images:@@ -166,7 +185,7 @@ class JudgeAttachments:transport = attachment_transport(provider, model, image.mime_type)if transport is None:return _Attachment(outcome="unavailable")- provider_limit = MAX_PDF_BYTES if image.kind == "file" else MAX_IMAGE_BYTES.get(provider)+ provider_limit = MAX_IMAGE_BYTES.get(provider) if image.kind == "image" else _BYTE_LIMITS.get(image.kind)if image.pointer is None:encoded = image.base64_data or ""if len(encoded) * 3 // 4 - encoded[-2:].count("=") > min(inline_budget, provider_limit or inline_budget):@@ -214,11 +233,13 @@ class JudgeAttachments:return _Attachment(outcome="inline", part=part, inline_bytes=stored_size)-def _kind(modality: str, mime_type: str | None) -> Literal["image", "file", "audio"] | None:+def _kind(modality: str, mime_type: str | None) -> Literal["image", "file", "audio", "video"] | None:if modality == "image" and mime_type in IMAGE_MIME_TYPES:return "image"if modality == "audio" and mime_type in AUDIO_FORMATS:return "audio"+ if modality == "video" and mime_type in VIDEO_MIME_TYPES:+ return "video"if mime_type == PDF_MIME_TYPE:return "file"return None@@ -229,6 +250,7 @@ _MIME_ALIASES = {"audio/mp3": "audio/mpeg","audio/x-wav": "audio/wav","audio/wave": "audio/wav",+ "video/mpg": "video/mpeg",}diff --git a/posthog/temporal/ai_observability/test_judge_attachments.py b/posthog/temporal/ai_observability/test_judge_attachments.pyindex d6d9b6d7d151..0d64a5be387b 100644--- a/posthog/temporal/ai_observability/test_judge_attachments.py+++ b/posthog/temporal/ai_observability/test_judge_attachments.py@@ -6,14 +6,19 @@ from unittest.mock import patchfrom posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.ai_observability.judge_attachments import MAX_ATTACHMENTS, JudgeAttachments-from products.ai_observability.backend.llm.attachments import MAX_IMAGE_BYTES, MAX_PDF_BYTES, AttachmentPart+from products.ai_observability.backend.llm.attachments import (+ MAX_IMAGE_BYTES,+ MAX_PDF_BYTES,+ MAX_VIDEO_BYTES,+ AttachmentPart,+)from products.ai_observability.backend.text_repr.formatters.media_blocks import MediaBlock, parse_media_blockOBJECT_STORAGE = "products.ai_observability.backend.ai_blobs.object_storage"def _pointer(digit: str, mime: str = "image%2Fjpeg") -> MediaBlock:- modality = "audio" if mime.startswith("audio") else "image"+ modality = next((kind for kind in ("audio", "video") if mime.startswith(kind)), "image")return MediaBlock(modality=modality, url=f"phaiblob://v1/sha256/{digit * 64}?mime={mime}&size=63357")@@ -136,6 +141,30 @@ class TestJudgeAttachmentsContent:AttachmentPart(mime_type="audio/wav", data=b"hi"),id="audio_inline_on_gemini",),+ pytest.param(+ "gemini",+ "gemini-3-flash",+ "video%2Fmp4",+ "Video 1:",+ AttachmentPart(mime_type="video/mp4", url="https://signed"),+ id="video_link_on_gemini",+ ),+ pytest.param(+ "gemini",+ "gemini-2.0-flash",+ "video%2Fmp4",+ "Video 1:",+ AttachmentPart(mime_type="video/mp4", data=b"hi"),+ id="video_inline_on_gemini_2_0",+ ),+ pytest.param(+ "anthropic",+ "claude-haiku-4-5",+ "video%2Fmp4",+ "Not attached, this judge can't read their file type: 1.",+ None,+ id="video_on_a_provider_without_video_input",+ ),pytest.param("openai","gpt-4o-audio-preview",@@ -184,7 +213,10 @@ class TestJudgeAttachmentsContent:content = images.content(prompt, provider, model)assert content == [- {"type": "text", "text": "The transcript refers to these attachments as [image N], [file N] or [audio N]."},+ {+ "type": "text",+ "text": "The transcript refers to these attachments as [image N], [file N], [audio N] or [video N].",+ },{"type": "text", "text": expected_label},*([expected_part] if expected_part else []),{"type": "text", "text": prompt},@@ -273,20 +305,50 @@ class TestJudgeAttachmentsContent:# An image over the budget is never downloaded.assert read.call_count == reads- def test_caps_pdf_bytes_on_links(self):+ @pytest.mark.parametrize(+ ("mime", "label", "limit"),+ [+ # Gemini's image limit is higher, so only the PDF cap can reject this one.+ pytest.param("application%2Fpdf", "File 1", MAX_PDF_BYTES, id="pdf"),+ pytest.param("video%2Fmp4", "Video 1", MAX_VIDEO_BYTES, id="video"),+ pytest.param("image%2Fpng", "Image 1", MAX_IMAGE_BYTES["gemini"], id="image"),+ ],+ )+ def test_caps_bytes_on_gemini_links(self, mime: str, label: str, limit: int):images = JudgeAttachments(team_id=7)- prompt = f"user: {images.marker(_pointer('a', mime='application%2Fpdf'))}"+ prompt = f"user: {images.marker(_pointer('a', mime=mime))}"with (patch(f"{OBJECT_STORAGE}.get_presigned_url", return_value="https://signed") as presign,- patch(f"{OBJECT_STORAGE}.head_object_strict", return_value={"ContentLength": MAX_PDF_BYTES + 1}),+ patch(f"{OBJECT_STORAGE}.head_object_strict", return_value={"ContentLength": limit + 1}),):- # Gemini has no image byte limit, so only the PDF cap can reject this one.content = images.content(prompt, "gemini", "gemini-3-flash")- assert {"type": "text", "text": "File 1: not attached, too large."} in content+ assert {"type": "text", "text": f"{label}: not attached, too large."} in contentpresign.assert_not_called()+ @pytest.mark.parametrize(("model", "attached"), [("gemini-2.5-flash", 10), ("gemini-2.0-flash", 1)])+ def test_keeps_the_newest_videos_within_the_gemini_limit(self, model: str, attached: int):+ images = JudgeAttachments(team_id=7)+ image = images.marker(_inline("aa"))+ videos = " ".join(+ images.marker(MediaBlock(modality="video", url=f"phaiblob://v1/sha256/{i:064x}?mime=video%2Fmp4"))+ for i in range(11)+ )++ with (+ patch(f"{OBJECT_STORAGE}.get_presigned_url", return_value="https://signed"),+ patch(f"{OBJECT_STORAGE}.head_object_strict", return_value={"ContentLength": 2}),+ patch(f"{OBJECT_STORAGE}.read_bytes", return_value=b"hi"),+ ):+ content = images.content(f"user: {image} {videos}", "gemini", model)++ labels = {part["text"] for part in content if isinstance(part, dict)}+ assert "Image 1:" in labels+ assert {f"Video {n}:" for n in range(12 - attached, 12)} <= labels+ assert f"Video {11 - attached}:" not in labels+ assert f"Not attached, over the judge's attachment limit: {11 - attached}." in labels+def test_attachments_the_judge_cannot_read_take_no_slot(self):images = JudgeAttachments(team_id=7)image = images.marker(_inline("aa"))diff --git a/posthog/temporal/ai_observability/test_message_utils.py b/posthog/temporal/ai_observability/test_message_utils.pyindex 78de7915e0f1..c3e1804d8449 100644--- a/posthog/temporal/ai_observability/test_message_utils.py+++ b/posthog/temporal/ai_observability/test_message_utils.py@@ -119,6 +119,12 @@ class TestExtractTextFromMessages:"[audio 1]",id="openai_audio_wav",),+ pytest.param({"inline_data": {"mime_type": "video/mp4", "data": "aGk="}}, "[video 1]", id="gemini_video"),+ pytest.param(+ {"type": "file", "mediaType": "video/mp4", "file": f"phaiblob://v1/sha256/{'c' * 64}?mime=video%2Fmp4"},+ "[video 1]",+ id="vercel_video",+ ),pytest.param({"type": "input_audio",diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 5282732d3575..04b485154e40 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -1203,7 +1203,9 @@ def test_judge_falls_back_to_the_plain_prompt_only_when_an_attached_image_is_rejif retries:assert result["verdict"] is True- assert client.complete.call_args_list[1].args[0].messages == [{"role": "user", "content": "user: Polite?"}]+ retry_content = client.complete.call_args_list[1].args[0].messages[0]["content"]+ assert retry_content.startswith("The model provider rejected the attachments")+ assert retry_content.endswith("user: Polite?")assert "https://signed" not in str(capture.call_args)assert active_errors == [None]else:diff --git a/products/ai_observability/backend/llm/attachments.py b/products/ai_observability/backend/llm/attachments.pyindex 6a43a21a2794..6dac120e9f9c 100644--- a/products/ai_observability/backend/llm/attachments.py+++ b/products/ai_observability/backend/llm/attachments.py@@ -9,19 +9,23 @@ IMAGE_MIME_TYPES = frozenset({"image/png", "image/jpeg", "image/webp", "image/giPDF_MIME_TYPE = "application/pdf"# The formats OpenAI's chat API takes as input audio, which Gemini reads too.AUDIO_FORMATS = {"audio/wav": "wav", "audio/mpeg": "mp3"}+# Only Gemini reads video.+VIDEO_MIME_TYPES = frozenset({"video/mp4", "video/mpeg", "video/quicktime", "video/webm"})# Providers whose image blocks take a link that they download themselves._URL_PROVIDERS = frozenset({"openai", "azure_openai", "anthropic", "openrouter", "gemini"})# Providers that read PDFs natively. OpenRouter is left out: it parses PDFs for other models with a paid OCR engine._PDF_PROVIDERS = frozenset({"openai", "anthropic", "gemini"})# Raw bytes per image. Anthropic allows 10 MB base64-encoded, about 7.5 MB raw, so keep a margin under it.-MAX_IMAGE_BYTES = {"anthropic": 7_000_000}+MAX_IMAGE_BYTES = {"anthropic": 7_000_000, "gemini": 15_000_000}# Raw bytes per PDF for every provider. Each page costs about as many tokens as an image, and links have no other cap.MAX_PDF_BYTES = 10_000_000+# Raw bytes per video. Gemini downloads links up to 15 MB, and inline bytes share the 15 MB request budget anyway.+MAX_VIDEO_BYTES = 15_000_000@frozenclass AttachmentPart:- """An image, PDF or audio clip in a message's content list. Each adapter converts it to its provider's block.+ """An image, PDF, audio clip or video in a message's content list. Each adapter converts it to its provider's block.Set `url` for a link the provider downloads, or `data` for inline bytes."""@@ -51,6 +55,11 @@ def attachment_transport(provider: str, model: str, mime_type: str) -> Literal["if mime_type in AUDIO_FORMATS:# OpenAI takes audio only as inline base64, and only on its audio models, so audio always goes inline.return "inline" if provider == "gemini" or openai_audio_model else None+ if mime_type in VIDEO_MIME_TYPES:+ if provider != "gemini":+ return None+ # The Gemini 2.0 family can't fetch external links.+ return "inline" if model.startswith("gemini-2.0") else "url"if openai_audio_model:# OpenAI's audio models reject images and PDFs, and the rejection would drop the audio too.return None@@ -70,6 +79,11 @@ def attachment_transport(provider: str, model: str, mime_type: str) -> Literal["return "url" if provider in _URL_PROVIDERS else "inline"+def max_videos(model: str) -> int:+ """Videos Gemini accepts in one request."""+ return 1 if model.startswith(("gemini-1.", "gemini-2.0")) else 10++def convert_attachment_parts(messages: list[dict[str, Any]], convert: Callable[[AttachmentPart], Any]) -> list[dict[str, Any]]:diff --git a/products/ai_observability/frontend/evaluations/create/EvaluationModelPanel.tsx b/products/ai_observability/frontend/evaluations/create/EvaluationModelPanel.tsxindex 4d9018869803..e4fd336525fe 100644--- a/products/ai_observability/frontend/evaluations/create/EvaluationModelPanel.tsx+++ b/products/ai_observability/frontend/evaluations/create/EvaluationModelPanel.tsx@@ -32,7 +32,10 @@ export function EvaluationModelPanel(): JSX.Element | null {</p></div>{featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_JUDGE_IMAGES] && !usesDecisionModel && (- <LemonField.Pure label="Attachments">+ <LemonField.Pure+ label="Attachments"+ info="If the judge can't take an attachment, it judges the text without it. This happens when the judge's model can't read the file type, when there are more than 20 attachments, or when the provider rejects a file, such as a PDF with too many pages."+ ><LemonSwitchchecked={includeMedia}onChange={setIncludeMedia}@@ -41,9 +44,9 @@ export function EvaluationModelPanel(): JSX.Element | null {data-attr="llma-evaluation-include-attachments"/><p className="text-muted text-sm">- The judge sees the images, PDFs and audio in what it evaluates. PDFs need an OpenAI, Anthropic- or Gemini judge, and audio a Gemini judge or an OpenAI audio model. Other file types are not- supported yet.+ The judge sees the images, PDFs, audio and video in what it evaluates. PDFs need an OpenAI,+ Anthropic or Gemini judge, audio a Gemini judge or an OpenAI audio model, and video a Gemini+ judge. Other file types are not supported yet.</p></LemonField.Pure>)}