Skip to main content

GenAI Telemetry

PyPI version Python 3.8+ License Downloads

The most comprehensive open-source observability SDK for GenAI/LLM applications.

Trace prompts, completions, token usage, latency, errors, and costs across OpenAI, Anthropic, LangChain, LlamaIndex, and more. Export to 10+ backends including Splunk, Elasticsearch, Datadog, and Prometheus.

What's New in v1.3.0: Sessions, Users, Scores and Prompts

  • Nested traces that actually nest. Every decorator now opens its span before your function runs, so anything traced inside (another decorator or an auto-instrumented LLM call) becomes a child span. Nested @trace_chain / @trace_agent calls stay in the same trace.
  • trace_context() groups a request into one trace and tags it with session_id, user_id, tags, metadata and trace_name. update_current_trace() / update_current_span() add attributes from inside your code.
  • Inputs and outputs (opt-in): setup_telemetry(..., capture_content=True) records each step's input and output as prompt_text / response_text, truncated to max_content_length.
  • Scores: score("user_feedback", 1, trace_id=...) for user feedback, eval results or labels. Numeric, boolean and categorical values. The Splunk exporter sends them to the genai_evals index.
  • Prompt management: get_prompt("support-answer", label="production") fetches versioned prompts from the GenAI Observability Splunk app, with caching and a fallback. @trace_llm(prompt_name=..., prompt_version=...) links generations to the prompt version.
  • Async functions are supported by all decorators. Trace context uses contextvars, so it follows asyncio tasks.
  • environment and release options tag every span.
from genai_telemetry import setup_telemetry, trace_context, trace_chain, trace_llm, score

setup_telemetry("support-bot", exporter="splunk", splunk_url="https://splunk:8088",
                splunk_token="...", capture_content=True, environment="production")

with trace_context(session_id=chat_id, user_id=user.id, tags=["beta"]) as trace_id:
    reply = rag_answer(question)          # decorated functions inside become one nested trace

score("user_feedback", 1, trace_id=trace_id, comment="Helpful")

Behaviour change: before 1.3.0, top-level @trace_llm calls kept reusing one trace ID per thread. Now each top-level call (or each trace_context block) is its own trace, which is what the Splunk app's Traces page expects.

What's New in v1.1.1: Zero-Code Auto-Instrumentation

No more decorators on every function! Just call auto_instrument() and all your LLM calls are automatically traced:

from genai_telemetry import setup_telemetry, auto_instrument

setup_telemetry(workflow_name="my-app", exporter="splunk", splunk_url="...", splunk_token="...")
auto_instrument()  # ← That's it!

# All LLM calls are now automatically traced
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(model="gpt-4o", messages=[...])  # ✓ Traced!

Quick Start

Installation

pip install genai-telemetry

The fastest way to get started — zero code changes to your existing LLM code:

from genai_telemetry import setup_telemetry, auto_instrument

# 1. Setup telemetry (pick your backend)
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="splunk",  # or "elasticsearch", "datadog", "console", etc.
    splunk_url="https://splunk.example.com:8088",
    splunk_token="your-hec-token",
)

# 2. Enable auto-instrumentation
auto_instrument()

# 3. Use your LLM libraries normally — they're now traced!
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What is observability?"}]
)
# ↑ Automatically captures: latency, tokens, cost, errors, model info

Option 2: Decorator-Based (Fine-Grained Control)

For explicit control over what gets traced:

from genai_telemetry import setup_telemetry, trace_llm

setup_telemetry(workflow_name="my-chatbot", exporter="console")

@trace_llm(model_name="gpt-4o", model_provider="openai")
def chat(message: str):
    from openai import OpenAI
    client = OpenAI()
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": message}]
    )
    return response  # Return full response to capture token counts

result = chat("Hello!")

Supported Frameworks (Auto-Instrumentation)

Framework What's Traced Status
OpenAI Chat completions, embeddings (sync + async) ✅ Supported
Anthropic Messages API (sync + async) ✅ Supported
Google AI (Gemini) generate_content, embeddings ✅ Supported
LangChain LLMs, chains, agents, retrievers, tools, embeddings ✅ Supported
LlamaIndex Query engines, retrievers, LLMs, embeddings ✅ Supported
CrewAI Agents, tasks, crews 🔜 Coming Soon
AutoGen Agents, conversations 🔜 Coming Soon
Haystack Pipelines, components 🔜 Coming Soon

Auto-Instrumentation API

