|
| 1 | +"""OpenTelemetry adapter: forwards spans to an otel tracer. |
| 2 | +
|
| 3 | +:: |
| 4 | +
|
| 5 | + from ai.telemetry import otel |
| 6 | + otel.install() # uses the global TracerProvider |
| 7 | +
|
| 8 | +Span names and attributes follow the ``gen_ai`` semantic conventions, |
| 9 | +so LLM-aware viewers (Phoenix, Braintrust, Langfuse, Datadog, ...) |
| 10 | +render them natively. |
| 11 | +
|
| 12 | +The adapter also attaches each current-setting otel span to the otel |
| 13 | +context in the task that opened it, so raw otel spans a user creates |
| 14 | +inside a tool still parent correctly under ours — and our root spans |
| 15 | +nest under any raw otel span the caller already has open. Spans |
| 16 | +opened with ``set_as_current=False`` are never attached: they don't |
| 17 | +parent concurrent work in our tree, so they must not do it in otel's. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import json |
| 23 | +from typing import TYPE_CHECKING, Any |
| 24 | + |
| 25 | +from .. import errors, telemetry |
| 26 | + |
| 27 | +try: |
| 28 | + from opentelemetry import context as otel_context |
| 29 | + from opentelemetry import trace as otel_trace |
| 30 | +except ModuleNotFoundError as exc: # pragma: no cover |
| 31 | + raise errors.InstallationError( |
| 32 | + "could not import `opentelemetry`, which is required for the otel " |
| 33 | + 'telemetry adapter, you can install it with `pip install "ai[otel]"` ' |
| 34 | + 'or `uv add "ai[otel]"`' |
| 35 | + ) from exc |
| 36 | + |
| 37 | +if TYPE_CHECKING: |
| 38 | + from collections.abc import AsyncGenerator |
| 39 | + |
| 40 | + from ..types import messages as messages_ |
| 41 | + |
| 42 | + |
| 43 | +def _messages_json(messages: list[messages_.Message]) -> str: |
| 44 | + return "[" + ",".join(m.model_dump_json() for m in messages) + "]" |
| 45 | + |
| 46 | + |
| 47 | +def _name(sp: telemetry.Span) -> str: |
| 48 | + match sp.data: |
| 49 | + case telemetry.AiStreamSpanData() as d: |
| 50 | + return f"chat {d.model}" |
| 51 | + case telemetry.AiGenerateSpanData() as d: |
| 52 | + return f"generate_content {d.model}" |
| 53 | + case telemetry.ToolExecutionSpanData() as d: |
| 54 | + return f"execute_tool {d.tool_name}" |
| 55 | + case telemetry.RunSpanData() as d: |
| 56 | + return f"invoke_agent {d.agent}" |
| 57 | + case telemetry.LoopTurnSpanData() as d: |
| 58 | + return f"loop_turn {d.index}" |
| 59 | + case _: |
| 60 | + return sp.name |
| 61 | + |
| 62 | + |
| 63 | +def _attributes(sp: telemetry.Span) -> dict[str, Any]: |
| 64 | + attrs: dict[str, Any] = {} |
| 65 | + if sp.replay: |
| 66 | + attrs["ai.replay"] = True |
| 67 | + match sp.data: |
| 68 | + case telemetry.AiStreamSpanData() as d: |
| 69 | + attrs["gen_ai.operation.name"] = "chat" |
| 70 | + attrs["gen_ai.request.model"] = d.model |
| 71 | + attrs["gen_ai.input.messages"] = _messages_json(d.messages) |
| 72 | + if d.message is not None: |
| 73 | + attrs["gen_ai.output.messages"] = _messages_json([d.message]) |
| 74 | + if d.usage is not None: |
| 75 | + attrs["gen_ai.usage.input_tokens"] = d.usage.input_tokens |
| 76 | + attrs["gen_ai.usage.output_tokens"] = d.usage.output_tokens |
| 77 | + case telemetry.AiGenerateSpanData() as d: |
| 78 | + attrs["gen_ai.operation.name"] = "generate_content" |
| 79 | + attrs["gen_ai.request.model"] = d.model |
| 80 | + if d.message is not None: |
| 81 | + attrs["gen_ai.output.messages"] = _messages_json([d.message]) |
| 82 | + case telemetry.ToolExecutionSpanData() as d: |
| 83 | + attrs["gen_ai.operation.name"] = "execute_tool" |
| 84 | + attrs["gen_ai.tool.name"] = d.tool_name |
| 85 | + attrs["gen_ai.tool.call.id"] = d.tool_call_id |
| 86 | + if d.args is not None: |
| 87 | + attrs["gen_ai.tool.call.arguments"] = json.dumps( |
| 88 | + d.args, default=str |
| 89 | + ) |
| 90 | + if d.result is not None: |
| 91 | + attrs["gen_ai.tool.call.result"] = json.dumps( |
| 92 | + d.result, default=str |
| 93 | + ) |
| 94 | + if d.is_error: |
| 95 | + attrs["ai.tool.is_error"] = True |
| 96 | + case telemetry.RunSpanData() as d: |
| 97 | + attrs["gen_ai.operation.name"] = "invoke_agent" |
| 98 | + attrs["gen_ai.agent.name"] = d.agent |
| 99 | + attrs["gen_ai.request.model"] = d.model |
| 100 | + case telemetry.HookSpanData() as d: |
| 101 | + attrs["ai.hook.label"] = d.label |
| 102 | + attrs["ai.hook.type"] = d.hook_type |
| 103 | + attrs["ai.hook.status"] = d.status |
| 104 | + case telemetry.LoopTurnSpanData() as d: |
| 105 | + attrs["ai.loop_turn.index"] = d.index |
| 106 | + case telemetry.CustomSpanData() as d: |
| 107 | + for key, value in d.attributes.items(): |
| 108 | + attrs[key] = ( |
| 109 | + value |
| 110 | + if isinstance(value, str | bool | int | float) |
| 111 | + else repr(value) |
| 112 | + ) |
| 113 | + return attrs |
| 114 | + |
| 115 | + |
| 116 | +def install( |
| 117 | + *, tracer_provider: otel_trace.TracerProvider | None = None |
| 118 | +) -> telemetry.WrapSpanAdapter: |
| 119 | + """Create the otel adapter, register it, and return it. |
| 120 | +
|
| 121 | + Uses the global tracer provider unless one is passed. |
| 122 | + """ |
| 123 | + tracer = otel_trace.get_tracer("ai", tracer_provider=tracer_provider) |
| 124 | + |
| 125 | + @telemetry.wrap_span |
| 126 | + async def otel_spans(span: telemetry.Span) -> AsyncGenerator[None, Any]: |
| 127 | + # Parenting is ambient: the current otel context holds the |
| 128 | + # parent (ours attach below; a raw otel span the caller has |
| 129 | + # open works the same way), and it mirrors the framework's |
| 130 | + # parenting because only current-setting spans attach. |
| 131 | + otel_span = tracer.start_span(_name(span), start_time=span.started_at) |
| 132 | + # Mirror the framework's currentness: a set_as_current=False |
| 133 | + # span doesn't parent concurrent work in our tree, so it must |
| 134 | + # not become current in the otel context either. |
| 135 | + token = ( |
| 136 | + otel_context.attach(otel_trace.set_span_in_context(otel_span)) |
| 137 | + if span.set_as_current |
| 138 | + else None |
| 139 | + ) |
| 140 | + try: |
| 141 | + # Milestones resume the yield live and are forwarded right |
| 142 | + # away, so backends that render in-progress spans show them |
| 143 | + # as they happen; span end resumes with None. |
| 144 | + while (ev := (yield)) is not None: |
| 145 | + otel_span.add_event( |
| 146 | + ev.name, |
| 147 | + { |
| 148 | + k: v |
| 149 | + if isinstance(v, str | bool | int | float) |
| 150 | + else repr(v) |
| 151 | + for k, v in ev.attributes.items() |
| 152 | + }, |
| 153 | + timestamp=ev.time_ns, |
| 154 | + ) |
| 155 | + finally: |
| 156 | + if token is not None: |
| 157 | + otel_context.detach(token) |
| 158 | + for key, value in _attributes(span).items(): |
| 159 | + otel_span.set_attribute(key, value) |
| 160 | + if span.error is not None: |
| 161 | + if isinstance(span.error, Exception): |
| 162 | + otel_span.record_exception(span.error) |
| 163 | + otel_span.set_status( |
| 164 | + otel_trace.StatusCode.ERROR, str(span.error) |
| 165 | + ) |
| 166 | + otel_span.end(end_time=span.ended_at) |
| 167 | + |
| 168 | + telemetry.register(otel_spans) |
| 169 | + return otel_spans |
0 commit comments