Generated banner for LLM Analytics Setup
Generated logo for LLM Analytics Setup

LLM Analytics Setup

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

PostHog LLM analytics for all supported providers
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive guide for integrating PostHog's LLM analytics into applications using various AI providers and frameworks. By wrapping existing LLM clients with PostHog's instrumentation, developers can automatically capture detailed telemetry—including input/output tokens, latency, model names, and costs—without proxying their API calls. The skill covers a wide range of providers and frameworks, offering specific implementation patterns for each, and includes a fallback manual capture method for custom setups.

What it does

  • Instruments LLM calls to automatically capture $ai_generation events.
  • Tracks key metrics like latency, token usage, and total cost per generation.
  • Supports a broad ecosystem of LLM providers and AI frameworks.
  • Enables linking LLM generations to specific users for better observability.
  • Provides a manual capture interface for unsupported or custom LLM providers.
  • Ensures data privacy by distinguishing between event properties and PII.

When to use it

  • When you need to monitor the performance and cost of LLM calls in production.
  • When you want to debug AI agent behavior by tracing input and output sequences.
  • When you need to associate AI interactions with specific user sessions.
  • When you are building applications using frameworks like LangChain, AutoGen, or LlamaIndex.

Advantages

  • Non-intrusive integration that does not proxy your LLM API calls.
  • Centralized visibility into LLM costs and usage across different providers.
  • Automatic capture of critical performance metrics like time-to-first-token.
  • Flexible configuration allows for custom properties and trace IDs.

Usage examples

“How do I add PostHog analytics to my Anthropic Claude implementation in Python?”
The agent will provide the code to initialize the PostHog client and wrap the Anthropic client, enabling automatic event capture for all messages.create calls.
“I am using AutoGen for my agents, how can I track their LLM usage in PostHog?”
The agent will guide you to install the necessary extensions and show how to pass a wrapped OpenAI client into the AutoGen OpenAIChatCompletionClient.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/posthog/llm-analytics-setup/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip llm-analytics-setup.zip -d .agents/skills

Documentation by PostHog

PostHog LLM analytics

This skill helps you add PostHog LLM analytics to any application using AI/LLM providers.

Reference files

  • references/openai.md - Openai llm analytics installation - docs

  • references/azure-openai.md - Azure openai llm analytics installation - docs

  • references/anthropic.md - Anthropic llm analytics installation - docs

  • references/google.md - Google llm analytics installation - docs

  • references/cohere.md - Cohere llm analytics installation - docs

  • references/mistral.md - Mistral llm analytics installation - docs

  • references/perplexity.md - Perplexity llm analytics installation - docs

  • references/deepseek.md - Deepseek llm analytics installation - docs

  • references/groq.md - Groq llm analytics installation - docs

  • references/together-ai.md - Together ai llm analytics installation - docs

  • references/fireworks-ai.md - Fireworks ai llm analytics installation - docs

  • references/xai.md - Xai llm analytics installation - docs

  • references/cerebras.md - Cerebras llm analytics installation - docs

  • references/hugging-face.md - Hugging face llm analytics installation - docs

  • references/ollama.md - Ollama llm analytics installation - docs

  • references/openrouter.md - Openrouter llm analytics installation - docs

  • references/langchain.md - Langchain llm analytics installation - docs

  • references/llamaindex.md - Llamaindex llm analytics installation - docs

  • references/crewai.md - Crewai llm analytics installation - docs

  • references/autogen.md - Autogen llm analytics installation - docs

  • references/dspy.md - Dspy llm analytics installation - docs

  • references/langgraph.md - Langgraph llm analytics installation - docs

  • references/pydantic-ai.md - Pydantic ai llm analytics installation - docs

  • references/vercel-ai.md - Vercel ai SDK llm analytics installation - docs

  • references/litellm.md - Litellm llm analytics installation - docs

  • references/instructor.md - Instructor llm analytics installation - docs

  • references/semantic-kernel.md - Semantic kernel llm analytics installation - docs

  • references/mirascope.md - Mirascope llm analytics installation - docs

  • references/mastra.md - Mastra llm analytics installation - docs

  • references/smolagents.md - Smolagents llm analytics installation - docs

  • references/openai-agents.md - Openai agents SDK llm analytics installation - docs

  • references/portkey.md - Portkey llm analytics installation - docs

  • references/helicone.md - Helicone llm analytics installation - docs

  • references/manual-capture.md - Manual capture llm analytics installation - docs

  • references/basics.md - Llm analytics basics - docs

  • references/traces.md - Traces - docs

  • references/calculating-costs.md - Calculating llm costs - docs

