: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
from collections import Counter
from datetime import datetime
import structlog
from openai import OpenAI
from posthog.schema import SurveyQuestionType
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.api.utils import ServerTimingsGathered
from posthog.hogql_queries.paginators import HogQLHasMorePaginator
from posthog.llm.gateway_client import build_openai_client, resolve_ai_gateway_config
from posthog.models import Team, User
from products.surveys.backend.models import Survey
from products.surveys.backend.responses.fetch_rows import RESPONSE_EVENT_FILTER, SUBMISSION_GROUPING_KEY
from products.surveys.backend.util import get_archived_response_uuids, get_survey_response_clickhouse_query
logger = structlog.get_logger(__name__)
RESPONSE_LIMIT = 100
HEADLINE_SYSTEM_PROMPT = """You are a product manager's assistant. You create concise one-line summaries of survey feedback.
You don't do any other tasks."""
HEADLINE_USER_PROMPT = """Based on the survey data below, generate a single sentence (max 20 words) that captures the main theme or sentiment.
Be specific and actionable. No markdown, no bullet points, just one plain sentence.
Survey: {survey_name}
{formatted_data}"""
def _extract_values(rows: list, col_idx: int, is_multiple_choice: bool) -> list[str]:
values: list[str] = []
for row in rows:
val = row[col_idx]
if not val:
continue
if is_multiple_choice and isinstance(val, list):
values.extend(s for v in val if v and (s := str(v).strip()))
elif s := str(val).strip():
values.append(s)
return values
def _format_question_summary(question: dict, values: list[str]) -> str:
q_text = question.get("question", "Unknown question")
q_type = question.get("type", "")
if not values:
return f'"{q_text}": No responses'
if q_type == SurveyQuestionType.OPEN:
lines = [f'"{q_text}" ({len(values)} responses):']
lines.extend(f" - {v}" for v in values)
return "\n".join(lines)
if q_type == SurveyQuestionType.RATING:
nums = [float(v) for v in values if v.replace(".", "", 1).isdigit()]
if nums:
scale = question.get("scale", 5)
avg = round(sum(nums) / len(nums), 1)
return f'"{q_text}": Average {avg}/{scale} ({len(nums)} responses)'
return f'"{q_text}": {len(values)} responses'
if q_type == SurveyQuestionType.SINGLE_CHOICE or q_type == SurveyQuestionType.MULTIPLE_CHOICE:
counter = Counter(values)
lines = [f'"{q_text}" ({len(values)} responses):']
for choice, cnt in counter.most_common():
pct = round(cnt / len(values) * 100)
lines.append(f" - {choice}: {pct}%")
return "\n".join(lines)
return f'"{q_text}": {len(values)} responses'
def generate_survey_headline(
survey: Survey,
team: Team,
user: User,
) -> dict:
"""Generate a one-line headline summary of all survey responses."""
logger.info("[survey_headline_summary] generating headline", survey_id=str(survey.id))
timer = ServerTimingsGathered()
# we want to ignore link questions, but need to preserve the indices
questions_with_idx = [
(i, q) for i, q in enumerate(survey.questions or []) if q.get("type", "").lower() != SurveyQuestionType.LINK
]
if not questions_with_idx:
return {
"headline": "No questions in survey",
"responses_sampled": 0,
"has_more": False,
"timings_header": timer.to_header_string(),
}
start_date = (survey.start_date or survey.created_at).replace(hour=0, minute=0, second=0, microsecond=0)
end_date = (survey.end_date or datetime.now()).replace(hour=23, minute=59, second=59, microsecond=0)
select_fields = []
merged_fields = []
for orig_idx, q in questions_with_idx:
is_multiple_choice = q.get("type", "").lower() == SurveyQuestionType.MULTIPLE_CHOICE
field = get_survey_response_clickhouse_query(orig_idx, q.get("id"), is_multiple_choice)
select_fields.append(f"{field} as q{orig_idx}")
presence = f"length(q{orig_idx}) > 0" if is_multiple_choice else f"isNotNull(q{orig_idx})"
merged_fields.append(f"argMaxIf(q{orig_idx}, timestamp, {presence}) as answer_{orig_idx}")
# Get archived response UUIDs to exclude
# UUIDs are pre-validated by Django's UUIDField when stored in SurveyResponseArchive
archived_uuids = get_archived_response_uuids(survey.id, team.pk)
archived_filter = " HAVING response_uuid NOT IN {exclude_uuids}" if archived_uuids else ""
with timer("query"):
query = f"""
SELECT {", ".join(f"answer_{idx}" for idx, _ in questions_with_idx)}
FROM (
SELECT {", ".join(merged_fields)}, argMax(uuid, timestamp) as response_uuid,
max(timestamp) as submitted_at
FROM (
SELECT {", ".join(select_fields)}, uuid, timestamp,
{SUBMISSION_GROUPING_KEY} as submission_key
FROM events
WHERE {RESPONSE_EVENT_FILTER}
AND properties.$survey_id = {{survey_id}}
AND timestamp >= {{start_date}}
AND timestamp <= {{end_date}}
) GROUP BY submission_key
{archived_filter}
) ORDER BY submitted_at DESC
"""
placeholders: dict[str, ast.Expr] = {
"survey_id": ast.Constant(value=str(survey.id)),
"start_date": ast.Constant(value=start_date),
"end_date": ast.Constant(value=end_date),
}
if archived_uuids:
placeholders["exclude_uuids"] = ast.Tuple(exprs=[ast.Constant(value=uuid) for uuid in archived_uuids])
paginator = HogQLHasMorePaginator(limit=RESPONSE_LIMIT, offset=0)
result = paginator.execute_hogql_query(
team=team,
query_type="survey_headline_responses",
query=parse_select(query, placeholders=placeholders),
)
rows = result.results or []
has_more = paginator.has_more()
logger.info("[survey_headline_summary] queried responses", survey_id=str(survey.id), responses=len(rows))
if not rows:
return {
"headline": "No responses yet",
"responses_sampled": 0,
"has_more": False,
"timings_header": timer.to_header_string(),
}
formatted_parts = []
for col_idx, (_, question) in enumerate(questions_with_idx):
is_multiple_choice = question.get("type", "").lower() == SurveyQuestionType.MULTIPLE_CHOICE
values = _extract_values(rows, col_idx, is_multiple_choice)
formatted_parts.append(_format_question_summary(question, values))
formatted_data = "\n\n".join(formatted_parts)
with timer("llm"):
logger.info("[survey_headline_summary] starting LLM call", survey_id=str(survey.id))
try:
completion = _headline_client(survey, team, user).chat.completions.create(
model="gpt-4.1-mini",
temperature=0.3,
messages=[
{"role": "system", "content": HEADLINE_SYSTEM_PROMPT},
{
"role": "user",
"content": HEADLINE_USER_PROMPT.format(
survey_name=survey.name,
formatted_data=formatted_data,
),
},
],
user=user.distinct_id or "",
)
logger.info("[survey_headline_summary] LLM call completed", survey_id=str(survey.id))
content = completion.choices[0].message.content if completion.choices else None
headline = content.strip() if content else "Unable to generate summary"
except Exception as e:
logger.exception("[survey_headline_summary] LLM call failed", survey_id=str(survey.id), error=str(e))
raise
logger.info("[survey_headline_summary] headline generated", survey_id=str(survey.id), responses=len(rows))
return {
"headline": headline,
"responses_sampled": len(rows),
"has_more": has_more,
"timings_header": timer.to_header_string(),
}
def _headline_client(survey: Survey, team: Team, user: User) -> OpenAI:
if resolve_ai_gateway_config() is None:
return OpenAI()
client = build_openai_client(
product="django",
ai_product="surveys",
distinct_id=user.distinct_id,
properties={"ai_feature": "survey_headline", "survey_id": str(survey.id), "team_id": str(team.id)},
)
return client.with_options(default_headers={"X-PostHog-Billable": "false", "X-PostHog-Privacy-Mode": "true"})