: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
import uuid
import asyncio
from dataclasses import dataclass
from datetime import datetime, timedelta
from math import ceil
from django.conf import settings
from django.utils.timezone import now
import structlog
from google.genai import Client
from google.genai.errors import APIError
from google.genai.types import Blob, Content, Part, VideoMetadata
from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
from posthog.models.user import User
from posthog.settings.temporal import TEMPORAL_WORKFLOW_MAX_ATTEMPTS
from posthog.storage import object_storage
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
from posthog.temporal.session_replay.rasterize_recording.types import (
RASTERIZE_WORKFLOW_TIMEOUT,
RasterizeRecordingInputs,
)
from products.exports.backend.models.exported_asset import ExportedAsset
from ee.hogai.videos.constants import (
DEFAULT_VIDEO_UNDERSTANDING_MODEL,
MOMENT_VIDEO_EXPORT_FORMAT,
SHORT_VALIDATION_VIDEO_PLAYBACK_SPEED,
)
logger = structlog.get_logger(__name__)
@dataclass(frozen=True)
class SessionMomentInput:
# ID to identify the moment in mappings (for example, event_uuid)
moment_id: str
# Timestamp to start the video from
timestamp_s: int
# How long the video should be
duration_s: int
# Prompt to validate the moment
prompt: str
@dataclass(frozen=True)
class SessionMomentOutput(SessionMomentInput):
# Asset ID of the stored video
asset_id: int
# Description of the moment, generated by LLM
video_description: str
# When the video was created
created_at: datetime
# When the video will expire
expires_after: datetime
# What model was used to analyze the video
model_id: str
class SessionMomentsLLMAnalyzer:
"""Generate videos for Replay session events and analyze them with LLM"""
def __init__(self, session_id: str, team_id: int, user: User, trace_id: str | None = None):
self.session_id = session_id
self.team_id = team_id
self.user = user
self.trace_id = trace_id
self._provider = GeminiVideoUnderstandingProvider(model_id=DEFAULT_VIDEO_UNDERSTANDING_MODEL)
async def analyze(
self, moments_input: list[SessionMomentInput], expires_after_days: int, failed_moments_min_ratio: float
) -> list[SessionMomentOutput]:
"""
Analyze the session moments with LLM and return mapping of moment_id to LLM analysis
Args:
moments_input: List of session moments to analyze
expires_after_days: For how long to store the videos. Depends on the use case.
failed_moments_min_ratio: If less than N% of moments were generated, fail the analysis. Depends on the use case.
"""
# Generate mapping of moments to moment ids
moment_id_to_moment = {moment.moment_id: moment for moment in moments_input}
# Generate mapping of created videos (asset IDs) to moment ids
moment_id_to_asset_id = await self._generate_videos_for_moments(
moments_input=moments_input,
expires_after_days=expires_after_days,
failed_moments_min_ratio=failed_moments_min_ratio,
)
# Analyze videos with LLM
results = await self._analyze_moment_videos_with_llm(
moment_id_to_asset_id=moment_id_to_asset_id,
moment_id_to_moment=moment_id_to_moment,
expires_after_days=expires_after_days,
)
return results
async def _generate_videos_for_moments(
self,
moments_input: list[SessionMomentInput],
expires_after_days: int,
failed_moments_min_ratio: float,
) -> dict[str, int]:
"""Generate videos for moments and return mapping of moment_id to asset_id"""
tasks = {}
async with asyncio.TaskGroup() as tg:
for moment in moments_input:
tasks[moment.moment_id] = tg.create_task(
self._generate_video_for_single_moment(moment=moment, expires_after_days=expires_after_days)
)
# Collect asset IDs
moment_to_asset_id: dict[str, int] = {}
for moment_id, task in tasks.items():
res: int | Exception = task.result()
if isinstance(res, Exception):
logger.exception(
f"Failed to generate video for moment {moment_id} from session {self.session_id} of team {self.team_id}: {res}"
)
# Not failing explicitly to avoid failing all the generations if one fails
continue
moment_to_asset_id[moment_id] = res
# Check if enough moments were generated
expected_min_moments = ceil(len(moments_input) * failed_moments_min_ratio)
if expected_min_moments > len(moment_to_asset_id):
exception_message = f"Not enough moments were generated for session {self.session_id} of team {self.team_id}: {len(moment_to_asset_id)} out of {len(moments_input)}, expected at least {expected_min_moments}"
logger.exception(exception_message)
# Remove all the generated videos to not bloat the database
asset_ids = list(moment_to_asset_id.values())
# nosemgrep: idor-lookup-without-team (internal AI pipeline, IDs from team-scoped context)
await ExportedAsset.objects.filter(id__in=asset_ids).adelete()
raise Exception(exception_message)
return moment_to_asset_id
async def _generate_video_for_single_moment(
self, moment: SessionMomentInput, expires_after_days: int
) -> int | Exception:
"""Generate a video for an event in Replay session and return the asset ID"""
try:
created_at = now()
expires_after = created_at + timedelta(days=expires_after_days)
exported_asset = await ExportedAsset.objects.acreate(
team_id=self.team_id,
export_format=MOMENT_VIDEO_EXPORT_FORMAT,
export_context={
"session_recording_id": self.session_id,
"timestamp": moment.timestamp_s,
"duration": moment.duration_s,
"playback_speed": SHORT_VALIDATION_VIDEO_PLAYBACK_SPEED,
"show_metadata_footer": True,
},
created_by=self.user,
created_at=created_at,
expires_after=expires_after,
is_system=True,
)
# Generate a video through Temporal workflow
client = await async_connect()
await client.execute_workflow(
"rasterize-recording",
RasterizeRecordingInputs(exported_asset_id=exported_asset.id),
id=f"session-moment-video-export_{self.session_id}_{moment.moment_id}_{uuid.uuid4()}",
task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=int(TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
execution_timeout=RASTERIZE_WORKFLOW_TIMEOUT,
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=self.team_id),
SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=self.session_id),
]
),
)
# Return the asset ID for later retrieval
return exported_asset.id
except Exception as err: # Workflow retries exhausted
# Let caller handle the error
return err
async def _get_video_bytes(self, asset_id: int) -> bytes | None:
"""Retrieve video content as bytes for an ExportedAsset ID"""
try:
content: bytes | None = None
# Fetch the asset from the database
# nosemgrep: idor-lookup-without-team (asset_id from internal _export_moment_video, not user input)
asset = await ExportedAsset.objects.aget(id=asset_id)
# Get content from either database or object storage
if asset.content:
# Content stored directly in database
content = bytes(asset.content)
elif asset.content_location:
# Content stored in object storage
content = await database_sync_to_async(object_storage.read_bytes, thread_sensitive=False)(
asset.content_location
)
if not content:
logger.exception(
f"No content found for asset {asset_id} for session {self.session_id} "
f"of team {self.team_id} when validating session summaries"
)
raise ExportedAsset.DoesNotExist
return content
except ExportedAsset.DoesNotExist:
return None
async def _analyze_single_moment_video_with_llm(
self,
asset_id: int,
moment_id: str,
prompt: str,
) -> str | None | Exception:
"""Analyze a moment video with LLM"""
try:
# Not chunking bytes, as even with 300 sessions at once it's 100MB memory tops
video_bytes = await self._get_video_bytes(asset_id=asset_id)
if not video_bytes:
logger.warning(
f"No video bytes found for asset {asset_id} for moment {moment_id} of session {self.session_id} of team {self.team_id}"
)
return None
# Analyze the video with LLM — no start_offset needed since the rasterizer
# produces clean videos without warm-up periods
content = await self._provider.understand_video(
video_bytes=video_bytes,
mime_type=MOMENT_VIDEO_EXPORT_FORMAT,
prompt=prompt,
trace_id=self.trace_id,
)
if not content:
logger.warning(
f"No LLM content found for moment {moment_id} of session {self.session_id} of team {self.team_id}"
)
return None
return content
except Exception as err:
logger.exception(
f"Failed to analyze moment video {moment_id} of session {self.session_id} of team {self.team_id} with LLM: {err}"
)
# If the LLM validation fails - ensure to remove the generated video to not bloat the database,
# as it would be linked to the summary (to reuse) only after the LLM video validation is completed
# nosemgrep: idor-lookup-without-team (internal AI pipeline, IDs from team-scoped context)
await ExportedAsset.objects.filter(id=asset_id).adelete()
return err # Let caller handle the error
async def _analyze_moment_videos_with_llm(
self,
moment_id_to_asset_id: dict[str, int],
moment_id_to_moment: dict[str, SessionMomentInput],
expires_after_days: int,
) -> list[SessionMomentOutput]:
"""Send videos to LLM for validation and get analysis results"""
tasks = {}
async with asyncio.TaskGroup() as tg:
for moment_id, asset_id in moment_id_to_asset_id.items():
prompt = moment_id_to_moment[moment_id].prompt
tasks[moment_id] = tg.create_task(
self._analyze_single_moment_video_with_llm(asset_id=asset_id, moment_id=moment_id, prompt=prompt)
)
results: list[SessionMomentOutput] = []
for moment_id, task in tasks.items():
res = task.result()
if isinstance(res, Exception):
logger.exception(
f"Failed to analyze moment video {moment_id} of session {self.session_id} of team {self.team_id} with LLM: {res}"
)
continue
if not res:
continue
moment = moment_id_to_moment[moment_id]
created_at = now()
expires_after = created_at + timedelta(days=expires_after_days)
output = SessionMomentOutput(
moment_id=moment.moment_id,
timestamp_s=moment.timestamp_s,
duration_s=moment.duration_s,
prompt=moment.prompt,
asset_id=moment_id_to_asset_id[moment_id],
video_description=res,
created_at=created_at,
expires_after=expires_after,
model_id=self._provider.model_id,
)
results.append(output)
# No additional check for how many moments were analyzed as they can be limited by video size
return results
class GeminiVideoUnderstandingProvider:
"""Interface for Gemini video understanding"""
# https://ai.google.dev/gemini-api/docs/video-understanding#supported-formats
SUPPORTED_VIDEO_MIME_TYPES: list[str] = [
"video/x-flv",
"video/quicktime",
"video/mpeg",
"video/mpegs",
"video/mpg",
"video/mp4",
"video/webm",
"video/wmv",
"video/3gpp",
]
VIDEO_MAX_SIZE_BYTES = 20 * 1024 * 1024 # 20MB
def __init__(self, model_id: str):
self.model_id = model_id
api_key = settings.GEMINI_API_KEY
if not api_key:
raise ValueError("GEMINI_API_KEY is not set in environment or settings")
# Using default Gemini client as workaround, as PostHog wrapper doesn't support async yet
self.client = Client(api_key=api_key)
async def understand_video(
self,
video_bytes: bytes,
mime_type: str,
prompt: str,
start_offset_s: int | None = None,
end_offset_s: int | None = None,
trace_id: str | None = None,
) -> str | None:
"""
Understand a video and return a summary using the provided prompt
https://ai.google.dev/gemini-api/docs/video-understanding
"""
if mime_type not in self.SUPPORTED_VIDEO_MIME_TYPES:
logger.exception(
f"Video bytes for understanding video are not in a supported MIME type (trace_id:{trace_id}): {mime_type}"
)
return None
if not len(video_bytes):
logger.exception(f"Video bytes for understanding video are empty (trace_id: {trace_id})")
return None
if len(video_bytes) > self.VIDEO_MAX_SIZE_BYTES:
logger.exception(f"Video bytes for understanding video are too large (trace_id: {trace_id})")
return None
try:
video_metadata_config = {}
if start_offset_s:
video_metadata_config["start_offset"] = f"{start_offset_s}s"
if end_offset_s:
video_metadata_config["end_offset"] = f"{end_offset_s}s"
video_part = Part(
inline_data=Blob(data=video_bytes, mime_type=mime_type),
video_metadata=VideoMetadata(**video_metadata_config) if video_metadata_config else None,
)
prompt_part = Part(text=prompt)
contents = Content(parts=[video_part, prompt_part])
response = await self.client.aio.models.generate_content(
model=self.model_id,
contents=contents,
# Add trace ID, when PostHog wrapper supports async
)
return response.text
except APIError as e:
logger.exception(f"Gemini API error while understanding video (trace_id: {trace_id}): {e}")
return None
except Exception as e:
logger.exception(f"Unexpected error while understanding video (trace_id: {trace_id}): {e}")
return None