Each provider reference contains installation instructions, SDK setup, and code examples specific to that provider or framework. Find the reference that matches the user's stack and follow its instructions.

If the user's provider isn't listed, use manual-capture.md as a fallback — it covers the generic event capture approach that works with any provider.

Key principles

  • Environment variables: Always use environment variables for PostHog and LLM provider keys. Never hardcode them.

  • Minimal changes: Add LLM analytics alongside existing LLM calls. Don't replace or restructure existing code.

  • Trace all generations: Capture input tokens, output tokens, model name, latency, and costs for every LLM call.

  • Link to users: Associate LLM generations with identified users via distinct IDs when possible.

  • One provider at a time: Only instrument the provider(s) the user is actually using. Don't add instrumentation for providers not present in the codebase.

Framework guidelines

  • Remember that source code is available in the venv/site-packages directory

  • posthog is the Python SDK package name

  • Install dependencies with pip install posthog or pip install -r requirements.txt and do NOT use unquoted version specifiers like >= directly in shell commands

  • In CLIs and scripts: MUST call posthog.shutdown() before exit or all events are lost

  • Always use the Posthog() class constructor (instance-based API) instead of module-level posthog.api_key config

  • Always include enable_exception_autocapture=True in the Posthog() constructor to automatically track exceptions

  • NEVER send PII in capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content

  • PII belongs in identify() person properties, NOT in capture() event properties. Safe event properties are metadata like message_length, form_type, boolean flags.

  • Register posthog_client.shutdown with atexit.register() to ensure all events are flushed on exit

  • The Python SDK has NO identify() method — use posthog_client.set(distinct_id=user_id, properties={...}) to set person properties, or use identify_context(user_id) within a context

Files

references/calculating-costs.md

Calculating LLM costs - Docs

How are LLM costs calculated?

PostHog calculates cost based on the number of input (prompt) and output (completion) tokens generated by specific AI models, plus additional cost components like per-request and per-web-search pricing when applicable.

Model matching

We use OpenRouter's pricing data as our primary source to match your model and calculate costs. OpenRouter provides comprehensive pricing information for models across different providers, and we use both the $ai_provider and $ai_model properties from your events to find the exact pricing.

If OpenRouter doesn't have pricing data for a specific model, we fall back to our manually maintained pricing database for additional model support.

Cost components

The total cost ($ai_total_cost_usd) is calculated from multiple components:

  • Token-based costs: Input (prompt) and output (completion) tokens

  • Cache costs: Cached token reads and writes (when applicable)

  • Request-based costs: Some models charge per request in addition to token costs

  • Web search costs: Some models charge per web search performed

For cached LLM responses, our pricing models include cached token pricing which we automatically apply.

We also take into account the reasoning / thinking tokens for models that support it.

Cache token accounting

Different LLM providers report cache tokens differently:

  • Exclusive counting (Anthropic/Claude) - Cache tokens are separate from $ai_input_tokens. For example, if you have 100 input tokens and 50 cached tokens, $ai_input_tokens is 100.

  • Inclusive counting (OpenAI and most others) - Cache tokens are included in $ai_input_tokens. Using the same example, $ai_input_tokens is 150.

PostHog auto-detects which counting style to use based on the $ai_provider and $ai_model properties. For Anthropic and Claude models, PostHog assumes exclusive counting. For all other providers, it assumes inclusive counting.

Overriding auto-detection

If you're manually capturing events or using a framework wrapper that normalizes token counts differently, override the auto-detection by setting the $ai_cache_reporting_exclusive property:

  • $ai_cache_reporting_exclusive: true - Cache tokens are separate from input tokens (Anthropic-style)

  • $ai_cache_reporting_exclusive: false - Input tokens already include cache tokens

When not set, PostHog resolves this automatically and writes the resolved value back to the event for downstream consumers.

Setting custom pricing

You can override PostHog's automatic cost calculation by providing custom pricing for your LLM models. This is useful when:

  • You have negotiated custom pricing with your LLM provider

  • You're using a model that PostHog doesn't support yet

  • PostHog's automatic pricing doesn't match your specific use case

Option 1: Custom price per token

If you know your pricing per token, you can set the following custom properties when calling your LLM:

  • $ai_input_token_price (required): Price per input/prompt token

  • $ai_output_token_price (required): Price per output/completion token

  • $ai_cache_read_token_price (optional): Price per cached token read

  • $ai_cache_write_token_price (optional): Price per cached token write

  • $ai_request_price (optional): Price per request (for models that charge per request)

  • $ai_web_search_price (optional): Price per web search (for models that charge per search)

