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/manual-capture.md

Manual capture LLM analytics installation - Docs

  1. 1

    Capture LLM events manually

    If you're using a different server-side SDK or prefer to use the API, you can manually capture the data by calling the capture method or using the capture API.

    API

    Capture via API
    curl -X POST "https://us.i.posthog.com/i/v0/e/" \
            -H "Content-Type: application/json" \
            -d '{
                "api_key": "<ph_project_token>",
                "event": "$ai_generation",
                "properties": {
                    "distinct_id": "user_123",
                    "$ai_trace_id": "trace_id_here",
                    "$ai_model": "gpt-5-mini",
                    "$ai_provider": "openai",
                    "$ai_input": [{"role": "user", "content": "Tell me a fun fact about hedgehogs"}],
                    "$ai_input_tokens": 10,
                    "$ai_output_choices": [{"role": "assistant", "content": "Hedgehogs have around 5,000 to 7,000 spines on their backs!"}],
                    "$ai_output_tokens": 20,
                    "$ai_latency": 1.5,
                    "$ai_stream": true,
                    "$ai_time_to_first_token": 0.25
                }
            }'

    Node.js

    1. Install
    npm install posthog-node
    2. Initialize PostHog
    import { PostHog } from 'posthog-node'
    const client = new PostHog('<ph_project_token>', {
        host: 'https://us.i.posthog.com'
    })
    3. Capture Event
    // After your LLM call
    client.capture({
        distinctId: 'user_123',
        event: '$ai_generation',
        properties: {
            $ai_trace_id: 'trace_id_here',
            $ai_model: 'gpt-5-mini',
            $ai_provider: 'openai',
            $ai_input: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
            $ai_input_tokens: 10,
            $ai_output_choices: [{ role: 'assistant', content: 'Hedgehogs have around 5,000 to 7,000 spines on their backs!' }],
            $ai_output_tokens: 20,
            $ai_latency: 1.5,
            // For streaming responses, also include:
            // $ai_stream: true,
            // $ai_time_to_first_token: 0.25
        }
    })
    client.shutdown()

    Python

    1. Install
    pip install posthog
    2. Initialize PostHog
    from posthog import Posthog
    posthog = Posthog("<ph_project_token>", host="https://us.i.posthog.com")
    3. Capture Event
    # After your LLM call
    posthog.capture(
        distinct_id='user_123',
        event='$ai_generation',
        properties={
            '$ai_trace_id': 'trace_id_here',
            '$ai_model': 'gpt-5-mini',
            '$ai_provider': 'openai',
            '$ai_input': [{'role': 'user', 'content': 'Tell me a fun fact about hedgehogs'}],
            '$ai_input_tokens': 10,
            '$ai_output_choices': [{'role': 'assistant', 'content': 'Hedgehogs have around 5,000 to 7,000 spines on their backs!'}],
            '$ai_output_tokens': 20,
            '$ai_latency': 1.5,
            # For streaming responses, also include:
            # '$ai_stream': True,
            # '$ai_time_to_first_token': 0.25
        }
    )

    Go

    1. Install
    go get github.com/posthog/posthog-go
    2. Initialize PostHog
    import "github.com/posthog/posthog-go"
    client, _ := posthog.NewWithConfig("<ph_project_token>", posthog.Config{
        Endpoint: "https://us.i.posthog.com",
    })
    defer client.Close()
    3. Capture Event
    // After your LLM call
    client.Enqueue(posthog.Capture{
        DistinctId: "user_123",
        Event:      "$ai_generation",
        Properties: map[string]interface{}{
            "$ai_trace_id":        "trace_id_here",
            "$ai_model":           "gpt-5-mini",
            "$ai_provider":        "openai",
            "$ai_input_tokens":    10,
            "$ai_output_tokens":   20,
            "$ai_latency":         1.5,
            // For streaming responses, also include:
            // "$ai_stream":              true,
            // "$ai_time_to_first_token": 0.25,
        },
    })

    Ruby

    1. Install
    gem install posthog-ruby
    2. Initialize PostHog
    require 'posthog-ruby'
    posthog = PostHog::Client.new({
        api_key: '<ph_project_token>',
        host: 'https://us.i.posthog.com'
    })
    3. Capture Event
    # After your LLM call
    posthog.capture({
        distinct_id: 'user_123',
        event: '$ai_generation',
        properties: {
        '$ai_trace_id' => 'trace_id_here',
        '$ai_model' => 'gpt-5-mini',
        '$ai_provider' => 'openai',
        '$ai_input_tokens' => 10,
        '$ai_output_tokens' => 20,
        '$ai_latency' => 1.5
        # For streaming responses, also include:
        # '$ai_stream' => true,
        # '$ai_time_to_first_token' => 0.25
        }
    })

    PHP

    1. Install
    composer require posthog/posthog-php
    2. Initialize PostHog
    <?php
    require_once __DIR__ . '/vendor/autoload.php';
    use PostHog\PostHog;
    PostHog::init('<ph_project_token>', [
        'host' => 'https://us.i.posthog.com'
    ]);
    3. Capture Event
    // After your LLM call
    PostHog::capture([
        'distinctId' => 'user_123',
        'event' => '$ai_generation',
        'properties' => [
            '$ai_trace_id' => 'trace_id_here',
            '$ai_model' => 'gpt-5-mini',
            '$ai_provider' => 'openai',
            '$ai_input_tokens' => 10,
            '$ai_output_tokens' => 20,
            '$ai_latency' => 1.5
            // For streaming responses, also include:
            // '$ai_stream' => true,
            // '$ai_time_to_first_token' => 0.25
        ]
    ]);
    Event Properties

    Each event type has specific properties. See the tabs below for detailed property documentation for each event type.

    Generation

    A generation is a single call to an LLM.

    Event name: $ai_generation

    Core properties
    PropertyDescription
    $ai_trace_idThe trace ID (a UUID to group AI events) like conversation_idMust contain only letters, numbers, and special characters: -, _, ~, ., @, (, ), !, ', :, |Example: d9222e05-8708-41b8-98ea-d4a21849e761
    $ai_session_id(Optional) Groups related traces together. Use this to organize traces by whatever grouping makes sense for your application (user sessions, workflows, conversations, or other logical boundaries).Example: session-abc-123, conv-user-456
    $ai_span_id(Optional) Unique identifier for this generation
    $ai_span_name(Optional) Name given to this generationExample: summarize_text
    $ai_parent_id(Optional) Parent span ID for tree view grouping
    $ai_modelThe model usedExample: gpt-5-mini
    $ai_providerThe LLM providerExample: openai, anthropic, gemini
    $ai_input_tokensThe number of tokens in the input (often found in response.usage)
    $ai_output_tokensThe number of tokens in the output (often found in response.usage)
    $ai_latency(Optional) The latency of the LLM call in seconds
    $ai_time_to_first_token(Optional) Time to first token in seconds. Only applicable for streaming responses.
    $ai_http_status(Optional) The HTTP status code of the response
    $ai_base_url(Optional) The base URL of the LLM providerExample: https://api.openai.com/v1
    $ai_request_url(Optional) The full URL of the request made to the LLM APIExample: https://api.openai.com/v1/chat/completions
    $ai_is_error(Optional) Boolean to indicate if the request was an error
    $ai_error(Optional) The error message or object
    Cost properties

    Cost properties are optional as we can automatically calculate them from model and token counts. If you want, you can provide your own cost properties or custom pricing instead.

    Pre-calculated costs
    PropertyDescription
    $ai_input_cost_usd(Optional) The cost in USD of the input tokens
    $ai_output_cost_usd(Optional) The cost in USD of the output tokens
    $ai_request_cost_usd(Optional) The cost in USD for the requests
    $ai_web_search_cost_usd(Optional) The cost in USD for the web searches
    $ai_total_cost_usd(Optional) The total cost in USD (sum of all cost components)
    Custom pricing
    PropertyDescription
    $ai_input_token_price(Optional) Price per input token (used to calculate $ai_input_cost_usd)
    $ai_output_token_price(Optional) Price per output token (used to calculate $ai_output_cost_usd)
    $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
    $ai_request_count(Optional) Number of requests (defaults to 1 if $ai_request_price is set)
    $ai_web_search_price(Optional) Price per web search
    $ai_web_search_count(Optional) Number of web searches performed
    Cache properties
    PropertyDescription
    $ai_cache_read_input_tokens(Optional) Number of tokens read from cache
    $ai_cache_creation_input_tokens(Optional) Number of tokens written to cache (Anthropic-specific)
    $ai_cache_reporting_exclusive(Optional) Whether cache tokens are excluded from $ai_input_tokens. When true, cache tokens are separate from input tokens. When false, input tokens already include cache tokens. Defaults to true for Anthropic provider or Claude models, false otherwise.
    Model parameters
    PropertyDescription
    $ai_temperature(Optional) Temperature parameter used in the LLM request
    $ai_stream(Optional) Whether the response was streamed
    $ai_max_tokens(Optional) Maximum tokens setting for the LLM response

    Trace

    A trace is a group that contains multiple spans, generations, and embeddings. Traces can be manually sent as events or appear as pseudo-events automatically created from child events.

    Event name: $ai_trace

    Core properties
    PropertyDescription
    $ai_trace_idThe trace ID (a UUID to group related AI events together)Must contain only letters, numbers, and special characters: -, _, ~, ., @, (, ), !, ', :, |Example: d9222e05-8708-41b8-98ea-d4a21849e761
    $ai_session_id(Optional) Groups related traces together. Use this to organize traces by whatever grouping makes sense for your application (user sessions, workflows, conversations, or other logical boundaries).Example: session-abc-123, conv-user-456
    $ai_latency(Optional) The latency of the trace in seconds
    $ai_span_name(Optional) The name of the traceExample: chat_completion, rag_pipeline
    $ai_is_error(Optional) Boolean to indicate if the trace encountered an error
    $ai_error(Optional) The error message or object if the trace failed
    Pseudo-trace Events

    When you send generation ($ai_generation), span ($ai_span), or embedding ($ai_embedding) events with a $ai_trace_id, PostHog automatically creates a pseudo-trace event that appears in the dashboard as a parent grouping. These pseudo-traces:

    • Are not actual events in your data

    • Automatically aggregate metrics from child events (latency, tokens, costs)

    • Provide a hierarchical view of your AI operations

    • Do not require sending an explicit $ai_trace event

    This means you can either:

    1. Send explicit $ai_trace events to control the trace metadata

    2. Let PostHog automatically create pseudo-traces from your generation/span events

    Span

    A span is a single action within your application, such as a function call or vector database search.

    Event name: $ai_span

    Core properties
    PropertyDescription
    $ai_trace_idThe trace ID (a UUID to group related AI events together)Must contain only letters, numbers, and the following characters: -, _, ~, ., @, (, ), !, ', :, |Example: d9222e05-8708-41b8-98ea-d4a21849e761
    $ai_session_id(Optional) Groups related traces together. Use this to organize traces by whatever grouping makes sense for your application (user sessions, workflows, conversations, or other logical boundaries).Example: session-abc-123, conv-user-456
    $ai_span_id(Optional) Unique identifier for this spanExample: bdf42359-9364-4db7-8958-c001f28c9255
    $ai_span_name(Optional) The name of the spanExample: vector_search, data_retrieval, tool_call
    $ai_parent_id(Optional) Parent ID for tree view grouping (trace_id or another span_id)Example: 537b7988-0186-494f-a313-77a5a8f7db26
    $ai_latency(Optional) The latency of the span in secondsExample: 0.361
    $ai_is_error(Optional) Boolean to indicate if the span encountered an error

    Embedding

    An embedding is a single call to an embedding model to convert text into a vector representation.

    Event name: $ai_embedding

    Core properties
    PropertyDescription
    $ai_trace_idThe trace ID (a UUID to group related AI events together). Must contain only letters, numbers, and special characters: -, _, ~, ., @, (, ), !, ', :, |Example: d9222e05-8708-41b8-98ea-d4a21849e761
    $ai_session_id(Optional) Groups related traces together. Use this to organize traces by whatever grouping makes sense for your application (user sessions, workflows, conversations, or other logical boundaries).Example: session-abc-123, conv-user-456
    $ai_span_id(Optional) Unique identifier for this embedding operation
    $ai_span_name(Optional) Name given to this embedding operationExample: embed_user_query, index_document
    $ai_parent_id(Optional) Parent span ID for tree-view grouping
    $ai_modelThe embedding model usedExample: text-embedding-3-small, text-embedding-ada-002
    $ai_providerThe LLM providerExample: openai, cohere, voyage
    $ai_inputThe text to embedExample: "Tell me a fun fact about hedgehogs" or array of strings for batch embeddings
    $ai_input_tokensThe number of tokens in the input
    $ai_latency(Optional) The latency of the embedding call in seconds
    $ai_http_status(Optional) The HTTP status code of the response
    $ai_base_url(Optional) The base URL of the LLM providerExample: https://api.openai.com/v1
    $ai_request_url(Optional) The full URL of the request made to the embedding APIExample: https://api.openai.com/v1/embeddings
    $ai_is_error(Optional) Boolean to indicate if the request was an error
    $ai_error(Optional) The error message or object if the embedding failed
    Cost properties

    Cost properties are optional as we can automatically calculate them from model and token counts. If you want, you can provide your own cost property instead.

    PropertyDescription
    $ai_input_cost_usd(Optional) Cost in USD for input tokens
    $ai_output_cost_usd(Optional) Cost in USD for output tokens (usually 0 for embeddings)
    $ai_total_cost_usd(Optional) Total cost in USD
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