: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
fix(llma): steer sql/agent users to posthog.ai_events for content (#61849)
Carlos Marchal7242a6d4dad0
diff --git a/products/ai_observability/skills/README.md b/products/ai_observability/skills/README.mdindex 87852a12ab99..22ffdab542f8 100644--- a/products/ai_observability/skills/README.md+++ b/products/ai_observability/skills/README.md@@ -7,7 +7,8 @@ Also available to Claude Code / Codex via `hogli sync:skill`.## Skills- **exploring-llm-traces** — how to query, inspect, and debug LLM traces via MCP tools.- Covers the `$ai_*` event schema, content detail levels, and step-by-step debugging workflows.+ Covers the `$ai_*` event schema, where message content lives (`events` vs the `ai_events`+ table), content detail levels, and step-by-step debugging workflows.- **exploring-llm-clusters** — how to investigate AI observability clustering results,compare cluster behavior, compute metrics, and drill into individual traces.- **exploring-llm-costs** — how to investigate LLM spend: total cost, breakdownsdiff --git a/products/ai_observability/skills/exploring-llm-costs/SKILL.md b/products/ai_observability/skills/exploring-llm-costs/SKILL.mdindex 1a19ccc14444..04c2469cd367 100644--- a/products/ai_observability/skills/exploring-llm-costs/SKILL.md+++ b/products/ai_observability/skills/exploring-llm-costs/SKILL.md@@ -147,6 +147,7 @@ versions for the same provider. To avoid rot:## Tips- Always set a time range — cost queries without one scan the full events table+- Token, cost, model, and `$ai_trace_id` properties are on `events` — but message _content_ (`$ai_input` / `$ai_output_choices`) lives only on the `posthog.ai_events` table; see the traces skill's [event reference](../exploring-llm-traces/references/events-and-properties.md) if you need content alongside cost- Always include `$ai_embedding` alongside `$ai_generation` when summing cost; embeddings are cheap per-call but add up at scale- Costs are written at ingestion (see [Calculating LLM costs](https://posthog.com/docs/ai-observability/calculating-costs)) — if `$ai_total_cost_usd` is missing or zero, read `$ai_cost_model_source` first: `passthrough` means the SDK supplied costs; `custom` means custom token prices; `openrouter` / `manual` mean automatic lookup; missing means the model wasn't matched (unusual custom model, fine-tune). Grep: `countIf(properties.$ai_total_cost_usd IS NULL)` per `(model, source)`- Custom pricing uses **per-token** prices, not per-million — if a custom-priced model looks ~1M× too expensive or too cheap, that's almost always the bugdiff --git a/products/ai_observability/skills/exploring-llm-traces/SKILL.md b/products/ai_observability/skills/exploring-llm-traces/SKILL.mdindex 7c6cf238eae9..e636e2b17184 100644--- a/products/ai_observability/skills/exploring-llm-traces/SKILL.md+++ b/products/ai_observability/skills/exploring-llm-traces/SKILL.md@@ -5,7 +5,9 @@ description: >Use when the user pastes a trace or session URL (e.g. /ai-observability/traces/<id> or /ai-observability/sessions/<id>),asks to debug a trace, figure out what went wrong, check if an agent used a tool correctly,verify context/files were surfaced, inspect subagent behavior, investigate LLM decisions,- or analyze token usage and costs.+ or analyze token usage and costs. Also use when raw SQL/HogQL against+ `events.properties.$ai_input` / `$ai_output_choices` returns empty — message content lives only+ on the dedicated `posthog.ai_events` table.---# Exploring LLM traces with MCP tools@@ -291,5 +293,6 @@ results (array for list, object for single trace)- Always include the `_posthogUrl` in your response so the user can click through- `$ai_input_state` / `$ai_output_state` on spans contain tool call inputs and outputs- `$ai_input` / `$ai_output_choices` on generations contain the full LLM conversation — can be megabytes; when the result is persisted to a file, use the parsing scripts+- In raw SQL, heavy content (`$ai_input` / `$ai_output` / `$ai_output_choices` / `$ai_input_state` / `$ai_output_state` / `$ai_tools`) lives only on the `posthog.ai_events` table, not `events.properties` — see the [event reference](./references/events-and-properties.md) for the column mapping and trace-id-anchored query patterns- Use `filterTestAccounts: true` to exclude internal/test traffic when searching- `$ai_trace` events are NOT in the `events` array — their data is surfaced via trace-level `inputState`, `outputState`, and `traceName`diff --git a/products/ai_observability/skills/exploring-llm-traces/references/events-and-properties.md b/products/ai_observability/skills/exploring-llm-traces/references/events-and-properties.mdindex 85b608ffb8ba..a0ea0c0dde11 100644--- a/products/ai_observability/skills/exploring-llm-traces/references/events-and-properties.md+++ b/products/ai_observability/skills/exploring-llm-traces/references/events-and-properties.md@@ -67,6 +67,58 @@ Embedding creation event (text to vector).| `$ai_total_cost_usd` | float | Total cost in USD || `$ai_latency` | float | Duration in seconds |+## Where heavy content lives: `events` vs `ai_events`++The heavy LLM properties are **not stored on `events`** — they live as native columns on a dedicated+ClickHouse table, referenced in HogQL as **`posthog.ai_events`**. The `events` table keeps only the lightweight metadata (token counts, costs,+model, provider, `$ai_trace_id`, latency, error flags).++| Heavy content | `events` property | `ai_events` column |+| -------------- | -------------------- | ------------------ |+| Input messages | `$ai_input` | `input` |+| Output | `$ai_output` | `output` |+| Output choices | `$ai_output_choices` | `output_choices` |+| Input state | `$ai_input_state` | `input_state` |+| Output state | `$ai_output_state` | `output_state` |+| Tools | `$ai_tools` | `tools` |++`posthog.ai_events` is `ORDER BY (team_id, trace_id, timestamp)`, so **`trace_id` is the access+path, not `timestamp`**. Rows are dropped after the retention period (30 days by default), so+traces older than that have no content. Nothing restricts which heavy columns an event can carry,+but the typical shape is: `$ai_generation` carries `input` / `output_choices` / `tools` (embeddings+carry `input`); `$ai_span` and `$ai_trace` carry `input_state` / `output_state`.++For trace inspection, prefer the `query-llm-trace` / `query-llm-traces-list` tools — they read+`posthog.ai_events` for you. Drop to the SQL below only for custom analysis (aggregations, joins,+batch extraction) or when you're already at the SQL layer.++**Single trace** — when you already have a `trace_id` (e.g. from a trace URL or `query-llm-traces-list`): read it directly.++```sql+SELECT timestamp, span_id, event, model, input, output_choices+FROM posthog.ai_events+WHERE trace_id = '<trace_id>'+ORDER BY timestamp+```++**Batch / analytics (a time window across many traces):** filter on the timestamp-indexed+`events` table first to get the trace IDs, then fetch the heavy content from `posthog.ai_events`+anchored on `trace_id`.++```sql+WITH matching_traces AS (+ SELECT DISTINCT properties.$ai_trace_id AS trace_id+ FROM events+ WHERE event = '$ai_generation'+ AND timestamp >= now() - INTERVAL 7 DAY+ AND properties.$ai_model = 'gpt-4o' -- token/cost/model/ids stay on events+)+SELECT a.trace_id, a.span_id, a.model, a.input, a.output_choices+FROM posthog.ai_events AS a+WHERE a.trace_id IN (SELECT trace_id FROM matching_traces)+ORDER BY a.trace_id, a.timestamp+```+## Common patterns### Linking events in a trace@@ -93,3 +145,7 @@ These properties can contain megabytes of data:Use `contentDetail: "preview"` or `"none"` when querying via MCP tools.When using `contentDetail: "full"`, dump results to a file.++In raw SQL these live only on `posthog.ai_events`, not `events.properties` —+see [Where heavy content lives](#where-heavy-content-lives-events-vs-ai_events) for the column+mapping and query patterns.diff --git a/products/ai_observability/skills/exploring-llm-traces/references/example-llm-trace.md.j2 b/products/ai_observability/skills/exploring-llm-traces/references/example-llm-trace.md.j2index bdc6066ee580..452a576fd848 100644--- a/products/ai_observability/skills/exploring-llm-traces/references/example-llm-trace.md.j2+++ b/products/ai_observability/skills/exploring-llm-traces/references/example-llm-trace.md.j2@@ -8,6 +8,8 @@ Key properties of the $ai_generation event: $ai_input and $ai_output_choices.**IMPORTANT:** The `$ai_input`, `$ai_input_state`, and `$ai_output_state` properties can be extremely large (containing full conversation histories, system prompts, or application state). When your query selects these properties, you MUST dump the results to a file and use bash commands to explore the output. Never output them directly into the conversation.+This content lives only on `posthog.ai_events` (read it directly by `trace_id`), not on `events.properties` — see [where heavy content lives](./events-and-properties.md#where-heavy-content-lives-events-vs-ai_events).+```sql{{ render_hogql_example({"kind": "TraceQuery", "traceId": "79955c94-7453-488f-a84a-eabb6f084e4c", "dateRange": {"date_from": "2025-12-09T23:45:41", "date_to": "2025-12-10T00:15:41", "explicitDate": true}}) }}```diff --git a/products/ai_observability/skills/exploring-llm-traces/references/example-llm-traces-list.md b/products/ai_observability/skills/exploring-llm-traces/references/example-llm-traces-list.mdindex c9d18c9ec776..2ae1d400e84f 100644--- a/products/ai_observability/skills/exploring-llm-traces/references/example-llm-traces-list.md+++ b/products/ai_observability/skills/exploring-llm-traces/references/example-llm-traces-list.md@@ -5,7 +5,8 @@ This is a two-phase query for performance: first find matching trace IDs, then fTime ranges are always required. Results can be large — dump to a file if needed.This query intentionally omits large content fields (`$ai_input`, `$ai_output`, `$ai_output_choices`, `$ai_input_state`, `$ai_output_state`, `$ai_tools`).-Use the [single trace query](./example-llm-trace.md) (or the `query-llm-trace` wrapper) to retrieve those for a specific trace; both read from a dedicated table that retains the full payload for ~30 days.+These live only on the dedicated `posthog.ai_events` table (not `events`), retained 30 days by default.+Use the [single trace query](./example-llm-trace.md) (or the `query-llm-trace` wrapper) to retrieve them for a specific trace, or read `posthog.ai_events` directly anchored on `trace_id` — see [where heavy content lives](./events-and-properties.md#where-heavy-content-lives-events-vs-ai_events) for the column mapping.## Phase 1 — Find trace IDsdiff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.mdindex de7a467381a0..64763f28307b 100644--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md@@ -47,6 +47,7 @@ Schema reference for PostHog's core system models, organized by domain:- [Hog Flows](./references/models-hog-flows.md)- [Hog Functions](./references/models-hog-functions.md)- [Integrations](./references/models-integrations.md)+- [AI observability events (`posthog.ai_events`)](./references/models-ai-observability-events.md)- [AI observability reviews](./references/models-ai-observability-reviews.md)- [Logs (`logs` data plane + saved views and alerts)](./references/models-logs.md)- [Metrics (`posthog.metrics`)](./references/models-metrics.md)diff --git a/products/posthog_ai/skills/querying-posthog-data/references/example-llm-trace.md.j2 b/products/posthog_ai/skills/querying-posthog-data/references/example-llm-trace.md.j2index bdc6066ee580..3440491633d7 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/example-llm-trace.md.j2+++ b/products/posthog_ai/skills/querying-posthog-data/references/example-llm-trace.md.j2@@ -8,6 +8,8 @@ Key properties of the $ai_generation event: $ai_input and $ai_output_choices.**IMPORTANT:** The `$ai_input`, `$ai_input_state`, and `$ai_output_state` properties can be extremely large (containing full conversation histories, system prompts, or application state). When your query selects these properties, you MUST dump the results to a file and use bash commands to explore the output. Never output them directly into the conversation.+These heavy fields live only on `posthog.ai_events` (read it directly by `trace_id`), not on `events.properties` — see [AI observability events](./models-ai-observability-events.md) for the column mapping and query patterns.+```sql{{ render_hogql_example({"kind": "TraceQuery", "traceId": "79955c94-7453-488f-a84a-eabb6f084e4c", "dateRange": {"date_from": "2025-12-09T23:45:41", "date_to": "2025-12-10T00:15:41", "explicitDate": true}}) }}```diff --git a/products/posthog_ai/skills/querying-posthog-data/references/example-llm-traces-list.md b/products/posthog_ai/skills/querying-posthog-data/references/example-llm-traces-list.mdindex 86d56b3fcf72..6ef126f36643 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/example-llm-traces-list.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/example-llm-traces-list.md@@ -6,6 +6,7 @@ Time ranges are always required. Results can be large — dump to a file if needThis query intentionally omits large content fields (`$ai_input`, `$ai_output_choices`, `$ai_input_state`, `$ai_output_state`).Use the [single trace query](./example-llm-trace.md) to retrieve those for a specific trace.+This content lives only on `posthog.ai_events` (not `events`), retained 30 days by default — read it anchored on `trace_id`. See [AI observability events](./models-ai-observability-events.md) for the column mapping and access patterns.## Phase 1 — Find trace IDsdiff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-events.md b/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-events.mdnew file mode 100644index 000000000000..bab961970569--- /dev/null+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-events.md@@ -0,0 +1,51 @@+# AI observability events (`posthog.ai_events`)++LLM/AI events (`$ai_generation`, `$ai_span`, `$ai_trace`, `$ai_embedding`, `$ai_metric`, `$ai_feedback`, `$ai_evaluation`) are captured on the shared `events` table. The **heavy LLM properties are not stored on `events`** — they live as native columns on a dedicated ClickHouse table, `posthog.ai_events`.++**Namespacing:** Reference this table as `posthog.ai_events`, not bare `ai_events` — it's registered under the `posthog.` namespace in the HogQL database (see `posthog/hogql/database/database.py`), same as `posthog.trace_spans` / `posthog.metrics`. A bare `FROM ai_events` fails with "Unknown table" at HogQL compile time. (Asymmetric with `events` and `logs`, which are registered at root level.)++**Prefer the typed tools when they fit:** `posthog:query-llm-trace` for a single trace and `posthog:query-llm-traces-list` for listing both join `posthog.ai_events` for you. Reach for HogQL when you need custom aggregations, joins, or pre-filtering the typed tools don't expose.++## Which columns live where++`events` keeps the lightweight metadata — token counts, costs, model, provider, `$ai_trace_id`, latency, error flags (also mirrored as native columns on `posthog.ai_events`, where the `$ai_`-prefixed property maps to the un-prefixed column, e.g. `$ai_model` → `model`). The heavy properties live only on `posthog.ai_events`:++| Heavy content | `events` property | `posthog.ai_events` column |+| -------------- | -------------------- | -------------------------- |+| Input messages | `$ai_input` | `input` |+| Output | `$ai_output` | `output` |+| Output choices | `$ai_output_choices` | `output_choices` |+| Input state | `$ai_input_state` | `input_state` |+| Output state | `$ai_output_state` | `output_state` |+| Tools | `$ai_tools` | `tools` |++Nothing restricts which heavy columns an event can carry, but the typical shape is: `$ai_generation` carries `input` / `output_choices` / `tools` (embeddings carry `input`); `$ai_span` and `$ai_trace` carry `input_state` / `output_state`. The full native column list is in `posthog/hogql/database/schema/ai_events.py`.++## Access patterns++`posthog.ai_events` is `ORDER BY (team_id, trace_id, timestamp)`, so **`trace_id` is the access path, not `timestamp`**. Rows are dropped after the retention period (30 days by default), so traces older than that have no content.++**Single trace (you have the ID):** read it directly.++```sql+SELECT timestamp, span_id, event, model, input, output_choices+FROM posthog.ai_events+WHERE trace_id = '<trace_id>'+ORDER BY timestamp+```++**Batch / analytics (a time window across many traces):** filter the timestamp-indexed `events` table to get the trace IDs, then fetch the heavy content from `posthog.ai_events` anchored on `trace_id`.++```sql+WITH matching_traces AS (+ SELECT DISTINCT properties.$ai_trace_id AS trace_id+ FROM events+ WHERE event = '$ai_generation'+ AND timestamp >= now() - INTERVAL 7 DAY+ AND properties.$ai_model = 'gpt-4o'+)+SELECT a.trace_id, a.span_id, a.model, a.input, a.output_choices+FROM posthog.ai_events AS a+WHERE a.trace_id IN (SELECT trace_id FROM matching_traces)+ORDER BY a.trace_id, a.timestamp+```diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.mdindex 1f9c484bf1a3..5c2be9e7f2e9 100644--- a/services/mcp/src/templates/execute-sql-prompt.md+++ b/services/mcp/src/templates/execute-sql-prompt.md@@ -39,18 +39,41 @@ Write SQL a human can scan: multi-line with indentation, one column/CTE per lineLarge JSON values in results (notably full `properties` objects) are truncated by default. If you anticipate a large result set, or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), dump the results to a file and process them with bash rather than returning them inline. Alternatively, cherry-pick specific keys (`properties.$browser`) instead of the whole object.-### Large LLM trace fields are stripped from `events.properties`--For LLM events (`$ai_generation`, `$ai_trace`, `$ai_span`, etc.), these specific keys with large values are stripped from `events.properties`:--- `properties.$ai_input`-- `properties.$ai_output`-- `properties.$ai_output_choices`-- `properties.$ai_input_state`-- `properties.$ai_output_state`-- `properties.$ai_tools`--Prefer `query-llm-trace` / `query-llm-traces-list` whenever you need any of those six keys — they contain information on the proper read patterns to a dedicated AI events table which contains these fields. Other AI properties (token counts, costs, model, trace IDs) stay on `events` in all three regimes and are safe to query directly.+### Large LLM trace fields live on the `posthog.ai_events` table, not `events.properties`++For LLM events (`$ai_generation`, `$ai_trace`, `$ai_span`, etc.) the heavy keys are **not stored on `events.properties`** — they live as native columns on a dedicated ClickHouse table. Like `posthog.trace_spans` / `posthog.metrics`, reference it as `posthog.ai_events` (a bare `FROM ai_events` errors with "Unknown table"):++| `events` property | `ai_events` column |+| -------------------- | ------------------ |+| `$ai_input` | `input` |+| `$ai_output` | `output` |+| `$ai_output_choices` | `output_choices` |+| `$ai_input_state` | `input_state` |+| `$ai_output_state` | `output_state` |+| `$ai_tools` | `tools` |++Other AI properties (token counts, costs, model, `$ai_trace_id`) stay on `events` in all regimes and are safe to query there.++`posthog.ai_events` is `ORDER BY (team_id, trace_id, timestamp)`, so **anchor on `trace_id`, never scan by `timestamp`**. Rows are dropped after the retention period (30 days by default), so older traces have no content. Nothing restricts which heavy columns an event can carry, but the typical shape is: `$ai_generation` carries `input` / `output_choices` / `tools` (embeddings carry `input`); `$ai_span` and `$ai_trace` carry `input_state` / `output_state`.++- **Single trace** — `SELECT input, output_choices FROM posthog.ai_events WHERE trace_id = '<id>' ORDER BY timestamp`.+- **Batch / analytics** — filter the timestamp-indexed `events` table first to get the trace IDs, then fetch heavy content from `posthog.ai_events` anchored on `trace_id`:++ ```sql+ WITH matching_traces AS (+ SELECT DISTINCT properties.$ai_trace_id AS trace_id+ FROM events+ WHERE event = '$ai_generation'+ AND timestamp >= now() - INTERVAL 7 DAY+ AND properties.$ai_model = 'gpt-4o'+ )+ SELECT a.trace_id, a.span_id, a.model, a.input, a.output_choices+ FROM posthog.ai_events AS a+ WHERE a.trace_id IN (SELECT trace_id FROM matching_traces)+ ORDER BY a.trace_id, a.timestamp+ ```++The `query-llm-trace` / `query-llm-traces-list` tools read `posthog.ai_events` for you; prefer them when a single trace's content is all you need.### Observability data-plane tables: `logs`, `posthog.trace_spans`, `posthog.metrics`