Important: Token prices should be per individual token, not per million tokens. For example, if your provider charges $0.03 per 1M tokens, you would set $ai_input_token_price: 0.00000003 (0.03 / 1,000,000).

PostHog AI

JavaScript
import { OpenAI } from '@posthog/ai'
import { PostHog } from 'posthog-node'
const phClient = new PostHog(
  '<ph_project_token>',
  { host: 'https://us.i.posthog.com' }
)
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  posthog: phClient
})
const response = await openai.responses.create({
  model: 'my-custom-model',
  messages: [{ role: 'user', content: 'Hello' }],
  posthogProperties: {
    $ai_input_token_price: 0.00000003,   // $0.03 per 1M tokens = $0.00000003 per token
    $ai_output_token_price: 0.00000006,  // $0.06 per 1M tokens = $0.00000006 per token
    // Optional: cache pricing
    $ai_cache_read_token_price: 0.000000015,
    $ai_cache_write_token_price: 0.0000000375
  }
})
Python
from posthog.ai.openai import OpenAI
from posthog import Posthog
posthog = Posthog(
    "<ph_project_token>",
    host="https://us.i.posthog.com"
)
client = OpenAI(
    api_key="sk-...",
    posthog_client=posthog
)
response = client.responses.create(
    model="my-custom-model",
    messages=[{"role": "user", "content": "Hello"}],
    posthog_properties={
        "$ai_input_token_price": 0.00000003,   # $0.03 per 1M tokens = $0.00000003 per token
        "$ai_output_token_price": 0.00000006,  # $0.06 per 1M tokens = $0.00000006 per token
        # Optional: cache pricing
        "$ai_cache_read_token_price": 0.000000015,
        "$ai_cache_write_token_price": 0.0000000375
    }
)

Both $ai_input_token_price and $ai_output_token_price must be provided for custom pricing to take effect. PostHog will then calculate the total cost based on the token counts and your custom prices.

Option 2: Pre-calculated costs

If you're manually capturing LLM events and have already calculated the total costs yourself, you can send them directly:

  • $ai_input_cost_usd: Total cost for input/prompt tokens in USD

  • $ai_output_cost_usd: Total cost for output/completion tokens in USD

  • $ai_request_cost_usd: Total cost for requests in USD

  • $ai_web_search_cost_usd: Total cost for web searches in USD

PostHog AI

JavaScript
// After making your LLM call and calculating costs
posthog.capture('$ai_generation', {
  $ai_trace_id: traceId,
  $ai_model: 'my-custom-model',
  $ai_provider: 'my-provider',
  $ai_input_tokens: inputTokens,
  $ai_output_tokens: outputTokens,
  $ai_input_cost_usd: 0.0042,
  $ai_output_cost_usd: 0.0028
  // ... other required properties
})
Python
# After making your LLM call and calculating costs
posthog.capture(
    event='$ai_generation',
    properties={
        '$ai_trace_id': trace_id,
        '$ai_model': 'my-custom-model',
        '$ai_provider': 'my-provider',
        '$ai_input_tokens': input_tokens,
        '$ai_output_tokens': output_tokens,
        '$ai_input_cost_usd': 0.0042,
        '$ai_output_cost_usd': 0.0028
        # ... other required properties
    }
)

PostHog will use these values directly without any additional calculation.

Precedence

Cost calculation follows this precedence order:

  1. Pre-calculated costs ($ai_input_cost_usd, $ai_output_cost_usd, $ai_request_cost_usd, $ai_web_search_cost_usd): These values are used directly without any additional calculation

  2. Custom pricing ($ai_input_token_price, $ai_output_token_price, $ai_request_price, $ai_web_search_price): PostHog calculates costs from token counts and usage metrics using your custom prices

  3. Automatic model matching: PostHog matches your model using OpenRouter's pricing data first, then falls back to manually maintained pricing if needed

Cost calculation metadata

When PostHog calculates costs automatically, it sets the following metadata properties on the event to help you understand how costs were determined:

PropertyDescriptionExamples
$ai_model_cost_usedThe model identifier used for cost calculation. May differ from the requested model when a variant or alias is resolved.openai/gpt-4o-mini
$ai_cost_model_sourceWhere the cost data for this model was sourced from.openrouter, manual, custom, passthrough
$ai_cost_model_providerThe provider used to look up the cost for this model.openai, anthropic, custom

These properties are useful for debugging cost discrepancies or understanding which pricing was applied when using model aliases or custom configurations.

You can find the code for this on GitHub.

Community questions

Ask a question

Was this page useful?

HelpfulCould be better

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/posthog/llm-analytics/skills/setup · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
PostHog/skills

AutoGineer is not affiliated with or endorsed by PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download llm-analytics-setup.zip