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.

fix(slack-app): answer product questions with PostHog's own products (#77477)

Joe Martin7f33ea12f643
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index ec0dc1e844a0..c73cc5a62a40 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -4355,6 +4355,10 @@ describe("AgentServer HTTP Mode", () => {
expect(prompt).toContain("# Identity");
expect(prompt).toContain("PostHog Slack app");
expect(prompt).toContain("Do NOT refer to yourself as Claude");
+ expect(prompt).toContain("# PostHog products first");
+ expect(prompt).toContain(
+ "Never send the user to a third-party product for something PostHog does",
+ );
delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;
},
);
@@ -4430,6 +4434,7 @@ describe("AgentServer HTTP Mode", () => {
).buildCloudSystemPrompt();
expect(prompt).not.toContain("# Identity");
expect(prompt).not.toContain("PostHog Slack app");
+ expect(prompt).not.toContain("# PostHog products first");
delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;
});
});
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 1cf51785ea0f..53d5fd8527da 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -3559,6 +3559,13 @@ You are replying in a Slack thread. Slack readers want short, skimmable answers
- Do not narrate your thinking or list every step you took; report what matters and the result.
- This is a default, not a hard rule. If the user (or their saved memory) asks for more depth or a specific format, follow that instead.
+# PostHog products first
+PostHog is a product suite, not just analytics — session replay, feature flags, experiments, surveys, error tracking, logs, data warehouse, CDP, messaging, and customer support all ship as PostHog products.
+- When someone asks how to set up, enable, configure, or use a capability, assume they mean PostHog's version of it and answer about that.
+- Search our docs with the \`docs-search\` tool before you answer, and ground the answer in what it returns rather than in what you remember. The product changes faster than your training data.
+- Never send the user to a third-party product for something PostHog does. If you are unsure whether we cover it, search the docs before concluding we don't — and if we genuinely don't, say so plainly instead of recommending a competitor. Pointing at a third party we integrate with, as a source or destination, is fine.
+- When a request could mean either a PostHog feature or something in the user's own codebase, ask which they mean instead of guessing.
+
# Mentioning users
To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appears in the message context — copy it verbatim, including the \`U…\` ID. Do NOT construct a mention token from a name, and do NOT substitute the display name (or any other string) for the \`U…\` ID — \`<@Jane|Jane Doe>\` is not a valid mention; only the form with the real ID like \`<@U01ABCDEF23|Jane Doe>\` is. If the person you want to refer to has no \`<@U…|displayname>\` token anywhere in the thread context, write their name as plain text instead of inventing one. These \`<@U…>\` tokens are Slack-only: never carry one — or a name or handle derived from it — into a GitHub PR, commit message, or review request as an \`@\`-mention. A Slack display name or handle is NOT a GitHub username; see the pull-request instructions below.
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index bc0d133abbb3..2524970be904 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -5,6 +5,7 @@ import uuid
import asyncio
import logging
from collections.abc import Sequence
+from dataclasses import replace
from functools import partial
from typing import TYPE_CHECKING, Any, Literal
@@ -366,6 +367,8 @@ class _SandboxedEvalRun(_BaseEvalRun):
# guard rejects sync ORM calls from async contexts, so run it
# in a worker thread.
sandbox_context = await asyncio.to_thread(self._demo_data.make_context, eval_case.name)
+ if original_case is not None and original_case.interaction_origin:
+ sandbox_context = replace(sandbox_context, interaction_origin=original_case.interaction_origin)
if original_case is not None and original_case.setup is not None:
try:
seed_result = await asyncio.to_thread(original_case.setup, sandbox_context)
diff --git a/products/posthog_ai/eval_harness/config.py b/products/posthog_ai/eval_harness/config.py
index 7398eb9c1839..fb105706015d 100644
--- a/products/posthog_ai/eval_harness/config.py
+++ b/products/posthog_ai/eval_harness/config.py
@@ -40,6 +40,12 @@ class SandboxedEvalCase(BaseEvalCase):
repo_fixture: str = ""
"""Name of the repo fixture (informational, for tracking)."""
+ interaction_origin: str | None = None
+ """Surface to run the case as (e.g. ``"slack"``), for suites grading behavior that only
+ exists on one surface. The agent server branches its system prompt on this, so setting it
+ is what makes a case exercise the real prompt instead of a copy. ``None`` runs the case
+ like a plain task, which is what every non-surface-specific suite wants."""
+
setup: Callable[[CustomPromptSandboxContext], dict[str, Any]] | None = Field(
default=None,
exclude=True,
diff --git a/products/slack_app/evals/__init__.py b/products/slack_app/evals/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/slack_app/evals/eval_posthog_first.py b/products/slack_app/evals/eval_posthog_first.py
new file mode 100644
index 000000000000..87a7216df952
--- /dev/null
+++ b/products/slack_app/evals/eval_posthog_first.py
@@ -0,0 +1,72 @@
+"""Does the Slack app answer "how do I set up X?" with PostHog's own product?
+
+A customer asked the Slack app what they needed to set up PostHog's support
+features and got pointed at third-party support tools instead. The agent has no
+grounding step for product questions, so an ambiguous "how do I set up X" falls
+through to whatever the model remembers about the category — and for every
+capability PostHog sells, the model remembers competitors too.
+
+Cases are the shape that fails: a short question about a capability PostHog
+ships, with no explicit mention of PostHog's product name. Each runs with
+``interaction_origin="slack"`` so the agent gets the real Slack system prompt
+rather than the plain-task one.
+
+Metrics:
+
+* ``docs_searched`` — did the agent ground the answer in our docs at all?
+* ``posthog_product_answer`` — is the answer about PostHog's own product?
+* ``no_third_party_recommendation`` — does it avoid sending the customer to a competitor?
+
+To run::
+
+ hogli evals eval_posthog_first
+"""
+
+from __future__ import annotations
+
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import RequiredToolCall
+from products.slack_app.evals.scorers import (
+ DOCS_SEARCH_TOOL_NAME,
+ AnsweredAboutPostHogProduct,
+ NoThirdPartyRecommendation,
+)
+
+
+async def eval_posthog_first(ctx: EvalContext) -> None:
+ cases: list[SandboxedEvalCase] = [
+ SandboxedEvalCase(
+ name="support_setup",
+ prompt="what do I need to set up to start using the support features?",
+ expected={"posthog_product_answer": {"capability": "customer support / a support inbox"}},
+ interaction_origin="slack",
+ ),
+ SandboxedEvalCase(
+ name="drip_emails",
+ prompt=(
+ "we want to email people who signed up but never uploaded a file, "
+ "a couple of days after they sign up. how do we set that up?"
+ ),
+ expected={"posthog_product_answer": {"capability": "automated / drip email to users"}},
+ interaction_origin="slack",
+ ),
+ SandboxedEvalCase(
+ name="stripe_alongside_events",
+ prompt="how do we get our Stripe billing data sitting next to our product data so we can join them?",
+ expected={"posthog_product_answer": {"capability": "syncing an external source into a data warehouse"}},
+ interaction_origin="slack",
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-slack-posthog-first-cli",
+ cases=cases,
+ scorers=[
+ RequiredToolCall({DOCS_SEARCH_TOOL_NAME}, name="docs_searched"),
+ AnsweredAboutPostHogProduct(),
+ NoThirdPartyRecommendation(),
+ ],
+ ctx=ctx,
+ )
diff --git a/products/slack_app/evals/scorers.py b/products/slack_app/evals/scorers.py
new file mode 100644
index 000000000000..4b8fc12387c5
--- /dev/null
+++ b/products/slack_app/evals/scorers.py
@@ -0,0 +1,131 @@
+"""Scorers for the Slack app's answers to "how do I set up X?" questions."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from products.posthog_ai.eval_harness.log_parser import LogParser
+from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer
+from products.posthog_ai.eval_harness.scorers.contract import Score
+
+DOCS_SEARCH_TOOL_NAME = "docs-search"
+
+
+def _user_prompt(output: dict[str, Any] | None) -> str:
+ if not output:
+ return ""
+ raw_log = output.get("raw_log")
+ if raw_log:
+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "").get_user_prompt()
+ prompt = output.get("prompt")
+ return prompt if isinstance(prompt, str) else ""
+
+
+EXPECTED_KEY = "posthog_product_answer"
+
+
+def _answer_under_test(output: dict[str, Any] | None, expected: Any, *, scorer_name: str) -> dict[str, Any] | Score:
+ """Shared ``_prepare`` body: pull the capability under test and the final answer.
+
+ Both judges grade the same two strings and opt in through the same ``expected``
+ sub-dict, so they apply to a case together or skip together.
+ """
+ spec = expected.get(EXPECTED_KEY) if isinstance(expected, dict) else None
+ if not isinstance(spec, dict) or not spec.get("capability"):
+ return Score(name=scorer_name, score=None, metadata={"reason": "Case declares no capability to grade"})
+ if not output:
+ return Score(name=scorer_name, score=0.0, metadata={"reason": "No output"})
+ last_message = output.get("last_message")
+ if not isinstance(last_message, str) or not last_message.strip():
+ return Score(name=scorer_name, score=0.0, metadata={"reason": "No final assistant message"})
+ return {
+ "output": {
+ "prompt": _user_prompt(output),
+ "last_message": last_message,
+ "capability": spec["capability"],
+ }
+ }
+
+
+class AnsweredAboutPostHogProduct(JudgedScorer):
+ """Binary: does the answer explain PostHog's own product for the capability asked about?
+
+ Opts in via ``expected={"posthog_product_answer": {"capability": "..."}}``.
+ """
+
+ def _prepare(self, output, expected) -> dict[str, Any] | Score:
+ return _answer_under_test(output, expected, scorer_name=self._name())
+
+ def __init__(self, **kwargs):
+ super().__init__(
+ name="posthog_product_answer",
+ prompt_template="""
+You are evaluating an answer the PostHog Slack app gave to a customer asking how to set something up.
+
+PostHog ships its own product for the capability below, so the answer should be about that product — what to enable, install, or configure inside PostHog.
+
+Capability the customer asked about:
+<capability>
+{{output.capability}}
+</capability>
+
+Customer's question:
+<prompt>
+{{output.prompt}}
+</prompt>
+
+Agent's final answer:
+<final_answer>
+{{output.last_message}}
+</final_answer>
+
+Does the answer explain how to do this with PostHog's own product? An answer that walks through PostHog setup steps, names the PostHog product or its settings, or links PostHog docs for it qualifies — even if some details are wrong. An answer that only discusses instrumenting the customer's own code, only asks clarifying questions, or is about some other tool does NOT qualify. Answer `yes` or `no`.
+""".strip(),
+ choice_scores=BINARY_CHOICE_SCORES,
+ model=JUDGE_MODEL,
+ max_completion_tokens=256,
+ **kwargs,
+ )
+
+
+class NoThirdPartyRecommendation(JudgedScorer):
+ """Binary: does the answer avoid steering the customer to a non-PostHog product?
+
+ This is the regression that prompted the suite — the agent recommending an
+ external tool for a capability PostHog already sells. Opts in via the same
+ ``expected={"posthog_product_answer": {"capability": "..."}}`` entry.
+ """
+
+ def _prepare(self, output, expected) -> dict[str, Any] | Score:
+ return _answer_under_test(output, expected, scorer_name=self._name())
+
+ def __init__(self, **kwargs):
+ super().__init__(
+ name="no_third_party_recommendation",
+ prompt_template="""
+You are checking whether an answer from the PostHog Slack app sent a customer to a competitor.
+
+PostHog ships its own product for the capability below, so recommending someone else's product for it is a failure — the customer is already paying for ours.
+
+Capability the customer asked about:
+<capability>
+{{output.capability}}
+</capability>
+
+Customer's question:
+<prompt>
+{{output.prompt}}
+</prompt>
+
+Agent's final answer:
+<final_answer>
+{{output.last_message}}
+</final_answer>
+
+Is the answer free of recommendations to use a non-PostHog product for this capability? Naming a third party PostHog integrates with as a data source or destination is fine, and so is naming one to explain a migration away from it. Suggesting the customer adopt, install, or evaluate someone else's product to get this capability is not. Answer `yes` if the answer is clean, `no` if it steers the customer elsewhere.
+""".strip(),
+ choice_scores=BINARY_CHOICE_SCORES,
+ model=JUDGE_MODEL,
+ max_completion_tokens=256,
+ **kwargs,
+ )
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index ff0addea3a06..65fc973f5d7a 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -127,6 +127,10 @@ class CustomPromptSandboxContext:
capability. Only meaningful when ``repository`` is None — a task with a repository already gets
the full-permission credential path. Best-effort: if no team GitHub integration exists or the
mint fails, the sandbox starts without a token."""
+ interaction_origin: str | None = None
+ """Surface the run is answering on (e.g. ``"slack"``). The agent server branches its system
+ prompt on this, so evals that grade surface-specific behavior must set it to exercise the
+ prompt the surface really ships. ``None`` leaves the run originless, like a plain task."""
class TurnPollTimeout(RuntimeError):
@@ -238,6 +242,7 @@ async def create_task_and_trigger(
workflow_id_prefix=workflow_id_prefix,
github_read_access=context.github_read_access,
mcp_builtin_agent_key=mcp_builtin_agent_key,
+ interaction_origin=context.interaction_origin,
)
# lambda wrap: task.latest_run is a lazy ORM property; sync_to_async needs a callable
task_run = await sync_to_async(lambda: task.latest_run)()