from genai_telemetry import (
    auto_instrument,
    uninstrument,
    get_instrumented_frameworks,
    is_instrumented,
)

# Instrument all available frameworks
auto_instrument()

# Instrument specific frameworks only
auto_instrument(frameworks=["openai", "langchain"])

# Exclude specific frameworks
auto_instrument(exclude=["anthropic"])

# Check what's instrumented
print(get_instrumented_frameworks())  # ['openai', 'langchain', 'llamaindex']
print(is_instrumented("openai"))      # True

# Remove instrumentation
uninstrument()                        # Remove all
uninstrument(frameworks=["openai"])   # Remove specific

Supported Backends

Export telemetry to 10+ observability platforms:

Exporter Backend Key Parameters
splunk Splunk HEC splunk_url, splunk_token, splunk_index
elasticsearch Elasticsearch/OpenSearch es_hosts, es_api_key, es_index
otlp OpenTelemetry Collector otlp_endpoint, otlp_headers
datadog Datadog APM datadog_api_key, datadog_site
prometheus Prometheus Push Gateway prometheus_gateway
loki Grafana Loki loki_url, loki_tenant_id
cloudwatch AWS CloudWatch Logs cloudwatch_log_group, cloudwatch_region
console Console/stdout colored, verbose
file JSONL File file_path

Backend Examples

Splunk
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="splunk",
    splunk_url="https://splunk.example.com:8088",
    splunk_token="your-hec-token",
    splunk_index="genai_traces"
)
Elasticsearch
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="elasticsearch",
    es_hosts=["https://elasticsearch:9200"],
    es_api_key="your-api-key",
    es_index="genai-traces"
)
Datadog
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="datadog",
    datadog_api_key="your-api-key",
    datadog_site="datadoghq.com"
)
OpenTelemetry (Jaeger, Tempo, etc.)
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="otlp",
    otlp_endpoint="http://localhost:4318",
    otlp_headers={"Authorization": "Bearer your-token"}
)
Multiple Backends
setup_telemetry(
    workflow_name="my-chatbot",
    exporter=[
        {"type": "splunk", "url": "https://splunk:8088", "token": "xxx"},
        {"type": "elasticsearch", "hosts": ["http://es:9200"]},
        {"type": "console"}
    ]
)
Console (Development)
setup_telemetry(
    workflow_name="my-chatbot",
    exporter="console"
)

Available Decorators

For fine-grained control, use decorators on specific functions:

@trace_llm — LLM Completions

@trace_llm(model_name="gpt-4o", model_provider="openai")
def generate_response(prompt: str):
    return client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}]
    )

@trace_embedding — Embedding Calls

@trace_embedding(model="text-embedding-3-small")
def get_embeddings(texts: list):
    return client.embeddings.create(input=texts, model="text-embedding-3-small")

@trace_retrieval — Vector Store Queries

@trace_retrieval(vector_store="pinecone", embedding_model="text-embedding-3-small")
def search_documents(query: str):
    return vector_store.similarity_search(query, k=5)

@trace_tool — Tool/Function Calls

@trace_tool(tool_name="web_search")
def search_web(query: str):
    return search_api.search(query)

@trace_chain — Pipelines/Chains

@trace_chain(name="rag-pipeline")
def rag_pipeline(question: str):
    docs = retrieve(question)
    return generate(question, docs)

@trace_agent — Agent Executions

@trace_agent(agent_name="research-agent", agent_type="react")
def run_agent(task: str):
    return agent.execute(task)

What Gets Captured

Every trace includes:

{
  "trace_id": "abc123...",
  "span_id": "def456...",
  "parent_span_id": "ghi789...",
  "span_type": "LLM",
  "name": "openai.chat.completions.create",
  "workflow_name": "my-chatbot",
  "timestamp": "2024-01-15T10:30:00Z",
  "duration_ms": 1234.56,
  "status": "OK",
  "is_error": 0,
  "model_name": "gpt-4o",
  "model_provider": "openai",
  "input_tokens": 150,
  "output_tokens": 200,
  "total_tokens": 350,
  "session_id": "chat-42",
  "user_id": "alice@acme.com",
  "tags": ["beta"],
  "environment": "production",
  "prompt_name": "support-answer",
  "prompt_version": "3",
  "prompt_text": "[{\"role\": \"user\", \"content\": \"...\"}]",
  "response_text": "..."
}

