PostHog
PostHog is an analytics platform with AI observability features for monitoring LLM applications. Use it with Mastra in two ways:
- Agent tools let an agent work with PostHog data, such as events, insights, and feature flags, through Mastra Connect.
- Tracing exports your Mastra traces to PostHog as structured events.
ConnectDirect link to Connect
Before you start, complete the Connect setup to install @mastra/connect and configure your platform project.
Agent toolsDirect link to Agent tools
Give agents tools to capture events, run queries, and manage feature flags, experiments, insights, dashboards, cohorts, and surveys in PostHog.
Connect an account with the posthog provider ID. Run this command from the directory that contains your .env file:
mastra connect add posthog
Then pass tools() to the agent and select the provider:
import { Agent } from '@mastra/core/agent'
import { tools } from '@mastra/connect'
export const posthogAgent = new Agent({
id: 'posthog-agent',
name: 'PostHog agent',
instructions:
'You help people capture events, run queries, and manage feature flags, experiments, insights, dashboards, cohorts, and surveys in PostHog.',
model: '__GATEWAY_OPENAI_MODEL_LUNA__',
tools: tools({ providers: ['posthog'] }),
})
The agent gets 67 PostHog tools, with keys such as posthog_capture_event. See PostHog tools for the full list, and the tools() parameters to restrict tools or require approval before a call runs.
TracingDirect link to Tracing
The PostHog exporter sends your traces to PostHog as structured events, providing insights into token usage, costs, latency, and conversation flows.
InstallationDirect link to Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/posthog@latest
pnpm add @mastra/posthog@latest
yarn add @mastra/posthog@latest
bun add @mastra/posthog@latest
ConfigurationDirect link to Configuration
PrerequisitesDirect link to Prerequisites
- PostHog Account: Sign up at posthog.com
- Project API Key: Get your project API key from PostHog Settings → Project API Key
- Environment Variables: Set your credentials
# Required
POSTHOG_API_KEY=phc_xxxxxxxxxxxxxxxx
# Optional
POSTHOG_HOST=https://us.i.posthog.com # or eu.i.posthog.com for EU region
Zero-config setupDirect link to Zero-config setup
With environment variables set, use the exporter with no configuration:
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { PosthogExporter } from '@mastra/posthog'
export const mastra = new Mastra({
observability: new Observability({
configs: {
posthog: {
serviceName: 'my-service',
exporters: [new PosthogExporter()],
},
},
}),
})
Explicit configurationDirect link to Explicit configuration
You can also pass credentials directly (takes precedence over environment variables):
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { PosthogExporter } from '@mastra/posthog'
export const mastra = new Mastra({
observability: new Observability({
configs: {
posthog: {
serviceName: 'my-service',
exporters: [
new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY,
}),
],
},
},
}),
})
Configuration optionsDirect link to Configuration options
Complete configurationDirect link to Complete configuration
new PosthogExporter({
// Required credentials
apiKey: process.env.POSTHOG_API_KEY!,
// Optional settings
host: 'https://us.i.posthog.com', // Default: US region
// or "https://eu.i.posthog.com" for EU region
// or your self-hosted URL
// Batching configuration
flushAt: 20, // Batch size (default: 20)
flushInterval: 10000, // Flush interval in ms (default: 10000)
serverless: false, // Serverless mode: flushAt=10, flushInterval=2000
// User identification
defaultDistinctId: 'anonymous', // Fallback if no userId in metadata
// Privacy settings
enablePrivacyMode: false, // Excludes input/output from generation events
// Diagnostic logging
logLevel: 'info', // debug | info | warn | error
})
Serverless modeDirect link to Serverless mode
Optimized batching for serverless environments:
new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
serverless: true, // Configures smaller batches for faster flushing
})
Privacy modeDirect link to Privacy mode
Exclude input/output data from generation events while preserving token metrics:
new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
enablePrivacyMode: true, // Removes $ai_input and $ai_output_choices
})
Group analyticsDirect link to Group analytics
To attach events to a PostHog group, add a $groups object to tracingOptions.metadata. The exporter sends those values as the top-level groups field on the PostHog capture call, so you can slice analytics such as LLM cost by group.
await agent.generate(input, {
tracingOptions: {
metadata: {
$groups: {
publication: 'publication-1',
},
},
},
})