AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-llm-analytics

Add PostHog AI Observability to trace AI model usage. Use after implementing LLM features or reviewing PRs to ensure all generations are captured with token counts, latency, and costs. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-llm-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 40

references/semantic-kernel.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

Semantic Kernel AI Observability installation

Canonical URL: https://posthog.com/docs/ai-observability/installation/semantic-kernel

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.i.posthog.com instead of https://us.i.posthog.com (ingestion host), and use https://eu.posthog.com instead of https://app.posthog.com (app host for links).

On this page

Let AI instrument your LLM calls for you

Skip the manual setup — run this in your project and the wizard installs the SDK and wires up AI Observability for you.

npx @posthog/wizard ai-observability

PostHog Wizard hedgehog

Let AI instrument your LLM calls for you

  1. 1

    Install dependencies

    Required

    Full working examples

    See the complete Python example on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see this example instead: Python wrapper example.

    Install the OpenTelemetry SDK, the OpenAI instrumentation, and Semantic Kernel.

    pip install semantic-kernel openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
    
  2. 2

    Set up OpenTelemetry tracing

    Required

    Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog. PostHog converts gen_ai.* spans into $ai_generation events automatically.

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.resources import Resource, SERVICE_NAME
    from posthog.ai.otel import PostHogSpanProcessor
    from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
    
    resource = Resource(attributes={
        SERVICE_NAME: "my-app",
        "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
        "foo": "bar", # custom properties are passed through
    })
    
    provider = TracerProvider(resource=resource)
    provider.add_span_processor(
        PostHogSpanProcessor(
            api_key="<ph_project_token>",
            host="https://us.i.posthog.com",
        )
    )
    trace.set_tracer_provider(provider)
    
    OpenAIInstrumentor().instrument()
    
  3. 3

    Run your kernel

    Required

    Use Semantic Kernel as normal. PostHog automatically captures an $ai_generation event for each LLM call made through the OpenAI SDK that Semantic Kernel uses internally.

    import asyncio
    from semantic_kernel import Kernel
    from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
    
    async def main():
        kernel = Kernel()
        kernel.add_service(
            OpenAIChatCompletion(
                ai_model_id="gpt-4o-mini",
                api_key="your_openai_api_key",
            )
        )
        result = await kernel.invoke_prompt("Tell me a fun fact about hedgehogs")
        print(result)
    
    asyncio.run(main())
    

    Note: To capture LLM events anonymously, omit the posthog.distinct_id resource attribute and don't set a distinct ID in the PostHog context. See our docs on anonymous vs identified events to learn more.

    You can expect captured $ai_generation events to have the following properties:

    | Property | Description | | --- | --- | | $ai_model | The specific model, like gpt-5-mini or claude-4-sonnet | | $ai_latency | The latency of the LLM call in seconds | | $ai_time_to_first_token | Time to first token in seconds (streaming only) | | $ai_tools | Tools and functions available to the LLM | | $ai_input | List of messages sent to the LLM | | $ai_input_tokens | The number of tokens in the input (often found in response.usage) | | $ai_output_choices | List of response choices from the LLM | | $ai_output_tokens | The number of tokens in the output (often found in response.usage) | | $ai_total_cost_usd | The total cost in USD (input + output) | | [...] | See full list of properties |

  4. 4

    Users and sessions

    Recommended

    A server usually handles requests for many users, so a resource attribute can't say who each trace belongs to. Wrap each request in a PostHog context instead. The PostHog span processor adds the context's distinct ID and properties to every AI span started inside it. Other span processors and exporters on the same provider don't see them.

    Set $ai_session_id if your product has multi-turn conversations, so the Sessions tab can group their traces. Workloads that finish in a single trace, like batch jobs or one-shot generation, don't need it.

    Python

    # Requires posthog 7.70.0 or later
    import posthog
    
    with posthog.new_context():
        posthog.identify_context(user_id)
        posthog.tag("$ai_session_id", conversation_id)
        posthog.tag("plan", "pro")  # custom properties work too
    
        reply = handle_turn(user_message)
    

    A distinct ID set this way takes priority over a posthog.distinct_id resource attribute, so you can keep the resource attribute as the fallback for work outside a request. If your instrumentation already sets the gen_ai.conversation.id attribute, PostHog uses it as the session ID, and an explicit $ai_session_id takes priority over it.

  5. Verify traces and generations

    Recommended

    Confirm LLM events are being sent to PostHog

    Let's make sure LLM events are being captured and sent to PostHog. Under AI Observability, you should see rows of data appear in the Traces and Generations tabs.

    LLM generations in PostHog

    Check for LLM events in PostHog

  6. 5

    Next steps

    Recommended

    Now that you're capturing AI conversations, continue with the resources below to learn what else AI Observability enables within the PostHog platform.

    | Resource | Description | | --- | --- | | Basics | Learn the basics of how LLM calls become events in PostHog. | | Generations | Read about the $ai_generation event and its properties. | | Traces | Explore the trace hierarchy and how to use it to debug LLM calls. | | Spans | Review spans and their role in representing individual operations. | | Anaylze LLM performance | Learn how to create dashboards to analyze LLM performance. |