: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.abc import Sequence
from uuid import uuid4
from langchain_core.messages import (
HumanMessage as LangchainHumanMessage,
SystemMessage,
)
from langchain_core.runnables import RunnableConfig
from posthog.schema import AssistantMessage, HumanMessage
from ee.hogai.chat_agent.slash_commands.commands import SlashCommand
from ee.hogai.core.agent_modes.compaction_manager import AnthropicConversationCompactionManager
from ee.hogai.llm import MaxChatAnthropic
from ee.hogai.utils.types import AssistantMessageUnion, AssistantState, PartialAssistantState
from .prompts import SUPPORT_SUMMARIZER_SYSTEM_PROMPT, SUPPORT_SUMMARIZER_USER_PROMPT
from .transcript import customer_turns, render_transcript, strip_unverifiable_quotes
class TicketCommand(SlashCommand):
"""
Handles the /ticket slash command.
Summarizes the conversation for the frontend to use when creating a support ticket.
"""
_window_manager = AnthropicConversationCompactionManager()
async def execute(self, config: RunnableConfig, state: AssistantState) -> PartialAssistantState:
# Eligibility is enforced client-side (canCreateSupportTicket), like the support panel and its widget endpoint.
if self._is_first_message(state):
return PartialAssistantState(
messages=[
AssistantMessage(
content="I'll help you create a support ticket. Please describe your issue below.",
id=str(uuid4()),
)
]
)
messages_in_window = self._window_manager.get_messages_in_window(
state.messages, state.root_conversation_start_id
)
summary = await self._summarize_conversation(messages_in_window)
return PartialAssistantState(
messages=[
AssistantMessage(
content=summary,
id=str(uuid4()),
)
]
)
def _is_first_message(self, state: AssistantState) -> bool:
"""Check if /ticket is the first message in the conversation."""
human_messages = [msg for msg in state.messages if isinstance(msg, HumanMessage)]
return len(human_messages) <= 1
def _get_model(self) -> MaxChatAnthropic:
# We are not billing for conversation summary since we would be billing per-ticket creation.
# Needs a 1M-context model because this summarizes the whole conversation window, which can
# hold up to CONVERSATION_WINDOW_SIZE tokens.
return MaxChatAnthropic(
model="claude-sonnet-5",
streaming=True,
stream_usage=True,
user=self._user,
team=self._team,
max_tokens=2048,
# Sonnet 5 thinks by default and `max_tokens` covers thinking plus response together,
# so leaving it on would let thinking eat the summary's budget.
thinking={"type": "disabled"},
billable=False,
# The project/org/user context is about answering questions in-app, down to URL
# formatting, none of which applies to writing a ticket description.
inject_context=False,
)
async def _summarize_conversation(self, messages: Sequence[AssistantMessageUnion]) -> str:
"""Summarize the conversation for the support ticket."""
summarization_header = "PostHog AI Support Ticket Summary"
transcript = render_transcript(messages)
messages_list: list[SystemMessage | LangchainHumanMessage] = [
SystemMessage(content=SUPPORT_SUMMARIZER_SYSTEM_PROMPT),
LangchainHumanMessage(
content=f"<transcript>\n{transcript}\n</transcript>\n\n{SUPPORT_SUMMARIZER_USER_PROMPT}"
),
]
response = await self._get_model().ainvoke(messages_list)
content = response.content
if isinstance(content, list):
content = "".join(str(item) for item in content)
verified = strip_unverifiable_quotes(content, customer_turns(messages))
return f"{summarization_header}:\n\n{verified}"