LLM analytics is currently considered in beta
. To access it, enable the feature preview in your PostHog account.
- 1
Install the PostHog SDK
RequiredSetting up analytics starts with installing the PostHog SDK.
Terminalnpm install @posthog/ai posthog-node - 2
Install the Vercel AI SDK
RequiredInstall the Vercel AI SDK:
Terminalnpm install ai @ai-sdk/openaiProxy noteThese SDKs do not proxy your calls, they only fire off an async call to PostHog in the background to send the data.
You can also use LLM analytics with other SDKs or our API, but you will need to capture the data manually via the capture method. See schema in the manual capture section for more details.
- 3
Initialize PostHog and Vercel AI
RequiredIn the spot where you initialize the Vercel AI SDK, import PostHog and our
withTracing
wrapper, initialize PostHog with your project API key and host from your project settings, and pass it to thewithTracing
wrapper.TypeScriptimport { PostHog } from "posthog-node";import { withTracing } from "@posthog/ai"import { generateText } from "ai"import { createOpenAI } from "@ai-sdk/openai"const phClient = new PostHog('<ph_project_api_key>',{ host: 'https://us.i.posthog.com' });const openaiClient = createOpenAI({apiKey: 'your_openai_api_key',compatibility: 'strict'});const model = withTracing(openaiClient("gpt-4-turbo"), phClient, {posthogDistinctId: "user_123", // optionalposthogTraceId: "trace_123", // optionalposthogProperties: { "conversation_id": "abc123", "paid": true }, // optionalposthogPrivacyMode: false, // optionalposthogGroups: { "company": "company_id_in_your_db" }, // optional});phClient.shutdown() - 4
Call Vercel AI
RequiredNow, when you use the Vercel AI SDK, it automatically captures many properties into PostHog including
$ai_input
,$ai_input_tokens
,$ai_latency
,$ai_model
,$ai_model_parameters
,$ai_output_choices
, and$ai_output_tokens
. This works for bothtext
andimage
message types.You can also capture or modify additional properties with the
posthogDistinctId
,posthogTraceId
,posthogProperties
,posthogGroups
, andposthogPrivacyMode
parameters.TypeScriptconst { text } = await generateText({model: model,prompt: message});console.log(text)Note: If you want to capture LLM events anonymously, don't pass a distinct ID to the request. See our docs on anonymous vs identified events to learn more.