Chapter 48 · Instrument LLM Analytics
Subchapter 48.22
references/mastra.mdMarkdown5 KBView on GitHub
Required
Full working examples
See the complete Node.js example (opens in a new tab) on GitHub. If you’re using the PostHog SDK wrapper instead, see the Node.js wrapper example (opens in a new tab).
Install Mastra with the official @mastra/posthog exporter. Mastra’s observability system sends traces to PostHog as $ai_generation events automatically.
npm install @mastra/core @mastra/observability @mastra/posthog2
Required
Initialize Mastra with an Observability config that uses the PosthogExporter. Pass your PostHog project token and host from your project settings (opens in a new tab).
import { Mastra } from '@mastra/core'
import { Agent } from '@mastra/core/agent'
import { Observability } from '@mastra/observability'
import { PosthogExporter } from '@mastra/posthog'
const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: 'You are a helpful assistant with access to weather data.',
model: { id: 'openai/gpt-4o-mini' },
})
const mastra = new Mastra({
agents: { weatherAgent },
observability: new Observability({
configs: {
posthog: {
serviceName: 'my-app',
exporters: [
new PosthogExporter({
apiKey: '<ph_project_token>',
host: 'https://us.i.posthog.com',
defaultDistinctId: 'user_123', // fallback if no userId in metadata
}),
],
},
},
}),
})3
Required
Use Mastra as normal. The PosthogExporter automatically captures $ai_generation events for each LLM call, including token usage, cost, latency, and the full conversation.
Pass tracingOptions.metadata to generate() to attach per-request metadata. The userId field maps to PostHog’s distinct ID, sessionId maps to $ai_session_id, and any other keys are passed through as custom event properties.
const agent = mastra.getAgent('weatherAgent')
const result = await agent.generate("What's the weather in Dublin?", {
tracingOptions: {
metadata: {
userId: 'user_123', // becomes distinct_id
sessionId: 'session_abc', // becomes $ai_session_id
conversation_id: 'abc-123', // custom property
},
},
})
console.log(result.text)Note: If you want to capture LLM events anonymously, omit
userIdfromtracingOptions.metadataand don’t setdefaultDistinctId. See our docs on anonymous vs identified events (opens in a new tab) to learn more.
You can expect captured $ai_generation events to have the following properties:
| Property | Description |
|---|---|
| $ai_model | The specific model, like gpt-5-mini or claude-4-sonnet |
| $ai_latency | The latency of the LLM call in seconds |
| $ai_time_to_first_token | Time to first token in seconds (streaming only) |
| $ai_tools | Tools and functions available to the LLM |
| $ai_input | List of messages sent to the LLM |
| $ai_input_tokens | The number of tokens in the input (often found in response.usage) |
| $ai_output_choices | List of response choices from the LLM |
| $ai_output_tokens | The number of tokens in the output (often found in response.usage) |
| $ai_total_cost_usd | The total cost in USD (input + output) |
| […] (opens in a new tab) | See full list (opens in a new tab) of properties |
Recommended
Confirm LLM events are being sent to PostHog
Let’s make sure LLM events are being captured and sent to PostHog. Under AI Observability, you should see rows of data appear in the Traces and Generations tabs.


4
Recommended
Now that you’re capturing AI conversations, continue with the resources below to learn what else AI Observability enables within the PostHog platform.
| Resource | Description |
|---|---|
| Basics (opens in a new tab) | Learn the basics of how LLM calls become events in PostHog. |
| Generations (opens in a new tab) | Read about the $ai_generation event and its properties. |
| Traces (opens in a new tab) | Explore the trace hierarchy and how to use it to debug LLM calls. |
| Spans (opens in a new tab) | Review spans and their role in representing individual operations. |
| Anaylze LLM performance (opens in a new tab) | Learn how to create dashboards to analyze LLM performance. |
Ask a question
HelpfulCould be better