メインコンテンツへ移動

PostHog exporter

PostHog は、LLM アプリケーションを監視するための AI Observability 機能を備えた分析プラットフォームです。PostHog exporter は Trace を構造化イベントとして PostHog へ送信し、token 使用量、コスト、レイテンシ、会話フローに関するインサイトを提供します。

インストール
インストールへの直接リンク

npm install @mastra/posthog@latest

設定
設定への直接リンク

前提条件
前提条件への直接リンク

  1. PostHog アカウントposthog.com で登録します
  2. プロジェクト API キー:PostHog の Settings → Project API Key からプロジェクト API キーを取得します
  3. 環境変数:認証情報を設定します
.env
# Required
POSTHOG_API_KEY=phc_xxxxxxxxxxxxxxxx

# Optional
POSTHOG_HOST=https://us.i.posthog.com # or eu.i.posthog.com for EU region

ゼロコンフィグ設定
ゼロコンフィグ設定への直接リンク

環境変数を設定したら、設定なしで exporter を使用できます。

src/mastra/index.ts
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()],
},
},
}),
})

明示的な設定
明示的な設定への直接リンク

認証情報を直接渡すこともできます(環境変数より優先されます)。

src/mastra/index.ts
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,
}),
],
},
},
}),
})

設定オプション
設定オプションへの直接リンク

完全な設定
完全な設定への直接リンク

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
})

サーバーレスモード
サーバーレスモードへの直接リンク

サーバーレス環境向けに最適化されたバッチ処理です。

new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
serverless: true, // Configures smaller batches for faster flushing
})

プライバシーモード
プライバシーモードへの直接リンク

token メトリクスを維持したまま、generation イベントから input/output データを除外します。

new PosthogExporter({
apiKey: process.env.POSTHOG_API_KEY!,
enablePrivacyMode: true, // Removes $ai_input and $ai_output_choices
})

グループ分析
グループ分析への直接リンク

イベントを PostHog グループに関連付けるには、$groups オブジェクトを tracingOptions.metadata に追加します。exporter はこれらの値を PostHog の capture 呼び出しのトップレベル groups フィールドとして送信するため、グループ別の LLM コストなどの分析を切り分けられます。

await agent.generate(input, {
tracingOptions: {
metadata: {
$groups: {
publication: 'publication-1',
},
},
},
})