К основному содержанию
скилл CX Codex

omnibus-instrument-llm-analytics — скилл PostHog

Скилл omnibus-instrument-llm-analytics добавляет в код трейсинг вызовов LLM через PostHog: токены, задержки и стоимость каждой генерации. Заодно поставит SDK, если его ещё нет.

MIT 106 установок ★ 80 обновлён 2026-10-24

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PostHog/skills --skill omnibus-instrument-llm-analytics -a claude-code
Открыть на GitHub

Что делает omnibus-instrument-llm-analytics

Скилл сначала проходит по репозиторию: ищет SDK провайдеров и AI-фреймворки в файлах зависимостей и импортах, по lock-файлам определяет пакетный менеджер. Дальше открывает подходящий справочник в references/ — отдельный на каждого провайдера и каждый фреймворк — и работает по нему.

Установка SDK идёт фоновой задачей, чтобы не тормозить остальную работу. Трейсинг добавляется точечно: входные и выходные токены, имя модели, задержка и стоимость каждой генерации. Архитектуру существующих файлов скилл не перестраивает, правки минимальные, а генерации привязываются к пользователям через distinct ID.

Ключ PostHog и хост берутся из переменных окружения, в код их не вписывают. Если подключён env-file-tools MCP, скилл сам проверит и запишет значения через check_env_keys и set_env_values. Инструментируется только тот провайдер, который реально используется в проекте. Для стека без готового справочника остаётся manual-capture.md с общей схемой захвата событий.

Какие задачи решает

  • добавить учёт токенов и стоимости к уже написанным вызовам LLM
  • поставить PostHog SDK в проект, где аналитики ещё нет
  • определить по зависимостям провайдера и фреймворк, чтобы выбрать схему инструментирования
  • привязать генерации модели к конкретным пользователям по distinct ID
  • пройтись по PR и найти вызовы LLM, оставшиеся без трейсинга

Примеры запросов агенту

  • Добавь LLM-аналитику PostHog к вызовам Anthropic в этом репозитории: токены, задержки, стоимость.
  • Проверь PR и инструментируй все вызовы модели, которые ещё не покрыты трейсингом.
  • Поставь PostHog SDK и вынеси API-ключ с хостом в переменные окружения.

Как установить omnibus-instrument-llm-analytics

1Через Skills CLI (Vercel)

npx skills add PostHog/skills --skill omnibus-instrument-llm-analytics -a claude-code

2Вручную: положить файлы

~/.claude/skills/omnibus-instrument-llm-analytics/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/omnibus-instrument-llm-analytics/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об omnibus-instrument-llm-analytics

Как установить omnibus-instrument-llm-analytics в Claude Code?

Выполните npx skills add PostHog/skills --skill omnibus-instrument-llm-analytics -a claude-code. Файл скилла появится по пути ~/.claude/skills/omnibus-instrument-llm-analytics/SKILL.md.

Что делает omnibus-instrument-llm-analytics?

Разбирает стек проекта, ставит PostHog SDK при необходимости и добавляет трейсинг вызовов LLM: входные и выходные токены, имя модели, задержку и стоимость каждой генерации.

Какие провайдеры и фреймворки поддерживаются?

Справочники есть под OpenAI, Azure OpenAI, Anthropic, Google, Cohere, Mistral, Groq, Ollama, OpenRouter и другие провайдеры, а также под LangChain, LlamaIndex, CrewAI, DSPy, Vercel AI, LiteLLM и прочие фреймворки. Если нужного стека нет, скилл берёт manual-capture.md и захватывает события вручную.

Исходный текст

SKILL.md · MIT
---
name: omnibus-instrument-llm-analytics
description: >-
  Add PostHog LLM analytics 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.
metadata:
  author: PostHog
  version: 1.9.4
---

# Add PostHog LLM analytics

Use this skill to add PostHog LLM analytics that trace AI model usage in new or changed code. Use it after implementing LLM features or reviewing PRs to ensure all generations are captured with token counts, latency, and costs. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any provider or framework.

Supported providers: OpenAI, Azure OpenAI, Anthropic, Google, Cohere, Mistral, Perplexity, DeepSeek, Groq, Together AI, Fireworks AI, xAI, Cerebras, Hugging Face, Ollama, OpenRouter.

Supported frameworks: LangChain, LlamaIndex, CrewAI, AutoGen, DSPy, LangGraph, Pydantic AI, Vercel AI, LiteLLM, Instructor, Semantic Kernel, Mirascope, Mastra, SmolAgents, OpenAI Agents.

Proxy/gateway: Portkey, Helicone.

## Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the LLM stack.
  - Look for LLM provider SDKs (openai, anthropic, google-generativeai, etc.) and AI frameworks (langchain, llamaindex, crewai, etc.) in dependency files and imports.
  - Look for lockfiles to determine the package manager.
  - Check for existing PostHog or observability setup. If PostHog is already installed and LLM tracing is configured, skip to STEP 4 to add tracing for any new LLM calls.

STEP 2: Research instrumentation. (Skip if PostHog LLM tracing is already set up.)
  2.1. Find the reference file below that matches the detected provider or framework — it is the source of truth for callback setup, middleware configuration, and event capture. Read it now.
  2.2. If no reference matches, use manual-capture.md as a fallback — it covers the generic event capture approach that works with any provider.

STEP 3: Install the PostHog SDK. (Skip if PostHog is already set up.)
  - Add the PostHog SDK and any required callback/integration packages.
  - Do not manually edit dependency files — use the package manager's install command.
  - Always install packages as a background task. Don't await completion; proceed with other work immediately.

STEP 4: Add LLM tracing.
  - Instrument LLM calls to capture input tokens, output tokens, model name, latency, and costs for every generation.
  - Follow the provider-specific reference for the exact callback/middleware setup.
  - Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.
  - You must read a file immediately before attempting to write it.

STEP 5: Link to users.
  - Associate LLM generations with identified users via distinct IDs when possible.

STEP 6: Set up environment variables.
  - If an env-file-tools MCP server is connected, use check_env_keys then set_env_values to configure the PostHog API key and host.
  - Reference these environment variables in code instead of hardcoding them.

## 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.

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.

© PostHog · MIT · PostHog/skills

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
sentry-instrument getsentry Скилл sentry-instrument проводит агента по шагам: определяет платформу, ставит SDK Sentry и подключает нужный сигнал — от ошибок до AI-мониторинга. CX Codex +1 2 000установок observability-llm-obs elastic Скилл observability-llm-obs отвечает на вопросы о поведении LLM и агентных приложений по данным, уже загруженным в Elastic: задержки, ошибки, токены, стоимость, срабатывания guardrails. CX Codex +1 4 400установок llm-public-opinion-analytics-assistant reason-machines Скилл llm-public-opinion-analytics-assistant для Claude Code собирает тренды с 15 платформ, кластеризует темы и анализирует тональность через LLM. Рассылает результаты по email, Telegram и WeChat. CX Codex +1 2 400установок llm-intelligent-public-opinion-analytics reason-machines Скилл llm-intelligent-public-opinion-analytics для Claude Code разворачивает краулер популярных списков Weibo, Bilibili, Zhihu, Baidu и других сервисов с анализом топиков и уведомлениями. CX Codex +1 2 100установок langfuse langfuse Помогает настроить трейсинг, оценку и промпты в Langfuse прямо из чата с агентом. Пригодится при отладке вызовов моделей и сборе датасетов. CX Codex +1 21 400установок arize-instrumentation arize Скилл arize-instrumentation для Claude Code добавляет трассировку Arize AX в приложение с LLM. Он определяет стек и настраивает подходящую интеграцию после подтверждения. CX Codex +1 3 700установок

Из того же набора112

Весь набор →
feature-flags-api Скилл feature-flags-api помогает добавить feature flags от PostHog в API-приложение. Он пригодится, когда нужно встроить проверки флагов в существующий код. CX Codex +1 111установок integration-react-native Скилл integration-react-native помогает добавить аналитику PostHog в React Native-приложение, настроить идентификацию пользователей и отслеживание ошибок. CX Codex +1 109установок feature-flags-react-native Скилл feature-flags-react-native внедряет флаги функциональности PostHog в приложения на React Native без ручной настройки обвязки и лишних вызовов useEffect. CX Codex +1 109установок integration-astro-ssr Скилл integration-astro-ssr встраивает аналитику PostHog в SSR-проекты на Astro с API-роутами. Помогает связать клиентские и серверные события. CX Codex +1 109установок integration-swift Скилл integration-swift помогает настроить аналитику PostHog в приложениях на Swift под iOS и macOS по готовой четырёхшаговой схеме. CX Codex +1 108установок integration-react-vite Скилл integration-react-vite встраивает аналитику PostHog в React-приложение на Vite без роутера: четыре шага настройки, идентификация пользователей, фича-флаги и трекинг ошибок. CX Codex +1 107установок integration-nextjs-pages-router Скилл integration-nextjs-pages-router добавляет PostHog в приложения Next.js с Pages Router. Он ведёт агента по настройке аналитики, идентификации пользователей и отслеживанию ошибок. CX Codex +1 103установок integration-react-react-router-7-declarative Скилл integration-react-react-router-7-declarative для Claude Code пошагово подключает аналитику PostHog к приложениям на React Router v7 в декларативном режиме. CX Codex +1 102установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой