Metadata-Version: 2.5
Name: genkit-otel
Version: 0.14.0
Summary: OpenTelemetry GenAI semantic-conventions instrumentation for Genkit (traces, metrics, and message-content capture).
Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit-python/issues
Project-URL: Changelog, https://github.com/genkit-ai/genkit-python/releases
Project-URL: Documentation, https://genkit.dev/docs/get-started/?lang=python
Project-URL: Homepage, https://github.com/genkit-ai/genkit-python
Project-URL: Repository, https://github.com/genkit-ai/genkit-python
Author: Google
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: genai,genkit,observability,opentelemetry,otel,telemetry
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Framework :: Pydantic
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: genkit<2,>=0.14.0
Requires-Dist: opentelemetry-api>=1.38.0
Description-Content-Type: text/markdown

# genkit-otel

OpenTelemetry instrumentation and backend for [Genkit](https://github.com/genkit-ai/genkit-python).

It provides `GenAiInstrumentation`: OpenTelemetry GenAI semantic-conventions instrumentation emitting `gen_ai.*` spans and metrics.

## GenAI Semantic Conventions Instrumentation

Plugs into Genkit's pluggable instrumentation system and emits telemetry that follows the
[OTel GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai):

- `gen_ai.*` client spans for model operations (`chat <model>`), with request
  config, token usage, and finish reasons.
- The GenAI client metrics `gen_ai.client.token.usage` (split by
  `gen_ai.token.type`) and `gen_ai.client.operation.duration`.
- Optional message-content capture, either as span attributes or a dedicated
  `gen_ai.client.inference.operation.details` event.
- Optional `execute_tool` spans, and generic spans for other Genkit action
  types so the trace tree stays connected.

### Usage

The application owns the OpenTelemetry SDK and picks its exporter. Install
them alongside this package:

```sh
uv add genkit-otel opentelemetry-sdk opentelemetry-exporter-otlp
```

Initialize the SDK, then register the provider before creating `Genkit`:

```python
from opentelemetry import trace
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

from genkit import Genkit
from genkit.telemetry import configure_instrumentation
from genkit_otel import GenAiInstrumentation

resource = Resource.create({SERVICE_NAME: 'my-service'})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)

configure_instrumentation(GenAiInstrumentation())

ai = Genkit()
```

When the SDK is not initialized, the provider is effectively a no-op.

### Flushing before exit

`BatchSpanProcessor` and periodic metric readers buffer exports. A
serverless handler or a short script can return before they're sent. Call
`flush_instrumentations()` before the process freezes. It force-flushes the
global OTel tracer, meter, and logger providers. If a flush fails, it logs a
warning and doesn't raise:

```python
import asyncio

from genkit.telemetry import flush_instrumentations

# 1. Handle the request
response = await ai.generate(prompt='Suggest a dish for a peanut allergy.')

# 2. Drain buffered spans, metrics, and log events before returning
await asyncio.to_thread(flush_instrumentations)
```

If you passed `tracer`, `meter`, or `otel_logger` explicitly, flush the
provider you built them from. `GenAiInstrumentation` can't reach it.

### Content capture (PII)

Prompt and response content may contain PII, so capture is off by default.
`content_capturing_mode` is one of the spec tokens:

- **`NO_CONTENT`** (default): not captured.
- **`SPAN_ONLY`**: span attributes (`gen_ai.*.messages`) as JSON strings.
- **`EVENT_ONLY`**: a `gen_ai.client.inference.operation.details` log event.
- **`SPAN_AND_EVENT`**: both.

```python
from genkit_otel import GenAiInstrumentation

GenAiInstrumentation(content_capturing_mode='SPAN_ONLY')
```

Or omit the token and set the env. Same four tokens. Same result:

```bash
export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY
```

```python
GenAiInstrumentation()
```

A token on the constructor wins over the env var, including an explicit
`NO_CONTENT`. Garbage in the env var warns and stays `NO_CONTENT`.

To annotate a config field or variable, import the type:

```python
from genkit_otel import ContentCapturingMode

mode: ContentCapturingMode = 'SPAN_ONLY'
```

> `EVENT_ONLY` emits content on the OpenTelemetry logs signal (a
> `gen_ai.client.inference.operation.details` log record), not on the span.
> Trace-only backends like Jaeger cannot display it (its GenAI tab reads span
> attributes; its "Trace Logs" tab reads span events, neither is the logs
> signal). Use `SPAN_ONLY` or `SPAN_AND_EVENT` for Jaeger, or a logs backend
> (e.g. Loki, Elasticsearch/OpenSearch) for `EVENT_ONLY`.

### Options

- **`content_capturing_mode`** (env var, else `NO_CONTENT`): where spec-shaped `gen_ai.*` message content is recorded.
- **`capture_action_io`** (`False`): records raw Genkit input/output as `genkit.input`/`genkit.output` on every span (debugging / Dev UI).
- **`emit_metrics`** (`True`): emits token-usage and operation-duration metrics.
- **`emit_tool_spans`** (`False`): emits `execute_tool` spans for tool actions.
- **`scope_name`** (`genkit-genai`): instrumentation scope for the tracer, meter and logger.
- **`tracer` / `meter` / `otel_logger`** (resolved lazily): explicit instances to use instead of the process-global ones.

## Example

See [`samples/otel-jaeger`](../../samples/otel-jaeger) for a runnable sample
that exports traces to Jaeger and metrics to a local collector. `./tool/telemetry.sh`
downloads Jaeger and otelcol-contrib and keeps them running.
