Skip to content

: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.

feat(conversations): attribute ai-reply llm spend per ticket (#68879)

Alex Vdb8b134da190
diff --git a/products/conversations/backend/temporal/ai_reply/activities/classify.py b/products/conversations/backend/temporal/ai_reply/activities/classify.py
index 0364287a5b92..d53dde667471 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/classify.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/classify.py
@@ -9,7 +9,12 @@ from posthog.llm.gateway_client import get_async_anthropic_gateway_client
from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPES, UTILITY_MODEL
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, strip_json_fence
+from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_text,
+ create_message,
+ strip_json_fence,
+ tracing_kwargs,
+)
from products.conversations.backend.temporal.ai_reply.schemas import ClassifyInput, ClassifyOutput
logger = structlog.get_logger(__name__)
@@ -19,10 +24,10 @@ logger = structlog.get_logger(__name__)
async def support_classify_activity(input: ClassifyInput) -> ClassifyOutput:
"""One-shot LLM triage of a ticket into a type + diagnostics flag + seed search queries."""
async with Heartbeater():
- return await _classify(input.team_id, input.ticket_context)
+ return await _classify(input.team_id, input.ticket_context, input.trace_id, input.ticket_id)
-async def _classify(team_id: int, ticket_context: str) -> ClassifyOutput:
+async def _classify(team_id: int, ticket_context: str, trace_id: str = "", ticket_id: str = "") -> ClassifyOutput:
system = """You triage incoming customer support tickets for a product.
Classify the ticket into exactly one type and propose search queries to start retrieval.
@@ -51,6 +56,7 @@ classify the customer's support question."""
max_tokens=512,
system=system,
messages=[{"role": "user", "content": user_content}],
+ **tracing_kwargs(trace_id, ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.py
index e399cd430e48..90fa90ee7e5c 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py
@@ -215,6 +215,7 @@ Return your response as a JSON object with keys: reply, citations, confidence, s
citations=result.citations,
confidence=result.confidence,
sources=[{"ref": s.ref, "excerpt": s.excerpt[:MAX_EXCERPT_CHARS]} for s in result.sources[:MAX_SOURCES]],
+ task_run_id=str(session.task_run.id),
)
finally:
if session is not None:
diff --git a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
index 7d678d281a2c..1e1aae81dce2 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
@@ -6,7 +6,7 @@ from posthog.llm.gateway_client import get_async_anthropic_gateway_client
from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPE_HINTS, UTILITY_MODEL
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message
+from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, tracing_kwargs
from products.conversations.backend.temporal.ai_reply.schemas import RefineQueriesInput, RefineQueriesOutput
@@ -15,7 +15,13 @@ async def support_refine_queries_activity(input: RefineQueriesInput) -> RefineQu
"""Use a lightweight LLM to generate search queries from ticket context + missing gaps."""
async with Heartbeater():
return await _refine_queries(
- input.team_id, input.ticket_context, input.missing, input.ticket_type, input.seed_queries
+ input.team_id,
+ input.ticket_context,
+ input.missing,
+ input.ticket_type,
+ input.seed_queries,
+ input.trace_id,
+ input.ticket_id,
)
@@ -25,6 +31,8 @@ async def _refine_queries(
missing: list[str],
ticket_type: str = "how_to",
seed_queries: list[str] | None = None,
+ trace_id: str = "",
+ ticket_id: str = "",
) -> RefineQueriesOutput:
type_hint = TICKET_TYPE_HINTS.get(ticket_type, "")
system = f"""You are a search query generator for a customer support knowledge base.
@@ -52,6 +60,7 @@ derive search queries about the customer's support question."""
max_tokens=512,
system=system,
messages=[{"role": "user", "content": "\n".join(user_parts)}],
+ **tracing_kwargs(trace_id, ticket_id),
)
content = anthropic_text(message)
queries = [line.strip() for line in content.strip().split("\n") if line.strip()]
diff --git a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py b/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
index 1fe36a5d3759..09a30eb1e7d1 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
@@ -10,7 +10,12 @@ from posthog.llm.gateway_client import get_async_anthropic_gateway_client
from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import MAX_SOURCES, VALIDATOR_MODEL
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, strip_json_fence
+from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_text,
+ create_message,
+ strip_json_fence,
+ tracing_kwargs,
+)
from products.conversations.backend.temporal.ai_reply.schemas import ReviewReplyInput, ReviewReplyOutput
logger = structlog.get_logger(__name__)
@@ -76,7 +81,15 @@ class ReplyReviewResult(BaseModel):
async def support_review_reply_activity(input: ReviewReplyInput) -> ReviewReplyOutput:
"""Screen the final reply for data exfiltration / PII leakage before persisting."""
async with Heartbeater():
- return await _review_reply(input.team_id, input.ticket_context, input.reply, input.sources, input.ticket_type)
+ return await _review_reply(
+ input.team_id,
+ input.ticket_context,
+ input.reply,
+ input.sources,
+ input.ticket_type,
+ input.trace_id,
+ input.ticket_id,
+ )
async def _review_reply(
@@ -85,6 +98,8 @@ async def _review_reply(
reply: str,
sources: list[dict[str, str]] | None = None,
ticket_type: str = "how_to",
+ trace_id: str = "",
+ ticket_id: str = "",
) -> ReviewReplyOutput:
sources_text = ""
for s in (sources or [])[:MAX_SOURCES]:
@@ -108,6 +123,7 @@ TICKET TYPE: {ticket_type}"""
max_tokens=512,
system=REPLY_REVIEW_SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_content}],
+ **tracing_kwargs(trace_id, ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
index eccecbb2bc3a..8ea014aad926 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
@@ -10,7 +10,12 @@ from posthog.llm.gateway_client import get_async_anthropic_gateway_client
from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import MAX_SAFETY_REVIEWED_CHARS, UTILITY_MODEL
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, strip_json_fence
+from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_text,
+ create_message,
+ strip_json_fence,
+ tracing_kwargs,
+)
from products.conversations.backend.temporal.ai_reply.schemas import SafetyFilterInput, SafetyFilterOutput
logger = structlog.get_logger(__name__)
@@ -111,10 +116,12 @@ class SafetyFilterResult(BaseModel):
async def support_safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutput:
"""Screen ticket for prompt injection / data exfiltration before the draft loop."""
async with Heartbeater():
- return await _safety_filter(input.team_id, input.ticket_context)
+ return await _safety_filter(input.team_id, input.ticket_context, input.trace_id, input.ticket_id)
-async def _safety_filter(team_id: int, ticket_context: str) -> SafetyFilterOutput:
+async def _safety_filter(
+ team_id: int, ticket_context: str, trace_id: str = "", ticket_id: str = ""
+) -> SafetyFilterOutput:
# The workflow pre-slices ticket_context to MAX_SAFETY_REVIEWED_CHARS before passing it
# here and to _draft_async, so both always see the same bytes. Cap again defensively.
user_content = f"Ticket to review:\n<ticket>\n{ticket_context[:MAX_SAFETY_REVIEWED_CHARS]}\n</ticket>"
@@ -126,6 +133,7 @@ async def _safety_filter(team_id: int, ticket_context: str) -> SafetyFilterOutpu
max_tokens=512,
system=SAFETY_FILTER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_content}],
+ **tracing_kwargs(trace_id, ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/validate.py b/products/conversations/backend/temporal/ai_reply/activities/validate.py
index 970e00af86f2..ea32d11961bc 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/validate.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/validate.py
@@ -11,7 +11,12 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.activities.draft import _hydrate_chunks
from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPE_HINTS, VALIDATOR_MODEL
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, strip_json_fence
+from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_text,
+ create_message,
+ strip_json_fence,
+ tracing_kwargs,
+)
from products.conversations.backend.temporal.ai_reply.schemas import ValidateInput, ValidateOutput
logger = structlog.get_logger(__name__)
@@ -29,6 +34,8 @@ async def support_validate_activity(input: ValidateInput) -> ValidateOutput:
input.chunk_ids,
input.sources,
input.ticket_type,
+ input.trace_id,
+ input.ticket_id,
)
@@ -40,6 +47,8 @@ async def _validate(
chunk_ids: list[str],
sources: list[dict[str, str]] | None = None,
ticket_type: str = "how_to",
+ trace_id: str = "",
+ ticket_id: str = "",
) -> ValidateOutput:
# Only the cited chunks need rehydrating — fetch their content from the DB by id.
cited_ids = [cid for cid in chunk_ids if cid in set(citations)]
@@ -85,6 +94,7 @@ CITED CHUNKS:
max_tokens=1024,
system=system,
messages=[{"role": "user", "content": user_content}],
+ **tracing_kwargs(trace_id, ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/constants.py b/products/conversations/backend/temporal/ai_reply/constants.py
index 9d0313643b8b..3ba4652a836c 100644
--- a/products/conversations/backend/temporal/ai_reply/constants.py
+++ b/products/conversations/backend/temporal/ai_reply/constants.py
@@ -1,6 +1,10 @@
from typing import Literal
+from uuid import UUID
MAX_ATTEMPTS = 5
+
+# Stable namespace for deterministic per-ticket trace ids (uuid5).
+AI_REPLY_TRACE_NAMESPACE = UUID("a1b2c3d4-5678-4e9f-ab12-cd34ef567890")
SCORE_THRESHOLD = 0.5
RERANK_TOP_K = 5
# Ticket types whose replies may ever be published to the (untrusted) ticket author.
diff --git a/products/conversations/backend/temporal/ai_reply/llms.py b/products/conversations/backend/temporal/ai_reply/llms.py
index 180ad922d231..c1e9f39aebc8 100644
--- a/products/conversations/backend/temporal/ai_reply/llms.py
+++ b/products/conversations/backend/temporal/ai_reply/llms.py
@@ -13,6 +13,22 @@ def anthropic_text(message: Any) -> str:
return "".join(block.text for block in message.content if getattr(block, "type", None) == "text")
+def tracing_kwargs(trace_id: str, ticket_id: str) -> dict[str, Any]:
+ """Per-ticket gateway attribution to splat into a `create_message(...)` call.
+
+ `metadata.user_id` becomes the generation's `$ai_trace_id` (so every utility call for one
+ ticket shares a trace), and `x-posthog-property-ticket_id` is merged into the captured
+ `$ai_generation` properties. Each key is omitted when its value is empty so we never send a
+ null metadata/header; add another tracing property here and all callers pick it up.
+ """
+ kwargs: dict[str, Any] = {}
+ if trace_id:
+ kwargs["metadata"] = {"user_id": trace_id}
+ if ticket_id:
+ kwargs["extra_headers"] = {"x-posthog-property-ticket_id": ticket_id}
+ return kwargs
+
+
async def create_message(client: Any, **kwargs: Any) -> Any:
"""Call the gateway Messages API with a bounded timeout, re-raising transient API errors
as compact ApplicationErrors.
diff --git a/products/conversations/backend/temporal/ai_reply/schemas.py b/products/conversations/backend/temporal/ai_reply/schemas.py
index 70ae317a54f7..27f4a8f59b24 100644
--- a/products/conversations/backend/temporal/ai_reply/schemas.py
+++ b/products/conversations/backend/temporal/ai_reply/schemas.py
@@ -38,6 +38,8 @@ class BuildContextOutput:
class ClassifyInput:
team_id: int
ticket_context: str
+ trace_id: str = ""
+ ticket_id: str = ""
@dataclass
@@ -54,6 +56,8 @@ class RefineQueriesInput:
missing: list[str] = field(default_factory=list)
ticket_type: str = "how_to"
seed_queries: list[str] = field(default_factory=list)
+ trace_id: str = ""
+ ticket_id: str = ""
@dataclass
@@ -106,6 +110,8 @@ class DraftOutput:
# Evidence the agent actually relied on (BK chunk or doc URL + supporting excerpt).
# Lets validation ground against sources gathered via MCP tools, not just seed chunks.
sources: list[dict[str, str]] = field(default_factory=list)
+ # The Tasks TaskRun id for this draft session -- join key to LLMA cost data.
+ task_run_id: str = ""
@dataclass
@@ -117,6 +123,8 @@ class ValidateInput:
chunk_ids: list[str]
sources: list[dict[str, str]] = field(default_factory=list)
ticket_type: str = "how_to"
+ trace_id: str = ""
+ ticket_id: str = ""
@dataclass
@@ -149,6 +157,8 @@ class RecordTriageInput:
class SafetyFilterInput:
team_id: int
ticket_context: str
+ trace_id: str = ""
+ ticket_id: str = ""
@dataclass
@@ -165,6 +175,8 @@ class ReviewReplyInput:
reply: str
sources: list[dict[str, str]] = field(default_factory=list)
ticket_type: str = "how_to"
+ trace_id: str = ""
+ ticket_id: str = ""
@dataclass
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index 2fe9902c134b..46371ee2637f 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from datetime import timedelta
from typing import Any
+from uuid import uuid5
from temporalio import workflow
from temporalio.common import RetryPolicy
@@ -20,6 +21,7 @@ from products.conversations.backend.temporal.ai_reply.activities.review_reply im
from products.conversations.backend.temporal.ai_reply.activities.safety_filter import support_safety_filter_activity
from products.conversations.backend.temporal.ai_reply.activities.validate import support_validate_activity
from products.conversations.backend.temporal.ai_reply.constants import (
+ AI_REPLY_TRACE_NAMESPACE,
MAX_ATTEMPTS,
MAX_SAFETY_REVIEWED_CHARS,
SCORE_THRESHOLD,
@@ -85,6 +87,7 @@ class SupportReplyWorkflow:
async def run(self, input: SupportReplyInput) -> str:
team_id = input.team_id
ticket_id = input.ticket_id
+ trace_id = str(uuid5(AI_REPLY_TRACE_NAMESPACE, f"support-reply:{team_id}:{ticket_id}"))
wf_info = workflow.info()
_triage_base: dict[str, Any] = {
"schema_version": 1,
@@ -146,12 +149,15 @@ class SupportReplyWorkflow:
# --- Outcome tracking: set before each return, recorded in finally ---
outcome: dict[str, Any] = {}
+ draft_task_run_ids: list[str] = []
try:
# Input safety gate: block prompt-injection / exfiltration attempts before any LLM
# draft work. Mirrored from the signals product's safety_filter_activity pattern.
safety_output = await workflow.execute_activity(
support_safety_filter_activity,
- SafetyFilterInput(team_id=input.team_id, ticket_context=reviewed_context),
+ SafetyFilterInput(
+ team_id=input.team_id, ticket_context=reviewed_context, trace_id=trace_id, ticket_id=ticket_id
+ ),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
)
@@ -167,7 +173,9 @@ class SupportReplyWorkflow:
# loop, and `unactionable` tickets (spam/bare feedback) skip the expensive draft loop.
classify_output = await workflow.execute_activity(
support_classify_activity,
- ClassifyInput(team_id=input.team_id, ticket_context=reviewed_context),
+ ClassifyInput(
+ team_id=input.team_id, ticket_context=reviewed_context, trace_id=trace_id, ticket_id=ticket_id
+ ),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
)
@@ -206,6 +214,8 @@ class SupportReplyWorkflow:
missing=missing,
ticket_type=ticket_type,
seed_queries=classify_output.seed_queries,
+ trace_id=trace_id,
+ ticket_id=ticket_id,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -249,6 +259,9 @@ class SupportReplyWorkflow:
retry_policy=RetryPolicy(maximum_attempts=2),
)
+ if draft_output.task_run_id:
+ draft_task_run_ids.append(draft_output.task_run_id)
+
# Validate
validate_output = await workflow.execute_activity(
support_validate_activity,
@@ -260,6 +273,8 @@ class SupportReplyWorkflow:
chunk_ids=retrieve_output.chunk_ids,
sources=draft_output.sources,
ticket_type=ticket_type,
+ trace_id=trace_id,
+ ticket_id=ticket_id,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -286,6 +301,8 @@ class SupportReplyWorkflow:
reply=draft_output.reply,
sources=draft_output.sources,
ticket_type=ticket_type,
+ trace_id=trace_id,
+ ticket_id=ticket_id,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -348,6 +365,8 @@ class SupportReplyWorkflow:
reply=best_reply,
sources=best_sources,
ticket_type=ticket_type,
+ trace_id=trace_id,
+ ticket_id=ticket_id,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -414,5 +433,7 @@ class SupportReplyWorkflow:
**outcome,
"status": "done",
"finished_at": workflow.now().isoformat(),
+ "ai_trace_id": trace_id,
+ "draft_task_run_ids": draft_task_run_ids,
}
)