session_id, user_id, tags, metadata, environment and release appear when set (1.3.0+). prompt_text / response_text appear only with capture_content=True.

Production Use: Splunk App

genai-telemetry powers the GenAI Observability for Splunk app on Splunkbase — a production-grade monitoring solution for GenAI workloads with:

  • Langfuse-style Traces, Sessions, Users, Scores, Datasets and Prompts pages (app 2.2+)
  • Pre-built dashboards (Overview, LLM Performance, RAG Analytics, Agent & Tools, Cost Management, etc.)
  • Trace Explorer for debugging individual requests
  • Real-time cost tracking and optimization recommendations
  • Pre-built alerts for errors, latency spikes, and cost anomalies

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                      Your Application                           │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │   OpenAI    │  │  Anthropic  │  │  LangChain  │  ...        │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘             │
│         │                │                │                     │
│         └────────────────┼────────────────┘                     │
│                          ▼                                      │
│              ┌───────────────────────┐                          │
│              │   genai-telemetry     │                          │
│              │   auto_instrument()   │                          │
│              └───────────┬───────────┘                          │
└──────────────────────────┼──────────────────────────────────────┘
                           │
                           ▼
        ┌──────────────────────────────────────┐
        │         Multi-Backend Export         │
        └──────────────────────────────────────┘
                           │
          ┌────────────────┼────────────────┐
          ▼                ▼                ▼
    ┌──────────┐    ┌──────────┐    ┌──────────┐
    │  Splunk  │    │ Elastic  │    │ Datadog  │  ...
    └──────────┘    └──────────┘    └──────────┘

Advanced Usage

Manual Span Creation

For custom operations:

from genai_telemetry import get_telemetry

telemetry = get_telemetry()

with telemetry.start_span("custom-operation", span_type="TOOL") as span:
    span.set_attribute("custom_field", "custom_value")
    result = do_something()

Direct Span Submission

telemetry.send_span(
    span_type="LLM",
    name="custom-llm-call",
    duration_ms=1500,
    model_name="claude-3-opus",
    model_provider="anthropic",
    input_tokens=100,
    output_tokens=200
)

Auto Content Extraction

Extract text content while still tracking tokens:

@trace_llm(model_name="gpt-4o", model_provider="openai", extract_content=True)
def chat(message: str):
    response = client.chat.completions.create(...)
    return response

answer = chat("Hello!")  # Returns just the string content
print(answer)  # "Hello! How can I help you today?"

Why genai-telemetry?

Feature genai-telemetry LangSmith Langfuse Phoenix
Open Source ✅ Apache 2.0 ❌ Proprietary ✅ MIT ✅ BSD
Multi-Backend (9+) ✅ ❌ ❌ ❌
Splunk Native ✅ ❌ ❌ ❌
Auto-Instrumentation ✅ ✅ ✅ ✅
Self-Hosted ✅ Enterprise only ✅ ✅
Vendor Neutral ✅ ❌ LangChain-focused ✅ ✅

Examples

See the examples/ directory for complete working examples:

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

📄 License

Apache 2.0 — see LICENSE for details.

Metadata

Release files for genai-telemetry 1.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for genai-telemetry 1.3.0
File Size Uploaded Provenance Actions
genai_telemetry-1.3.0.tar.gz 54.5 kB Without provenance Details for genai_telemetry-1.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for genai-telemetry 1.3.0
File Interpreter ABI Platform Actions
genai_telemetry-1.3.0-py3-none-any.whl Python 3 none any Details for genai_telemetry-1.3.0-py3-none-any.whl

Total release size: 113.7 kB

Release files / genai_telemetry-1.3.0.tar.gz

Download URL genai_telemetry-1.3.0.tar.gz
Size 54.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ac15471fe842929fa369cf74ab8d465049f9aa4c153fbac649fb658a956df69e
BLAKE2b-256 checksum
How to use checksums
c741ec0a5d7f787b8ffae52fded8faf7fa6743039c1a3458a9c8d5e79732c413
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / genai_telemetry-1.3.0-py3-none-any.whl

Download URL genai_telemetry-1.3.0-py3-none-any.whl
Size 59.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fe2f704702d6b9775914fbf961e2ed1da81fa9b8e68b60ac6e9d7c7d2ca74b9e
BLAKE2b-256 checksum
How to use checksums
85b90a025e5c5acc1cf015cd228a55b0e83a08151ebcef5c1b3963c3ee5d3906
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for genai-telemetry 1.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page