diff --git a/CHANGELOG.md b/CHANGELOG.md index 968ed83c7..eb9ab6f9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Tools registered from an MCP server (via `.register_mcp_tools_stdio_async()`, `.register_mcp_tools_http_stream_async()`, or `Tool.from_mcp()`) now pass the tool result's `_meta` through to the `ContentToolResult`'s `extra` field. This lets MCP servers attach client-only metadata that isn't sent to the model — for example, shinychat's `display` hints, so a server can ask compatible chat UIs to open the tool-result card by default. Errored results still raise and never surface `_meta`. * MCP tool results that carry `structuredContent` now use it as the tool result's value (JSON-dumped for the model), instead of dropping it. The converted content blocks are preserved client-side under the `extra["content"]` key, merged with the `_meta` passthrough described above. * Providers now expose a `base_url` attribute (`chat.provider.base_url`) reporting the endpoint requests are sent to, when the provider can determine it. This is groundwork for richer telemetry (e.g. OpenTelemetry `server.address`/`server.port` attributes) and is handy for confirming which endpoint a provider resolved. +* The OpenTelemetry integration now emits **metrics** alongside spans, following the [GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/): per-request inference duration and token-usage histograms (`gen_ai.client.inference.*`), cumulative token-usage counters (including cache-read and reasoning tokens, broken down by `gen_ai.token.modality`), streaming latency (`gen_ai.client.inference.time_to_first_chunk`, `gen_ai.client.inference.time_per_output_chunk`), tool execution duration (`gen_ai.execute_tool.duration`), and per-invocation agent metrics (`gen_ai.invoke_agent.duration`, `gen_ai.invoke_agent.inference_calls`, `gen_ai.invoke_agent.tool_calls`). Metrics flow through the same SDK configuration as traces, so no extra setup is needed. +* OpenTelemetry spans are richer and more accurate. Chat spans now record `server.address`/`server.port`, the request parameters actually sent (`gen_ai.request.*`, including `gen_ai.request.stream` and reasoning effort), the finish reason (`gen_ai.response.finish_reasons`), cache-read and reasoning token counts, time to first chunk, and (with content capture enabled) the tool definitions sent with the request. The `invoke_agent` span is now an `internal`-kind span and records duration, inference/tool call counts, and total token usage. Successful requests are now marked with an `OK` span status (previously unset), and failed, cancelled (`StreamController.cancel()`), and interrupted (e.g. abandoned streams) requests now report an error status and `error.type` on both the spans and the duration metrics, matching ellmer. * The result of `chat.files.get()` (and elements of `chat.files.list()`) can now be passed straight to `.chat()` (and anywhere else content is accepted), so a file uploaded in an earlier session can be reused from its id alone: `chat.chat("Summarize this.", chat.files.get("file_011CRabc..."))`. When the provider doesn't report a MIME type (OpenAI's Files API never does), it's guessed from the filename. For when you want the underlying `ContentUploaded` reference itself (e.g. to build a `UserTurn` by hand), `FileMetadata` gains a `.to_content()` method. This works via a new general convention: any object implementing `to_content() -> Content` (see `chatlas.types.SupportsContent`) is accepted anywhere content is passed, so third-party packages can make their own objects usable as chat inputs. (#417) ### Changes diff --git a/chatlas/_chat.py b/chatlas/_chat.py index 321b727da..d472df0cc 100644 --- a/chatlas/_chat.py +++ b/chatlas/_chat.py @@ -63,11 +63,22 @@ from ._logging import log_tool_error from ._mcp_manager import MCPSessionManager from ._otel import ( + AgentOtelTally, activate_span, end_span, - record_chat_result, + record_agent_otel, + record_chat_chunk, + record_chat_span_error, + record_chat_span_interrupted, + record_chat_span_ok, + record_chat_span_output, + record_chat_span_status, + record_chat_ttft, record_chat_ttft_attr, record_error, + record_request_params, + record_tool_otel_interrupted, + record_tool_otel_result, start_agent_span, start_chat_span, start_tool_span, @@ -2756,10 +2767,12 @@ def _chat_impl( controller: StreamController, ) -> Generator[str | Content, None, None]: agent_span = start_agent_span(self.provider, self._conversation_id) + agent_tally = AgentOtelTally() try: user_turn_result: UserTurn | None = user_turn while user_turn_result is not None: - for chunk in self._submit_turns( + agent_tally.note_request() + turn_generator = self._submit_turns( user_turn_result, echo=echo, stream=stream, @@ -2768,15 +2781,24 @@ def _chat_impl( content_mode=content, controller=controller, _otel_parent=agent_span, - ): - yield chunk + ) + try: + for chunk in turn_generator: + yield chunk + finally: + # Close deterministically so an abandoned stream unwinds + # the chat span (recording it as interrupted) before the + # agent span records and ends. + turn_generator.close() turn = self.get_last_turn(role="assistant") assert turn is not None + agent_tally.note_turn(turn) user_turn_result = None # Don't invoke tools if the stream was cancelled if controller.cancelled: + agent_tally.error_type = "cancelled" break all_results: list[ContentToolResult] = [] @@ -2790,19 +2812,24 @@ def _chat_impl( if content == "all": yield x results = self._invoke_tool(x, _otel_parent=agent_span) - for res in results: - if echo == "output": - self._echo_content(res) - if content == "all": - yield res - all_results.append(res) + try: + for res in results: + if echo == "output": + self._echo_content(res) + if content == "all": + yield res + all_results.append(res) + finally: + results.close() if all_results: user_turn_result = UserTurn(all_results) + agent_tally.completed = True except Exception as e: - record_error(agent_span, e) + agent_tally.error_type = type(e).__name__ raise finally: + record_agent_otel(agent_span, self.provider, agent_tally) end_span(agent_span) @overload @@ -2843,9 +2870,11 @@ async def _chat_impl_async( controller: StreamController, ) -> AsyncGenerator[str | Content, None]: agent_span = start_agent_span(self.provider, self._conversation_id) + agent_tally = AgentOtelTally() try: user_turn_result: UserTurn | None = user_turn while user_turn_result is not None: + agent_tally.note_request() turn_generator = self._submit_turns_async( user_turn_result, echo=echo, @@ -2864,10 +2893,12 @@ async def _chat_impl_async( turn = self.get_last_turn(role="assistant") assert turn is not None + agent_tally.note_turn(turn) user_turn_result = None # Don't invoke tools if the stream was cancelled if controller.cancelled: + agent_tally.error_type = "cancelled" break all_results: list[ContentToolResult] = [] @@ -2881,21 +2912,26 @@ async def _chat_impl_async( if content == "all": yield x results = self._invoke_tool_async(x, _otel_parent=agent_span) - async for res in results: - if echo == "output": - self._echo_content(res) - if content == "all": - yield res - else: - yield "\n\n" - all_results.append(res) + try: + async for res in results: + if echo == "output": + self._echo_content(res) + if content == "all": + yield res + else: + yield "\n\n" + all_results.append(res) + finally: + await results.aclose() if all_results: user_turn_result = UserTurn(all_results) + agent_tally.completed = True except Exception as e: - record_error(agent_span, e) + agent_tally.error_type = type(e).__name__ raise finally: + record_agent_otel(agent_span, self.provider, agent_tally) end_span(agent_span) @overload @@ -2944,8 +2980,20 @@ def _submit_turns( request_turns = [*self._turns, user_turn] provider_turns = normalize_turns_for_provider(request_turns) chat_span = start_chat_span( - self.provider, request_turns, _otel_parent, self._conversation_id + self.provider, + request_turns, + _otel_parent, + self._conversation_id, + stream=stream, + data_model=data_model, + tools=self._tools, ) + # Measured from request issuance; the finally covers unwinds that no + # handler sees (e.g. a keyboard interrupt or an abandoned stream). + request_start: Optional[float] = time.monotonic() + # Set once the whole request path has completed; gates the OK stamp in + # the finally (stamped last since the SDK treats Ok as final). + succeeded = False try: def emit(x: str | Content): @@ -2971,6 +3019,9 @@ def emit(x: str | Content): # Start collecting additional keyword args (from model parameters) all_kwargs = self._collect_all_kwargs(kwargs) + for span in (chat_span, _otel_parent): + record_request_params(span, self._standard_model_params, all_kwargs) + if stream: # Activate the chat span only around the bounded provider calls # (this initial request and each chunk fetch below) so a @@ -2979,7 +3030,7 @@ def emit(x: str | Content): # consumer's scope. # Measured from request issuance; chat_perform() blocks until # headers arrive. - stream_start = time.monotonic() + stream_start: Optional[float] = time.monotonic() with activate_span(chat_span): response = self.provider.chat_perform( stream=True, @@ -2995,6 +3046,8 @@ def emit(x: str | Content): try: result = None + first_chunk_start: Optional[float] = request_start + last_chunk_time = request_start while True: try: with activate_span(chat_span): @@ -3004,6 +3057,16 @@ def emit(x: str | Content): if controller.cancelled: break result = self.provider.stream_merge_chunks(result, chunk) + if first_chunk_start is not None: + record_chat_ttft(self.provider, first_chunk_start) + first_chunk_start = None + else: + record_chat_chunk(self.provider, last_chunk_time) + # Taken after the chunk is merged but before its contents + # are yielded; consecutive timestamps give the interval + # between chunk arrivals, including any consumer time + # between pulls. + last_chunk_time = time.monotonic() for content in self.provider.stream_content( chunk, result, turns=provider_turns ): @@ -3017,6 +3080,20 @@ def emit(x: str | Content): yield from acc.flush_thinking(content_mode, emit) + # A cancelled stream is still a completed request (tokens + # and a response id may be known), but it reports an error + # status with `error.type = "cancelled"`, matching the + # finish reason set on the partial turn below. + record_chat_span_status( + chat_span, + self.provider, + result, + request_start, + error_type="cancelled" if controller.cancelled else None, + ) + # Duration recorded; skip it in the error handler/finally. + request_start = None + if not controller.cancelled: turn = self.provider.stream_turn( result, @@ -3027,12 +3104,19 @@ def emit(x: str | Content): if echo == "all": emit_other_contents(turn, emit) turn = finalize_assistant_turn(self.provider, turn) - record_chat_result(chat_span, turn) + record_chat_span_output(chat_span, turn) acc.complete_turn(turn) + else: + partial_turn = self._turns[-1] if self._turns else None + if isinstance(partial_turn, AssistantTurn): + record_chat_span_output(chat_span, partial_turn) finally: acc.finalize_turn() close_response(response) + if not controller.cancelled: + succeeded = True + else: with activate_span(chat_span): response = self.provider.chat_perform( @@ -3043,6 +3127,12 @@ def emit(x: str | Content): kwargs=all_kwargs, ) + record_chat_span_status( + chat_span, self.provider, response, request_start + ) + # Duration recorded; skip it in the error handler/finally. + request_start = None + turn = self.provider.value_turn( response, has_data_model=data_model is not None, @@ -3060,12 +3150,20 @@ def emit(x: str | Content): emit_other_contents(turn, emit) turn = finalize_assistant_turn(self.provider, turn) - record_chat_result(chat_span, turn) + record_chat_span_output(chat_span, turn) self._turns.extend([user_turn, turn]) + succeeded = True except Exception as e: - record_error(chat_span, e) + record_chat_span_error(chat_span, self.provider, e, request_start) + # Duration recorded (or nothing to record); the finally must not + # also record this request as interrupted. + request_start = None raise finally: + if succeeded: + record_chat_span_ok(chat_span) + if request_start is not None: + record_chat_span_interrupted(chat_span, self.provider, request_start) end_span(chat_span) @overload @@ -3111,8 +3209,20 @@ async def _submit_turns_async( request_turns = [*self._turns, user_turn] provider_turns = normalize_turns_for_provider(request_turns) chat_span = start_chat_span( - self.provider, request_turns, _otel_parent, self._conversation_id + self.provider, + request_turns, + _otel_parent, + self._conversation_id, + stream=stream, + data_model=data_model, + tools=self._tools, ) + # Measured from request issuance; the finally covers unwinds that no + # handler sees (e.g. a keyboard interrupt or an abandoned stream). + request_start: Optional[float] = time.monotonic() + # Set once the whole request path has completed; gates the OK stamp in + # the finally (stamped last since the SDK treats Ok as final). + succeeded = False try: def emit(x: str | Content): @@ -3138,6 +3248,9 @@ def emit(x: str | Content): # Start collecting additional keyword args (from model parameters) all_kwargs = self._collect_all_kwargs(kwargs) + for span in (chat_span, _otel_parent): + record_request_params(span, self._standard_model_params, all_kwargs) + if stream: # Activate the chat span only around the bounded provider calls # (this initial request and each chunk fetch below) so a @@ -3146,7 +3259,7 @@ def emit(x: str | Content): # consumer's scope. # Measured from request issuance; chat_perform_async() blocks # until headers arrive. - stream_start = time.monotonic() + stream_start: Optional[float] = time.monotonic() with activate_span(chat_span): response = await self.provider.chat_perform_async( stream=True, @@ -3162,6 +3275,8 @@ def emit(x: str | Content): try: result = None + first_chunk_start: Optional[float] = request_start + last_chunk_time = request_start while True: try: with activate_span(chat_span): @@ -3171,6 +3286,16 @@ def emit(x: str | Content): if controller.cancelled: break result = self.provider.stream_merge_chunks(result, chunk) + if first_chunk_start is not None: + record_chat_ttft(self.provider, first_chunk_start) + first_chunk_start = None + else: + record_chat_chunk(self.provider, last_chunk_time) + # Taken after the chunk is merged but before its contents + # are yielded; consecutive timestamps give the interval + # between chunk arrivals, including any consumer time + # between pulls. + last_chunk_time = time.monotonic() for content in self.provider.stream_content( chunk, result, turns=provider_turns ): @@ -3186,6 +3311,20 @@ def emit(x: str | Content): for item in acc.flush_thinking(content_mode, emit): yield item + # A cancelled stream is still a completed request (tokens + # and a response id may be known), but it reports an error + # status with `error.type = "cancelled"`, matching the + # finish reason set on the partial turn below. + record_chat_span_status( + chat_span, + self.provider, + result, + request_start, + error_type="cancelled" if controller.cancelled else None, + ) + # Duration recorded; skip it in the error handler/finally. + request_start = None + if not controller.cancelled: turn = self.provider.stream_turn( result, @@ -3196,12 +3335,19 @@ def emit(x: str | Content): if echo == "all": emit_other_contents(turn, emit) turn = finalize_assistant_turn(self.provider, turn) - record_chat_result(chat_span, turn) + record_chat_span_output(chat_span, turn) acc.complete_turn(turn) + else: + partial_turn = self._turns[-1] if self._turns else None + if isinstance(partial_turn, AssistantTurn): + record_chat_span_output(chat_span, partial_turn) finally: acc.finalize_turn() await aclose_response(response) + if not controller.cancelled: + succeeded = True + else: with activate_span(chat_span): response = await self.provider.chat_perform_async( @@ -3212,6 +3358,12 @@ def emit(x: str | Content): kwargs=all_kwargs, ) + record_chat_span_status( + chat_span, self.provider, response, request_start + ) + # Duration recorded; skip it in the error handler/finally. + request_start = None + turn = self.provider.value_turn( response, has_data_model=data_model is not None, @@ -3229,12 +3381,20 @@ def emit(x: str | Content): emit_other_contents(turn, emit) turn = finalize_assistant_turn(self.provider, turn) - record_chat_result(chat_span, turn) + record_chat_span_output(chat_span, turn) self._turns.extend([user_turn, turn]) + succeeded = True except Exception as e: - record_error(chat_span, e) + record_chat_span_error(chat_span, self.provider, e, request_start) + # Duration recorded (or nothing to record); the finally must not + # also record this request as interrupted. + request_start = None raise finally: + if succeeded: + record_chat_span_ok(chat_span) + if request_start is not None: + record_chat_span_interrupted(chat_span, self.provider, request_start) end_span(chat_span) def _collect_all_kwargs( @@ -3260,12 +3420,20 @@ def _invoke_tool( ): tool_span = start_tool_span(request, parent=_otel_parent) tool = self._tools.get(request.name) + # Measured from invocation start; the finally covers unwinds that no + # handler sees (e.g. a keyboard interrupt or an abandoned iteration). + tool_start = time.monotonic() + recorded = False + result: ContentToolResult | None = None try: if tool is None: error = RuntimeError("Unknown tool.") record_error(tool_span, error) - yield self._handle_tool_error_result(request, error=error) + result = self._handle_tool_error_result(request, error=error) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return if isinstance(tool, ToolBuiltIn): @@ -3274,17 +3442,22 @@ def _invoke_tool( "It should be handled by the provider." ) record_error(tool_span, error) - yield self._handle_tool_error_result(request, error=error) + result = self._handle_tool_error_result(request, error=error) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return # First, invoke the request callbacks. If a ToolRejectError is raised, # treat it like a tool failure (i.e., gracefully handle it). - result: ContentToolResult | None = None try: self._on_tool_request_callbacks.invoke(request) except ToolRejectError as e: record_error(tool_span, e) - yield self._handle_tool_error_result(request, e) + result = self._handle_tool_error_result(request, e) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return try: @@ -3324,8 +3497,17 @@ def _invoke_tool( except Exception as e: record_error(tool_span, e) - yield self._handle_tool_error_result(request, e) + result = self._handle_tool_error_result(request, e) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result + return + + record_tool_otel_result(request, tool_start, result) + recorded = True finally: + if not recorded: + record_tool_otel_interrupted(tool_span, request, tool_start) end_span(tool_span) async def _invoke_tool_async( @@ -3333,12 +3515,20 @@ async def _invoke_tool_async( ): tool_span = start_tool_span(request, parent=_otel_parent) tool = self._tools.get(request.name) + # Measured from invocation start; the finally covers unwinds that no + # handler sees (e.g. a keyboard interrupt or an abandoned iteration). + tool_start = time.monotonic() + recorded = False + result: ContentToolResult | None = None try: if tool is None: error = RuntimeError("Unknown tool.") record_error(tool_span, error) - yield self._handle_tool_error_result(request, error=error) + result = self._handle_tool_error_result(request, error=error) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return if isinstance(tool, ToolBuiltIn): @@ -3347,17 +3537,22 @@ async def _invoke_tool_async( "It should be handled by the provider." ) record_error(tool_span, error) - yield self._handle_tool_error_result(request, error=error) + result = self._handle_tool_error_result(request, error=error) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return # First, invoke the request callbacks. If a ToolRejectError is raised, # treat it like a tool failure (i.e., gracefully handle it). - result: ContentToolResult | None = None try: await self._on_tool_request_callbacks.invoke_async(request) except ToolRejectError as e: record_error(tool_span, e) - yield self._handle_tool_error_result(request, e) + result = self._handle_tool_error_result(request, e) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result return # Awaiting an async generator function's call fails, so it goes through wrap_async() @@ -3406,8 +3601,17 @@ async def _invoke_tool_async( except Exception as e: record_error(tool_span, e) - yield self._handle_tool_error_result(request, e) + result = self._handle_tool_error_result(request, e) + record_tool_otel_result(request, tool_start, result) + recorded = True + yield result + return + + record_tool_otel_result(request, tool_start, result) + recorded = True finally: + if not recorded: + record_tool_otel_interrupted(tool_span, request, tool_start) end_span(tool_span) def _handle_tool_error_result(self, request: ContentToolRequest, error: Exception): diff --git a/chatlas/_otel.py b/chatlas/_otel.py index ddc8f6f09..647427aa4 100644 --- a/chatlas/_otel.py +++ b/chatlas/_otel.py @@ -3,24 +3,244 @@ import os import time from contextlib import AbstractContextManager, nullcontext -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Mapping, Optional +from urllib.parse import urlparse import orjson -from opentelemetry import trace +from opentelemetry import metrics, trace from opentelemetry.trace import SpanKind, StatusCode -from ._content import ContentText, ContentToolRequest, ContentToolResult -from ._turn import SystemTurn, UserTurn +from ._content import Content, ContentText, ContentToolRequest, ContentToolResult +from ._tools import Tool +from ._turn import AssistantTurn, SystemTurn, UserTurn if TYPE_CHECKING: from opentelemetry.trace import Span - from ._content import Content - from ._provider import Provider - from ._turn import AssistantTurn, Turn + from ._provider import Provider, StandardModelParams + from ._turn import Turn tracer = trace.get_tracer("co.posit.python-package.chatlas") +meter = metrics.get_meter("co.posit.python-package.chatlas") + +# Histograms from the GenAI semantic conventions for metrics. The +# `gen_ai.client.inference.*` instruments are defined by the client inference +# conventions; the agent and tool instruments by the general metrics page. +# See: https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/client-inference.md +# See: https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/ +# +# The conventions advise explicit bucket boundaries for each histogram; they +# are passed as advisory parameters (the SDK, or user-configured views, may +# still override them). +_DURATION_BUCKETS: list[float] = [ + 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, + 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92, +] +_AGENT_DURATION_BUCKETS: list[float] = [ + 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, + 12.8, 25.6, 51.2, 102.4, 204.8, 409.6, +] +_TOKEN_BUCKETS: list[float] = [ + 1, 4, 16, 64, 256, 1024, 4096, 16384, + 65536, 262144, 1048576, 4194304, 16777216, 67108864, +] +_COUNT_BUCKETS: list[float] = [1, 2, 4, 8, 16, 32, 64, 128] + +# name -> (description, unit, advised bucket boundaries) +OTEL_HISTOGRAM_SPECS: dict[str, tuple[str, str, list[float]]] = { + "gen_ai.client.inference.duration": ( + "GenAI client inference operation duration", + "s", + _DURATION_BUCKETS, + ), + "gen_ai.client.inference.operation.input_tokens": ( + "Number of input tokens used per inference operation", + "{token}", + _TOKEN_BUCKETS, + ), + "gen_ai.client.inference.operation.output_tokens": ( + "Number of output tokens used per inference operation", + "{token}", + _TOKEN_BUCKETS, + ), + "gen_ai.client.inference.time_to_first_chunk": ( + "Time to receive the first chunk of a streamed response", + "s", + _DURATION_BUCKETS, + ), + "gen_ai.client.inference.time_per_output_chunk": ( + "Time per output chunk, for each chunk after the first", + "s", + _DURATION_BUCKETS, + ), + "gen_ai.execute_tool.duration": ( + "The duration of a single tool execution", + "s", + _DURATION_BUCKETS, + ), + "gen_ai.invoke_agent.duration": ( + "The end-to-end duration of a single agent invocation", + "s", + _AGENT_DURATION_BUCKETS, + ), + "gen_ai.invoke_agent.inference_calls": ( + "The number of inference calls made during an agent invocation", + "{inference_call}", + _COUNT_BUCKETS, + ), + "gen_ai.invoke_agent.tool_calls": ( + "The number of tool calls made during an agent invocation", + "{tool_call}", + _COUNT_BUCKETS, + ), +} + +# Monotonic token usage counters from the client inference conventions. Each +# counter is broken down by `gen_ai.token.modality`; providers only report +# totals, so chatlas reports the `unknown` modality. +# See: https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-token-metrics.md +OTEL_COUNTER_SPECS: dict[str, tuple[str, str]] = { + "gen_ai.client.inference.usage.input_tokens": ( + "Number of input tokens used, including cached tokens", + "{token}", + ), + "gen_ai.client.inference.usage.output_tokens": ( + "Number of output tokens used, including reasoning tokens", + "{token}", + ), + "gen_ai.client.inference.usage.cache_read.input_tokens": ( + "Number of input tokens served from a provider-managed cache", + "{token}", + ), + "gen_ai.client.inference.usage.reasoning.output_tokens": ( + "Number of output tokens used for reasoning", + "{token}", + ), +} + +# Instruments are created lazily so they bind to whatever MeterProvider is +# configured when they're first used (tests swap out `meter`). +_histograms: dict[str, metrics.Histogram] = {} +_counters: dict[str, metrics.Counter] = {} + + +def _get_histogram(name: str) -> metrics.Histogram: + histogram = _histograms.get(name) + if histogram is None: + description, unit, boundaries = OTEL_HISTOGRAM_SPECS[name] + histogram = meter.create_histogram( + name, + description=description, + unit=unit, + explicit_bucket_boundaries_advisory=boundaries, + ) + _histograms[name] = histogram + return histogram + + +def _get_counter(name: str) -> metrics.Counter: + counter = _counters.get(name) + if counter is None: + description, unit = OTEL_COUNTER_SPECS[name] + counter = meter.create_counter(name, description=description, unit=unit) + _counters[name] = counter + return counter + + +def record_histogram(name: str, value: float, attributes: Mapping[str, Any]) -> None: + _get_histogram(name).record(value, attributes=_clean_attributes(attributes)) + + +def record_counter(name: str, value: int, attributes: Mapping[str, Any]) -> None: + _get_counter(name).add(value, attributes=_clean_attributes(attributes)) + + +def _clean_attributes(attributes: Mapping[str, Any]) -> dict[str, Any]: + # `None` isn't a valid attribute value; treat it as unset. + return {k: v for k, v in attributes.items() if v is not None} + + +# `gen_ai.provider.name` well-known values, keyed by the provider's display +# name. Other providers fall back to the lowercased display name. +# See: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/ +OTEL_PROVIDER_NAMES: dict[str, str] = { + "Anthropic": "anthropic", + "AWS/Bedrock": "aws.bedrock", + "Azure/OpenAI": "azure.ai.openai", + "DeepSeek": "deepseek", + "Google/Gemini": "gcp.gemini", + "Google/Vertex": "gcp.vertex_ai", + "Groq": "groq", + "Mistral": "mistral_ai", + "OpenAI": "openai", + "Perplexity": "perplexity", +} + + +def otel_provider_name(provider: Provider[Any, Any, Any, Any]) -> str: + name = provider.name + return OTEL_PROVIDER_NAMES.get(name, name.lower()) + + +def otel_server_attributes(provider: Provider[Any, Any, Any, Any]) -> dict[str, Any]: + """`server.address` and `server.port` from the provider's base URL. + + The port falls back to the scheme default since semconv requires it when + the address is set. Providers that can't determine their endpoint + (`provider.base_url is None`) report nothing. + """ + base_url = provider.base_url + if base_url is None: + return {} + parsed = urlparse(str(base_url)) + if not parsed.hostname: + return {} + # urlparse strips the brackets around IPv6 literals, which semconv also + # omits from `server.address`. + attributes: dict[str, Any] = {"server.address": parsed.hostname} + try: + port = parsed.port + except ValueError: + # `.port` raises on a malformed port; treat that as absent. + port = None + if port is None: + port = {"https": 443, "http": 80}.get(parsed.scheme) + if port is not None: + attributes["server.port"] = port + return attributes + + +def otel_metric_attributes( + provider: Provider[Any, Any, Any, Any], + result: Any = None, +) -> dict[str, Any]: + attributes: dict[str, Any] = { + "gen_ai.operation.name": "chat", + "gen_ai.provider.name": otel_provider_name(provider), + "gen_ai.request.model": provider.model, + **otel_server_attributes(provider), + } + response_model = _response_model(result) + if response_model is not None: + attributes["gen_ai.response.model"] = str(response_model) + return attributes + + +def _response_model(result: Any) -> Any: + if result is None: + return None + if isinstance(result, Mapping): + return result.get("model") or result.get("model_version") + return getattr(result, "model", None) or getattr(result, "model_version", None) + + +def _response_id(result: Any) -> Any: + if result is None: + return None + if isinstance(result, Mapping): + return result.get("id") or result.get("response_id") + return getattr(result, "id", None) or getattr(result, "response_id", None) def capture_content() -> bool: @@ -35,14 +255,16 @@ def start_agent_span( ) -> Span: attributes: dict[str, Any] = { "gen_ai.operation.name": "invoke_agent", - "gen_ai.provider.name": provider.name.lower(), + "gen_ai.provider.name": otel_provider_name(provider), "gen_ai.request.model": provider.model, } if conversation_id is not None: attributes["gen_ai.conversation.id"] = conversation_id return tracer.start_span( "invoke_agent", - kind=SpanKind.CLIENT, + # chatlas's agent loop runs in-process, so this is the semconv + # `gen_ai.invoke_agent.internal` span. + kind=SpanKind.INTERNAL, attributes=attributes, ) @@ -52,17 +274,27 @@ def start_chat_span( turns: list[Turn], parent: Optional[Span], conversation_id: Optional[str] = None, + *, + stream: bool = False, + data_model: Any = None, + tools: Optional[Mapping[str, Any]] = None, ) -> Span: ctx = trace.set_span_in_context(parent) if parent is not None else None attributes: dict[str, Any] = { "gen_ai.operation.name": "chat", - "gen_ai.provider.name": provider.name.lower(), + "gen_ai.provider.name": otel_provider_name(provider), "gen_ai.request.model": provider.model, + **otel_server_attributes(provider), } if conversation_id is not None: # Per the GenAI semantic conventions, only set when a conversation # identifier is readily available; never invent a fallback value. attributes["gen_ai.conversation.id"] = conversation_id + if stream: + # Only set when streaming; unset means non-streaming per semconv. + attributes["gen_ai.request.stream"] = True + if data_model is not None: + attributes["gen_ai.output.type"] = "json" span = tracer.start_span( f"chat {provider.model}", kind=SpanKind.CLIENT, @@ -71,6 +303,10 @@ def start_chat_span( ) if capture_content() and span.is_recording(): + definitions = otel_tool_definitions(provider, tools, data_model) + if definitions: + span.set_attribute("gen_ai.tool.definitions", to_json(definitions)) + # Separate the system turn (recorded as system_instructions) from the # rest of the conversation (recorded as input.messages), per the GenAI # semantic conventions. @@ -81,6 +317,41 @@ def start_chat_span( return span +def otel_tool_definitions( + provider: Provider[Any, Any, Any, Any], + tools: Optional[Mapping[str, Any]], + data_model: Any = None, +) -> list[dict[str, Any]]: + # Built-in (provider-executed) tools have no argument schema, so only + # `Tool`s are recorded. Providers that implement structured output via + # tool calling add a private tool to the request; record it so the span + # matches. + definitions = [ + as_otel_tool_definition(tool) + for tool in (tools or {}).values() + if isinstance(tool, Tool) + ] + if data_model is not None: + structured_tool = provider.structured_output_tool(data_model) + if structured_tool is not None: + definitions.append(as_otel_tool_definition(structured_tool)) + return definitions + + +# A GenAI semconv tool definition for a Tool. +def as_otel_tool_definition(tool: Tool) -> dict[str, Any]: + function = tool.schema["function"] + parameters = function.get("parameters") + definition: dict[str, Any] = { + "type": "function", + "name": tool.name, + "description": function.get("description"), + # An empty schema isn't a useful JSON Schema object, so omit it. + "parameters": parameters if isinstance(parameters, dict) and parameters else None, + } + return _clean_attributes(definition) + + def start_tool_span( request: ContentToolRequest, parent: Optional[Span], @@ -113,44 +384,401 @@ def record_chat_ttft_attr(span: Span, start: float) -> None: ) -def record_chat_result( +# Sets the `gen_ai.request.*` attributes on a chat or invoke_agent span. +# Unlike ellmer (which learns of dropped params at request time), chatlas +# drops provider-unsupported standard params when they're set on the Chat, so +# everything in `params` was (or will be) sent. +def record_request_params( + span: Optional[Span], + params: StandardModelParams, + kwargs: Optional[Mapping[str, Any]], +) -> None: + if span is None or not span.is_recording(): + return + for name, value in otel_request_attributes(params, kwargs).items(): + span.set_attribute(name, value) + + +# Map the standard model params onto the `gen_ai.request.*` span attributes. +def otel_request_attributes( + params: StandardModelParams, + kwargs: Optional[Mapping[str, Any]], +) -> dict[str, Any]: + return _clean_attributes( + { + "gen_ai.request.temperature": params.get("temperature"), + "gen_ai.request.top_p": params.get("top_p"), + "gen_ai.request.top_k": params.get("top_k"), + "gen_ai.request.frequency_penalty": params.get("frequency_penalty"), + "gen_ai.request.presence_penalty": params.get("presence_penalty"), + "gen_ai.request.seed": params.get("seed"), + "gen_ai.request.max_tokens": params.get("max_tokens"), + "gen_ai.request.stop_sequences": params.get("stop_sequences"), + "gen_ai.request.reasoning.level": _reasoning_level(kwargs), + } + ) + + +def _reasoning_level(kwargs: Optional[Mapping[str, Any]]) -> Optional[str]: + # Reasoning effort isn't a standard chatlas param; each provider threads it + # through its own kwargs shape. Best-effort across the known ones + # (OpenAI's `reasoning={"effort": ...}`, Anthropic's + # `output_config={"effort": ...}`, the completions API's `reasoning_effort`, + # Google's `config={"thinking_config": {"thinking_level": ...}}`). + if not kwargs: + return None + for key in ("reasoning", "output_config"): + value = kwargs.get(key) + if isinstance(value, Mapping): + effort = value.get("effort") + if isinstance(effort, str): + return effort + config = kwargs.get("config") + if isinstance(config, Mapping): + thinking = config.get("thinking_config") + if isinstance(thinking, Mapping): + level = thinking.get("thinking_level") + if level is not None: + # google-genai's ThinkingLevel enum (e.g. ThinkingLevel.LOW) + value = getattr(level, "value", level) + if isinstance(value, str): + return value.lower() + effort = kwargs.get("reasoning_effort") + return effort if isinstance(effort, str) else None + + +# Records a completed model request: the operation duration, token usage +# histograms and counters, and the usage/response attributes on the chat +# span. A user-cancelled stream is still a completed request (tokens and +# response id may be known), but is reported with an error status and +# `error_type = "cancelled"` on the span and the duration metric, matching +# the `cancelled` finish reason set on the partial turn. +# +# A successful request's OK status is deliberately NOT set here: it is +# stamped later, via `record_chat_span_ok()`, once nothing more can fail. +def record_chat_span_status( span: Span, - turn: AssistantTurn[Any], + provider: Provider[Any, Any, Any, Any], + result: Any, + start: float, + error_type: Optional[str] = None, ) -> None: + attributes = otel_metric_attributes(provider, result) + record_histogram( + "gen_ai.client.inference.duration", + time.monotonic() - start, + {**attributes, "error.type": error_type}, + ) + + tokens = _safe_value_tokens(provider, result) + reasoning = _safe_value_reasoning_tokens(provider, result) or 0 + input_tokens = output_tokens = cached_input = 0 + if tokens is not None: + # tokens are (input, output, cached_input) + input_tokens = tokens[0] + tokens[2] + output_tokens = tokens[1] + cached_input = tokens[2] + + if input_tokens > 0 or output_tokens > 0: + record_histogram( + "gen_ai.client.inference.operation.input_tokens", + input_tokens, + attributes, + ) + record_histogram( + "gen_ai.client.inference.operation.output_tokens", + output_tokens, + attributes, + ) + usage = { + "gen_ai.client.inference.usage.input_tokens": input_tokens, + "gen_ai.client.inference.usage.output_tokens": output_tokens, + "gen_ai.client.inference.usage.cache_read.input_tokens": cached_input, + "gen_ai.client.inference.usage.reasoning.output_tokens": reasoning, + } + usage_attributes = {**attributes, "gen_ai.token.modality": "unknown"} + for name, value in usage.items(): + if value > 0: + record_counter(name, value, usage_attributes) + if not span.is_recording(): return - if turn.tokens is not None: - input_tokens, output_tokens, cached_input = turn.tokens - total_input = input_tokens + cached_input - if total_input > 0 or output_tokens > 0: - span.set_attribute("gen_ai.usage.input_tokens", total_input) - span.set_attribute("gen_ai.usage.output_tokens", output_tokens) - - completion = turn.completion - if completion is not None: - response_model = getattr(completion, "model", None) or getattr( - completion, "model_version", None - ) - if response_model is not None: - span.set_attribute("gen_ai.response.model", str(response_model)) + response_model = _response_model(result) + if response_model is not None: + span.set_attribute("gen_ai.response.model", str(response_model)) + response_id = _response_id(result) + if response_id is not None: + span.set_attribute("gen_ai.response.id", str(response_id)) + if input_tokens > 0 or output_tokens > 0: + span.set_attribute("gen_ai.usage.input_tokens", input_tokens) + span.set_attribute("gen_ai.usage.output_tokens", output_tokens) + if cached_input > 0: + span.set_attribute("gen_ai.usage.cache_read.input_tokens", cached_input) + if reasoning > 0: + span.set_attribute("gen_ai.usage.reasoning.output_tokens", reasoning) + + if error_type is not None: + span.set_status(StatusCode.ERROR) + span.set_attribute("error.type", error_type) + + +# Marks a successfully completed request OK. Set last -- once the whole +# request path (turn assembly, structured-output parsing, response cleanup) +# has finished -- because the SDK treats Ok as final: it overrides any prior +# Error and ignores any later one (the spec's `Ok > Error > Unset` total +# order), so stamping it earlier could mask a late failure. +def record_chat_span_ok(span: Span) -> None: + if not span.is_recording(): + return + span.set_status(StatusCode.OK) + + +def _safe_value_tokens( + provider: Provider[Any, Any, Any, Any], result: Any +) -> Optional[tuple[int, int, int]]: + # Telemetry must never break the chat: a partial (cancelled) result may + # not have usage info in the shape the provider expects. + if result is None: + return None + try: + return provider.value_tokens(result) + except Exception: + return None + + +def _safe_value_reasoning_tokens( + provider: Provider[Any, Any, Any, Any], result: Any +) -> Optional[int]: + if result is None: + return None + try: + return provider.value_reasoning_tokens(result) + except Exception: + return None + + +# Sets the finish reasons and (when content capture is enabled) the output +# messages on the chat span, from the completed (or cancelled) turn. +def record_chat_span_output(span: Span, turn: Turn) -> None: + if not span.is_recording(): + return + if not isinstance(turn, AssistantTurn): + return + # A partial turn only reaches here when the stream was cancelled; it + # reports a `cancelled` finish reason, matching `interrupted` from + # `record_chat_span_interrupted()`. + if turn.is_partial: + span.set_attribute("gen_ai.response.finish_reasons", ["cancelled"]) + elif turn.finish_reason is not None: + span.set_attribute("gen_ai.response.finish_reasons", [turn.finish_reason]) + if not capture_content(): + return + try: + msg = as_otel_message(turn) + span.set_attribute("gen_ai.output.messages", to_json([msg])) + except Exception: + pass + + +# Records a failed model request: the operation duration metric tagged with +# `error.type`, plus the exception and error status on the chat span. `start` +# is `None` once the duration has already been recorded for this request. +def record_chat_span_error( + span: Span, + provider: Provider[Any, Any, Any, Any], + error: Exception, + start: Optional[float], +) -> None: + if start is not None: + record_chat_duration_error(provider, type(error).__name__, start) + record_error(span, error) + if span.is_recording(): + span.set_attribute("gen_ai.response.finish_reasons", ["error"]) + - response_id = getattr(completion, "id", None) or getattr( - completion, "response_id", None +def record_chat_duration_error( + provider: Provider[Any, Any, Any, Any], + error_type: str, + start: float, +) -> None: + record_histogram( + "gen_ai.client.inference.duration", + time.monotonic() - start, + {**otel_metric_attributes(provider), "error.type": error_type}, + ) + + +# Records a model request that was unwound before it was recorded as a +# success or an error, e.g. by a keyboard interrupt or an abandoned stream. +# Runs from a `finally`, mirroring how `TurnAccumulator.finalize_turn()` +# marks the partial turn as interrupted from its own `finally`. +def record_chat_span_interrupted( + span: Span, + provider: Provider[Any, Any, Any, Any], + start: float, +) -> None: + record_chat_duration_error(provider, "interrupted", start) + if not span.is_recording(): + return + span.set_status(StatusCode.ERROR) + span.set_attribute("error.type", "interrupted") + span.set_attribute("gen_ai.response.finish_reasons", ["interrupted"]) + + +# Records the `gen_ai.client.inference.time_to_first_chunk` histogram. Per the +# client inference conventions, this is measured from request issuance to the +# first chunk received, whether or not that chunk contains model output. +# The span attribute is measured at the first non-empty token by +# `record_chat_ttft_attr()`. +# See: https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/client-inference.md +def record_chat_ttft( + provider: Provider[Any, Any, Any, Any], + start: float, +) -> None: + ttft = time.monotonic() - start + record_histogram( + "gen_ai.client.inference.time_to_first_chunk", + ttft, + otel_metric_attributes(provider), + ) + + +# Records the `gen_ai.client.inference.time_per_output_chunk` histogram. Per +# the client inference conventions, it is "recorded for each chunk received +# after the first one, measured as the time elapsed from the end of the +# previous chunk to the end of the current chunk". `previous_chunk_time` is +# the time the previous chunk was received. +def record_chat_chunk( + provider: Provider[Any, Any, Any, Any], + previous_chunk_time: float, +) -> None: + record_histogram( + "gen_ai.client.inference.time_per_output_chunk", + time.monotonic() - previous_chunk_time, + otel_metric_attributes(provider), + ) + + +# Per-invocation counts backing the invoke_agent span attributes and metrics. +class AgentOtelTally: + def __init__(self) -> None: + self.start = time.monotonic() + self.inference_calls = 0 + self.tool_calls = 0 + # (input, output, cached_input), summed over assistant turns + self.tokens = [0, 0, 0] + # `error.type` for the invocation: an error class name or "cancelled". + # An invocation that ends without completing or setting an error type + # was interrupted. + self.error_type: Optional[str] = None + self.completed = False + + # Inference calls are counted when the request starts (so failed requests + # are included); tool calls and tokens come from the completed turn. + def note_request(self) -> None: + self.inference_calls += 1 + + def note_turn(self, turn: AssistantTurn[Any]) -> None: + self.tool_calls += sum( + 1 for c in turn.contents if isinstance(c, ContentToolRequest) ) - if response_id is not None: - span.set_attribute("gen_ai.response.id", str(response_id)) + if turn.tokens is not None: + for i in range(3): + self.tokens[i] += turn.tokens[i] + + +# Records the invoke_agent metrics and, mirroring the chat span, also sets +# them as attributes on the invoke_agent span. +def record_agent_otel( + span: Span, + provider: Provider[Any, Any, Any, Any], + tally: AgentOtelTally, +) -> None: + attributes = otel_metric_attributes(provider) + attributes["gen_ai.operation.name"] = "invoke_agent" + error_type = tally.error_type or (None if tally.completed else "interrupted") + + duration = time.monotonic() - tally.start + # Only the duration metric defines `error.type` in the semantic conventions. + record_histogram( + "gen_ai.invoke_agent.duration", + duration, + {**attributes, "error.type": error_type}, + ) + record_histogram( + "gen_ai.invoke_agent.inference_calls", + tally.inference_calls, + attributes, + ) + record_histogram( + "gen_ai.invoke_agent.tool_calls", + tally.tool_calls, + attributes, + ) + + if not span.is_recording(): + return + span.set_attribute("gen_ai.invoke_agent.duration", duration) + span.set_attribute("gen_ai.invoke_agent.inference_calls", tally.inference_calls) + span.set_attribute("gen_ai.invoke_agent.tool_calls", tally.tool_calls) + if error_type is not None: + # The exception event is recorded once, on the chat or tool span where + # it occurred; the agent span only carries the status and error type. + span.set_status(StatusCode.ERROR) + span.set_attribute("error.type", error_type) + input_tokens = tally.tokens[0] + tally.tokens[2] + output_tokens = tally.tokens[1] + if input_tokens > 0 or output_tokens > 0: + span.set_attribute("gen_ai.usage.input_tokens", input_tokens) + span.set_attribute("gen_ai.usage.output_tokens", output_tokens) + + +def record_tool_otel_result( + request: ContentToolRequest, + start: float, + result: Optional[ContentToolResult], +) -> None: + error_type = None + if result is not None and result.error is not None: + error_type = _tool_error_type(result.error) + record_tool_otel_duration(request, start, error_type) - if capture_content(): - try: - msg = as_otel_message(turn) - span.set_attribute("gen_ai.output.messages", to_json([msg])) - except Exception: - pass - # Per the OTel spec, instrumentation libraries leave a successful span's - # status UNSET rather than marking it OK; errors are recorded via - # `record_error`. +def record_tool_otel_duration( + request: ContentToolRequest, + start: float, + error_type: Optional[str] = None, +) -> None: + record_histogram( + "gen_ai.execute_tool.duration", + time.monotonic() - start, + { + "gen_ai.operation.name": "execute_tool", + "gen_ai.tool.name": request.name, + "gen_ai.tool.type": "function", + "error.type": error_type, + }, + ) + + +def _tool_error_type(error: Any) -> str: + return "error" if isinstance(error, str) else type(error).__name__ + + +# The tool counterpart of `record_chat_span_interrupted()`: runs from a +# `finally` and records the call only if it was unwound before +# `record_tool_otel_result()` ran. +def record_tool_otel_interrupted( + span: Span, + request: ContentToolRequest, + start: float, +) -> None: + record_tool_otel_duration(request, start, "interrupted") + if not span.is_recording(): + return + span.set_status(StatusCode.ERROR) + span.set_attribute("error.type", "interrupted") def record_error(span: Span, error: Exception) -> None: @@ -224,15 +852,25 @@ def as_otel_part(content: Content) -> dict[str, Any]: part["id"] = content.request.id if content.error is not None: part["response"] = str(content.error) - elif isinstance(content.value, str): - part["response"] = content.value else: - part["response"] = json_safe(content.value) + part["response"] = tool_otel_response(content.value) return part return {"type": "generic", "class": type(content).__name__} +def tool_otel_response(value: Any) -> Any: + # `Content` values (e.g. an image) aren't JSON-serializable as-is, so + # convert them to otel parts rather than dropping the message. + if isinstance(value, Content): + return as_otel_part(value) + if isinstance(value, (list, tuple)) and all( + isinstance(v, Content) for v in value + ): + return [as_otel_part(v) for v in value] + return json_safe(value) + + def to_json(obj: Any) -> str: return orjson.dumps(obj).decode("utf-8") diff --git a/chatlas/_provider.py b/chatlas/_provider.py index e8e29840e..628696d69 100644 --- a/chatlas/_provider.py +++ b/chatlas/_provider.py @@ -386,6 +386,30 @@ def value_tokens( completion: ChatCompletionT, ) -> tuple[int, int, int] | None: ... + def value_reasoning_tokens( + self, + completion: ChatCompletionT, + ) -> int | None: + """ + Number of reasoning tokens in the completion, or None if the provider + does not report them separately. Used for the + `gen_ai.usage.reasoning.output_tokens` span attribute and usage counter. + """ + return None + + def structured_output_tool( + self, + data_model: type[BaseModel], + ) -> "Tool | None": + """ + The private tool added to the request to implement structured output, + if this provider implements `data_model` via tool calling. Returns + None for providers with native structured output support. Used to + record the tool definition on the OpenTelemetry chat span so the span + matches what the request contains. + """ + return None + def value_cost( self, completion: ChatCompletionT, diff --git a/chatlas/_provider_anthropic.py b/chatlas/_provider_anthropic.py index e6959a79c..753647908 100644 --- a/chatlas/_provider_anthropic.py +++ b/chatlas/_provider_anthropic.py @@ -593,6 +593,15 @@ def _chat_perform_args( return kwargs_full + def structured_output_tool(self, data_model: type[BaseModel]) -> "Tool | None": + mode = self._structured_output_mode + use_native = mode == "native" or ( + mode == "auto" and supports_structured_outputs(self.model) + ) + if use_native: + return None + return self.create_data_model_tool(data_model) + @staticmethod def create_data_model_tool(data_model: type[BaseModel]) -> Tool: def _structured_tool_call(**kwargs: Any): diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index e38437984..ccdd15f49 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -752,6 +752,11 @@ def _no_token_count_support() -> NotImplementedError: "(e.g. chat.get_last_turn().tokens)." ) + def structured_output_tool(self, data_model: type[BaseModel]) -> Tool: + # The Converse API has no native structured output support, so + # `data_model` is always implemented via a private tool call. + return AnthropicProvider.create_data_model_tool(data_model) + def translate_model_params(self, params: StandardModelParams) -> ConverseSubmitArgs: inference_config: InferenceConfigurationTypeDef = {} if "max_tokens" in params: @@ -791,7 +796,8 @@ def _chat_perform_args( tool_specs = [converse_tool_spec(tool) for tool in tools.values()] tool_config: Optional[ToolConfigurationTypeDef] = None if data_model is not None: - data_model_tool = AnthropicProvider.create_data_model_tool(data_model) + data_model_tool = self.structured_output_tool(data_model) + assert data_model_tool is not None tool_specs.append(converse_tool_spec(data_model_tool)) if tool_specs: diff --git a/chatlas/_provider_openai.py b/chatlas/_provider_openai.py index a0d8e26f1..6600c8c4e 100644 --- a/chatlas/_provider_openai.py +++ b/chatlas/_provider_openai.py @@ -456,6 +456,15 @@ def value_tokens(self, completion): cached_tokens, ) + def value_reasoning_tokens(self, completion): + usage = completion.usage + if usage is None: + return None + details = usage.output_tokens_details + if details is None: + return None + return details.reasoning_tokens + def value_cost( self, completion, diff --git a/chatlas/_provider_openai_completions.py b/chatlas/_provider_openai_completions.py index 334f8a325..a127971e5 100644 --- a/chatlas/_provider_openai_completions.py +++ b/chatlas/_provider_openai_completions.py @@ -369,6 +369,15 @@ def value_tokens(self, completion): cached_tokens, ) + def value_reasoning_tokens(self, completion): + usage = completion.usage + if usage is None: + return None + details = getattr(usage, "completion_tokens_details", None) + if details is None: + return None + return getattr(details, "reasoning_tokens", None) + def _turns_as_inputs(self, turns: list[Turn]) -> list["ChatCompletionMessageParam"]: res: list["ChatCompletionMessageParam"] = [] for turn in turns: diff --git a/docs/get-started/monitor.qmd b/docs/get-started/monitor.qmd index e32551daa..de38b90db 100644 --- a/docs/get-started/monitor.qmd +++ b/docs/get-started/monitor.qmd @@ -28,47 +28,53 @@ invoke_agent # wraps the full chat loop └── ... ``` -These spans are always emitted, but they go nowhere until you configure a backend to receive them. That's because chatlas depends only on the lightweight `opentelemetry-api` package, which defines spans without recording them. To actually capture and export traces, you install the OpenTelemetry **SDK** and point it at a destination — which is exactly what the next section does. +Chatlas records telemetry through the lightweight `opentelemetry-api` package. +The OpenTelemetry **SDK** collects and exports this data after you configure a destination. +The `opentelemetry-instrument` CLI can configure the SDK for you. ### Quick Start: Console Output -The simplest way to see chatlas spans is to print them to the console. Install the OTel SDK via the `otel` extra: +To print traces and metrics to the console, install the OTel SDK and its CLI: ```bash -pip install "chatlas[otel]" +pip install "chatlas[otel]" opentelemetry-distro ``` -Then configure a console exporter before creating any chats: +Save your chat code in `app.py`. +Run the app with `opentelemetry-instrument`: -```python -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor - -provider = TracerProvider() -provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter())) -trace.set_tracer_provider(provider) +```bash +opentelemetry-instrument \ + --traces_exporter console \ + --metrics_exporter console \ + --logs_exporter none \ + python app.py ``` -That's it — chatlas will automatically emit spans for every `chat()`, `stream()`, and tool invocation. +The CLI configures both tracing and metrics before the app starts. +Chatlas then emits telemetry for every `chat()`, `stream()`, and tool invocation. +Metrics export periodically and at shutdown. +Your app does not need provider or exporter setup code. ### A worked example -Here's a small travel assistant with a `get_weather` tool. The tool opens its own span (`fetch_forecast`) to represent the work it does, and we instrument [`httpx`](https://github.com/encode/httpx) — the HTTP library the provider SDKs use — so the underlying API request shows up too: +Here is a travel assistant with a `get_weather` tool. +The tool opens a span (`fetch_forecast`) for its own work. +Save the Python example as `app.py`, then run it with the console command. + +To include the underlying HTTP requests, install the [`httpx`](https://github.com/encode/httpx) instrumentor: ```bash pip install opentelemetry-instrumentation-httpx ``` +The CLI automatically enables installed instrumentors. + ```python import time from opentelemetry import trace -from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor from chatlas import ChatOpenAI -# Optional: nests the underlying HTTP call under each `chat` span -HTTPXClientInstrumentor().instrument() - tracer = trace.get_tracer("travel_assistant") def get_weather(city: str) -> str: @@ -93,7 +99,14 @@ Sent to a backend with a timeline view, the resulting trace looks like this: ![A trace waterfall showing the `invoke_agent` span over the full request, two `chat gpt-4o` spans for the model calls, an `execute_tool get_weather` span, and the nested `POST` and `fetch_forecast` spans underneath them.](/images/otel-trace.svg){class="rounded shadow mt-3" fig-alt="OpenTelemetry trace waterfall for a chatlas conversation with a tool call"} -Read top to bottom, this is the whole agent loop in one connected trace: the model decides to call the tool, the tool runs (with its own `fetch_forecast` work nested inside `execute_tool`), and a follow-up model call produces the answer. The two `POST` rows are the real HTTP requests, nested under their `chat` spans because chatlas keeps each span active while the provider call is in flight. Drop the `HTTPXClientInstrumentor` line and you'd still get the `invoke_agent`, `chat`, and `execute_tool` spans — just without the HTTP detail. +The trace shows the whole agent loop. +The model requests a tool, the tool runs, and a follow-up model call produces the answer. +The tool's `fetch_forecast` span captures its own work. + +The two `POST` spans represent HTTP requests inside the chat spans. +Chatlas keeps each chat span active while the provider call runs. +The HTTP instrumentor adds the `POST` spans. +Chatlas emits the agent, chat, and tool spans itself. By default the trace captures this *structure* but not the *message text* — the prompts and responses are omitted unless you opt in (see [Content Capture](#content-capture)). Instrumenting `httpx` is the simplest way to add lower-level HTTP detail; [Lower-level instrumentation](#lower-level-instrumentation) covers the full range of options. @@ -112,11 +125,14 @@ import logfire logfire.configure() ``` -Other OpenTelemetry-compatible backends (Datadog, Honeycomb, Jaeger, etc.) work too — just configure the appropriate exporter via the standard `opentelemetry-sdk` and `opentelemetry-exporter-*` packages. +This call configures both tracing and metrics. +A separate `MeterProvider` setup is not necessary. + +For other backends, use the [environment-based configuration](#environment-based-configuration) with `opentelemetry-instrument`. ### Configuration Module Pattern -For apps (especially Shiny apps), extract OTel setup into a dedicated module that runs before any other imports: +If your hosting platform starts the app directly, configure Logfire in a module that you import before the app code: ```python # otel_config.py @@ -133,15 +149,30 @@ from chatlas import ChatOpenAI ### Environment-based configuration -The OpenTelemetry SDK can read its exporter settings from [standard environment variables](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/), so you can point chatlas's traces at a backend without changing code — and without hard-coding the endpoint or its credentials in your app: +The CLI reads [standard environment variables](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/) to configure exporters. +To send traces and metrics to an OTLP-compatible collector or backend, install the OTLP exporters: ```bash -OTEL_EXPORTER_OTLP_ENDPOINT="https://logfire-eu.pydantic.dev" -OTEL_EXPORTER_OTLP_HEADERS="Authorization=" -OTEL_SERVICE_NAME="my-chatlas-app" +pip install "opentelemetry-distro[otlp]" + +export OTEL_TRACES_EXPORTER=otlp +export OTEL_METRICS_EXPORTER=otlp +export OTEL_LOGS_EXPORTER=none +export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf +export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318" +export OTEL_SERVICE_NAME="my-chatlas-app" + +opentelemetry-instrument python app.py ``` -These are read when the SDK is configured from the environment — for example, the zero-code `opentelemetry-instrument` approach [described below](#lower-level-instrumentation) — so the same app can run locally and in production with only its environment changed. Most hosting platforms let you set these per deployment; on [Posit Connect](https://posit.co/products/enterprise/connect/), for instance, you set them as [content environment variables](https://docs.posit.co/connect/user/content-settings/#setting-env-vars). +Replace the endpoint with your collector or backend address. +If the backend requires authentication, set `OTEL_EXPORTER_OTLP_HEADERS` to its required headers. +The CLI creates the tracing and metrics providers and their exporters before it starts the app. +Setting these variables alone does not configure the SDK in an app started with plain `python`. + +You can use the same app locally and in production with different environment variables. +Most hosting platforms let you set these per deployment. +On [Posit Connect](https://posit.co/products/enterprise/connect/), set them as [content environment variables](https://docs.posit.co/connect/user/content-settings/#setting-env-vars). Some platforms also emit their own OpenTelemetry data. Posit Connect (2026.02.0+) traces the *platform* — request latency, job queues, content execution and deployment — which administrators can export to the same backend. That's separate from the spans your app emits (Connect doesn't collect your application's traces for you), but sending both to one tool puts your chatlas traces alongside the platform activity around them. See Connect's [OpenTelemetry guide](https://docs.posit.co/connect/admin/opentelemetry/). @@ -149,13 +180,22 @@ Some platforms also emit their own OpenTelemetry data. Posit Connect (2026.02.0+ Chatlas follows the [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/), so attribute names (`gen_ai.*`) are consistent with other GenAI-instrumented libraries and are understood by OTel-aware backends out of the box. The lists below are representative rather than exhaustive — see the spec for the full set. -The **agent span** (`invoke_agent`) brackets the whole chat loop and records the provider and requested model (`gen_ai.provider.name`, `gen_ai.request.model`). +The **agent span** (`invoke_agent`) brackets the whole chat loop and records: + +- Provider and requested model (`gen_ai.provider.name`, `gen_ai.request.model`) +- How the invocation went: end-to-end duration, inference call and tool call counts (`gen_ai.invoke_agent.duration`, `gen_ai.invoke_agent.inference_calls`, `gen_ai.invoke_agent.tool_calls`), and total token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) +- An error status and `error.type` if the invocation failed, was cancelled, or was interrupted Each **chat span** (one per model API call) records: - Provider and requested model (`gen_ai.provider.name`, `gen_ai.request.model`) -- Token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) -- Response model and ID (`gen_ai.response.model`, `gen_ai.response.id`) +- Server address and port (`server.address`, `server.port`) +- Request parameters that were actually sent (`gen_ai.request.max_tokens`, `gen_ai.request.temperature`, `gen_ai.request.reasoning.level`, etc.), plus `gen_ai.request.stream` for streamed requests and `gen_ai.output.type` when structured output is requested +- Token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), including cache-read and reasoning tokens when the provider reports them (`gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.reasoning.output_tokens`) +- Response model and ID (`gen_ai.response.model`, `gen_ai.response.id`), plus the finish reason (`gen_ai.response.finish_reasons`) +- For streamed responses, time to first non-empty text or thinking token (`gen_ai.response.time_to_first_chunk`) +- Tool definitions sent with the request (`gen_ai.tool.definitions`, when content capture is enabled) +- An `OK` status on success, or an error status and `error.type` for failed (`RuntimeError`, etc.), `cancelled`, and `interrupted` requests - Optionally, the message content itself (system prompt, input messages, output messages) — see [Content Capture](#content-capture) below Each **tool span** (`execute_tool`, one per tool invocation) records: @@ -163,6 +203,38 @@ Each **tool span** (`execute_tool`, one per tool invocation) records: - Tool name, description, and call ID (`gen_ai.tool.name`, `gen_ai.tool.description`, `gen_ai.tool.call.id`) - Errors, if the tool raises (`error.type`, plus the exception is recorded on the span) +### Metrics + +Chatlas emits metrics defined by the [GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/). The OpenTelemetry SDK aggregates these measurements and exports them to your backend. + +The console and OTLP examples export both traces and metrics. +`logfire.configure()` also enables both by default. + +The SDK uses separate providers for tracing and metrics. +The metrics provider aggregates measurements and uses a metric reader to export them. +The CLI or Logfire supplies this configuration for your app. + +To export metrics every five seconds, set the interval before you start the app: + +```bash +export OTEL_METRIC_EXPORT_INTERVAL=5000 +``` + +The interval is in milliseconds. + +For each model API call: + +- `gen_ai.client.inference.duration` (histogram) — end-to-end request duration, tagged with `error.type` for failed, `cancelled`, or `interrupted` requests +- `gen_ai.client.inference.operation.input_tokens` / `gen_ai.client.inference.operation.output_tokens` (histograms) — token usage per call +- `gen_ai.client.inference.usage.input_tokens` / `gen_ai.client.inference.usage.output_tokens` / `gen_ai.client.inference.usage.cache_read.input_tokens` / `gen_ai.client.inference.usage.reasoning.output_tokens` (counters) — cumulative token usage, broken down by `gen_ai.token.modality` (currently always `unknown`, since providers only report totals) +- For streamed responses, `gen_ai.client.inference.time_to_first_chunk` and `gen_ai.client.inference.time_per_output_chunk` (histograms) + +For each tool invocation, `gen_ai.execute_tool.duration` (histogram), tagged with `error.type` when the tool fails or is interrupted. + +For each agent-loop invocation (one `chat()`/`stream()` call), `gen_ai.invoke_agent.duration`, `gen_ai.invoke_agent.inference_calls`, and `gen_ai.invoke_agent.tool_calls` (histograms). + +Model and agent metrics carry `gen_ai.provider.name`, `gen_ai.request.model`, `server.address`, and `server.port`, so you can group measurements by model or endpoint. Tool metrics carry `gen_ai.tool.name` and `gen_ai.tool.type`. + ### Content Capture Message content is **not** captured by default (it may contain sensitive data). To enable: @@ -261,12 +333,8 @@ To do this, you'll need to install the package: pip install opentelemetry-instrumentation-anthropic ``` -Then, add the following instrumentation code to your app: - -```python -from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor -AnthropicInstrumentor().instrument() -``` +Run your app with `opentelemetry-instrument`, as in the console quick start. +The CLI enables the installed Anthropic instrumentor automatically. ### Google diff --git a/pyproject.toml b/pyproject.toml index 6cdca7f85..20dcb5af2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,9 @@ dependencies = [ "orjson", "rich", "openai", - "opentelemetry-api>=1.0", + # OpenTelemetry 1.30 added explicit_bucket_boundaries_advisory, used to + # follow the GenAI semconv's advised histogram buckets. + "opentelemetry-api>=1.30", # `_typing_extensions.py` backfills from here on older interpreters; 3.13+ has # everything in `typing`. The floor is the release that added `TypeIs`. "typing-extensions>=4.10; python_version < '3.13'", @@ -46,7 +48,7 @@ Changelog = "https://github.com/posit-dev/chatlas/blob/main/CHANGELOG.md" otel = [ # opentelemetry-api is a hard dependency; the SDK is what users need to # configure a TracerProvider/exporter and actually emit chatlas spans. - "opentelemetry-sdk>=1.0", + "opentelemetry-sdk>=1.30", ] test = [ "pyright>=1.1.379", @@ -55,7 +57,7 @@ test = [ "syrupy>=4", "vcrpy>=6.0.0", "pytest-recording>=0.13", - "opentelemetry-sdk>=1.0", + "opentelemetry-sdk>=1.30", # vcrpy's aiohttp stub breaks on aiohttp 3.14+ (it references the removed # `aiohttp.streams.AsyncStreamReaderMixin`). Cap until vcrpy supports it. "aiohttp<3.14", @@ -84,7 +86,7 @@ dev = [ "snowflake-core>=1.5.0", "snowflake-snowpark-python", "tenacity", - "opentelemetry-sdk>=1.0", + "opentelemetry-sdk>=1.30", ] docs = [ "griffe>=1.3.2,<2.0.0", diff --git a/tests/test_otel.py b/tests/test_otel.py index f9959218c..c21ef0af2 100644 --- a/tests/test_otel.py +++ b/tests/test_otel.py @@ -3,26 +3,32 @@ import json from collections.abc import AsyncIterator, Iterator, Sequence from types import SimpleNamespace -from typing import cast +from typing import Any, cast import pytest pytest.importorskip("opentelemetry.sdk") -from chatlas import ChatOpenAI, _chat, _otel +from chatlas import ChatAnthropic, ChatGoogle, ChatOpenAI, _chat, _otel from chatlas._content import ( Content, + ContentImageInline, ContentText, ContentThinkingDelta, ContentToolRequest, ContentToolResult, ToolInfo, ) +from chatlas._stream_controller import StreamController from chatlas._tools import ToolBuiltIn -from chatlas._turn import AssistantTurn, Turn +from chatlas._turn import AssistantTurn, Turn, user_turn +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import InMemoryMetricReader from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from opentelemetry.trace import SpanKind +from pydantic import BaseModel @pytest.fixture(autouse=True) @@ -40,6 +46,96 @@ def otel_setup(): _otel.tracer = orig_tracer +@pytest.fixture +def otel_metrics(): + reader = InMemoryMetricReader() + provider = MeterProvider(metric_readers=[reader]) + + orig_meter = _otel.meter + _otel.meter = provider.get_meter("co.posit.python-package.chatlas") + # Instruments are cached per meter; don't leak them across tests. + _otel._histograms.clear() + _otel._counters.clear() + + yield reader + + _otel.meter = orig_meter + _otel._histograms.clear() + _otel._counters.clear() + + +def _metric_points(reader: InMemoryMetricReader) -> dict[str, list[Any]]: + """Flatten recorded metrics into data point lists named by instrument.""" + data = reader.get_metrics_data() + points: dict[str, list[Any]] = {} + for rm in data.resource_metrics: + for sm in rm.scope_metrics: + for metric in sm.metrics: + points.setdefault(metric.name, []).extend(metric.data.data_points) + return points + + +def _mock_completion( + chat: ChatOpenAI, + tokens: tuple[int, int, int] = (10, 5, 3), + reasoning: int | None = 2, +): + """Mock the (non-streaming) provider call to return a completion with + known usage info. ``tokens`` is (input, output, cached_input).""" + usage = SimpleNamespace( + input_tokens=tokens[0] + tokens[2], + output_tokens=tokens[1], + input_tokens_details=SimpleNamespace(cached_tokens=tokens[2]), + output_tokens_details=SimpleNamespace(reasoning_tokens=reasoning), + ) + completion = SimpleNamespace( + model="gpt-4o-mini-2024-07-18", + id="resp_123", + usage=usage, + service_tier=None, + ) + + def fake_value_turn(completion, has_data_model, turns=()): + return AssistantTurn( + "hi", + tokens=tokens, + finish_reason="success", + completion=completion, + ) + + chat.provider.chat_perform = lambda *args, **kwargs: completion # type: ignore[method-assign] + chat.provider.value_turn = fake_value_turn # type: ignore[method-assign] + return completion + + +def _mock_streaming_provider(chat: ChatOpenAI, n_chunks: int = 3): + def streaming_perform(*args, **kwargs): + def gen(): + for _ in range(n_chunks): + yield object() + + return gen() + + chat.provider.chat_perform = streaming_perform # type: ignore[method-assign] + chat.provider.stream_content = lambda chunk, completion, turns=(): [ # type: ignore[method-assign] + ContentText(text="hi") + ] + chat.provider.stream_merge_chunks = ( # type: ignore[method-assign] + lambda result, chunk: chunk + ) + chat.provider.stream_turn = ( # type: ignore[method-assign] + lambda completion, has_data_model, turns=(): AssistantTurn( + "hi", finish_reason="success" + ) + ) + + +def _finished_span(exporter: InMemorySpanExporter, prefix: str): + return next( + s for s in exporter.get_finished_spans() if s.name.startswith(prefix) + ) + + @pytest.mark.vcr def test_span_hierarchy_with_tools(otel_setup: InMemorySpanExporter): chat = ChatOpenAI( @@ -272,11 +368,10 @@ def test_streaming_span_lifecycle(otel_setup: InMemorySpanExporter): assert chat_span.end_time is not None, ( "Chat span should be finished after stream is consumed" ) - # Per the OTel spec, instrumentation libraries leave successful spans UNSET - # rather than marking them OK (OK is reserved for app/operator use and is - # treated as final, which would mask a later error on the same span). - assert chat_span.status.status_code.name == "UNSET", ( - f"Successful chat span should be UNSET, got {chat_span.status.status_code.name}" + # Successful requests are marked OK (matching ellmer), so dashboards can + # distinguish them from spans still in flight. + assert chat_span.status.status_code.name == "OK", ( + f"Successful chat span should be OK, got {chat_span.status.status_code.name}" ) # Time to first token is recorded on the streamed chat span. attrs = chat_span.attributes or {} @@ -295,6 +390,7 @@ def test_streaming_span_lifecycle(otel_setup: InMemorySpanExporter): ) async def test_ttft_recorded_at_first_non_empty_token( otel_setup: InMemorySpanExporter, + otel_metrics: InMemoryMetricReader, monkeypatch: pytest.MonkeyPatch, async_mode: bool, first_content: ContentText | ContentThinkingDelta, @@ -365,6 +461,10 @@ def stream_turn( assert len(chat_spans) == 1 attrs = chat_spans[0].attributes or {} assert attrs.get("gen_ai.response.time_to_first_chunk") == 5.0 + points = _metric_points(otel_metrics)["gen_ai.client.inference.time_to_first_chunk"] + assert len(points) == 1 + assert points[0].count == 1 + assert points[0].sum == 2.0 def test_chat_error_recorded(otel_setup: InMemorySpanExporter): @@ -759,3 +859,550 @@ async def get_date(): assert _parent_span_id(db_span) == tool_span.context.span_id, ( "span created inside an async generator tool should nest under the execute_tool span" ) + + +# --------------------------------------------------------------------------- +# GenAI semantic convention attributes and metrics +# --------------------------------------------------------------------------- + + +def test_agent_and_chat_span_kinds(otel_setup: InMemorySpanExporter): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + agent_span = _finished_span(otel_setup, "invoke_agent") + chat_span = _finished_span(otel_setup, "chat ") + # chatlas's agent loop runs in-process, so invoke_agent is an internal span + assert agent_span.kind == SpanKind.INTERNAL + assert chat_span.kind == SpanKind.CLIENT + + +def test_chat_span_status_ok_on_success(otel_setup: InMemorySpanExporter): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + assert chat_span.status.status_code.name == "OK" + + +def test_chat_span_response_and_usage_attributes(otel_setup: InMemorySpanExporter): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat, tokens=(10, 5, 3), reasoning=2) + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("gen_ai.response.model") == "gpt-4o-mini-2024-07-18" + assert attrs.get("gen_ai.response.id") == "resp_123" + assert attrs.get("gen_ai.usage.input_tokens") == 13 + assert attrs.get("gen_ai.usage.output_tokens") == 5 + assert attrs.get("gen_ai.usage.cache_read.input_tokens") == 3 + assert attrs.get("gen_ai.usage.reasoning.output_tokens") == 2 + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("success",) + # Not a streaming request, so the stream attribute is left unset + assert "gen_ai.request.stream" not in attrs + + +def test_server_attributes_on_chat_span(otel_setup: InMemorySpanExporter): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("server.address") == "api.openai.com" + assert attrs.get("server.port") == 443 + + +def test_request_params_recorded_on_chat_and_agent_spans( + otel_setup: InMemorySpanExporter, +): + chat = ChatOpenAI(model="gpt-4o-mini") + chat.set_model_params(max_tokens=50, temperature=0.5) + # seed isn't supported by OpenAI's Responses API, so it's dropped (with a + # warning) at set-time and must not show up on the spans. + with pytest.warns(UserWarning, match="not supported"): + chat.set_model_params(seed=42) + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + for prefix in ("invoke_agent", "chat "): + span = _finished_span(otel_setup, prefix) + attrs = span.attributes or {} + assert attrs.get("gen_ai.request.max_tokens") == 50 + assert attrs.get("gen_ai.request.temperature") == 0.5 + assert "gen_ai.request.seed" not in attrs + assert "gen_ai.request.top_p" not in attrs + + +def test_reasoning_level_recorded_from_kwargs(otel_setup: InMemorySpanExporter): + chat = ChatOpenAI(model="gpt-5-mini", reasoning="low") + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("gen_ai.request.reasoning.level") == "low" + + +def test_output_type_and_tool_definitions_with_data_model( + otel_setup: InMemorySpanExporter, monkeypatch: pytest.MonkeyPatch +): + monkeypatch.setenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "true") + + class Person(BaseModel): + name: str + + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + + def get_date() -> str: + "Return the current date" + return "2026-05-12" + + chat.register_tool(get_date) + + turn = user_turn("Say hello.") + for _ in chat._submit_turns( + turn, + echo="none", + stream=False, + data_model=Person, + controller=StreamController(), + ): + pass + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("gen_ai.output.type") == "json" + + defs = json.loads(str(attrs["gen_ai.tool.definitions"])) + assert isinstance(defs, list) + # OpenAI implements structured output natively, so only user tools appear + assert [d["name"] for d in defs] == ["get_date"] + get_date_def = defs[0] + assert get_date_def["type"] == "function" + assert get_date_def["description"] == "Return the current date" + assert get_date_def["parameters"]["type"] == "object" + + +def test_tool_definitions_omitted_without_content_capture( + otel_setup: InMemorySpanExporter, +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + + def get_date() -> str: + "Return the current date" + return "2026-05-12" + + chat.register_tool(get_date) + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert "gen_ai.tool.definitions" not in attrs + + +def test_anthropic_structured_output_tool_modes(): + class Person(BaseModel): + name: str + + # claude-3-5 lacks native structured outputs, so a private tool is used + chat = ChatAnthropic(model="claude-3-5-sonnet-latest") + tool = chat.provider.structured_output_tool(Person) + assert tool is not None + assert tool.name == "_structured_tool_call" + + # Claude 4.5+ uses native structured outputs, so no tool is needed + chat = ChatAnthropic(model="claude-sonnet-4-5") + assert chat.provider.structured_output_tool(Person) is None + + # ...unless tool mode is forced + chat = ChatAnthropic(model="claude-sonnet-4-5", structured_output_mode="tool") + assert chat.provider.structured_output_tool(Person) is not None + + +def test_otel_provider_name_mapping(): + assert _otel.otel_provider_name(ChatOpenAI(model="gpt-4o-mini").provider) == "openai" + assert ( + _otel.otel_provider_name(ChatAnthropic(model="claude-sonnet-4-5").provider) + == "anthropic" + ) + + +def test_inference_metrics_recorded( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat, tokens=(10, 5, 3), reasoning=2) + chat.chat("Say hello.", stream=False) + + points = _metric_points(otel_metrics) + + duration = points["gen_ai.client.inference.duration"] + assert len(duration) == 1 + assert duration[0].count == 1 + assert duration[0].sum >= 0 + attrs = duration[0].attributes + assert "error.type" not in attrs + assert attrs["gen_ai.operation.name"] == "chat" + assert attrs["gen_ai.provider.name"] == "openai" + assert attrs["gen_ai.request.model"] == "gpt-4o-mini" + assert attrs["gen_ai.response.model"] == "gpt-4o-mini-2024-07-18" + assert attrs["server.address"] == "api.openai.com" + + in_hist = points["gen_ai.client.inference.operation.input_tokens"] + assert len(in_hist) == 1 + assert in_hist[0].sum == 13 + out_hist = points["gen_ai.client.inference.operation.output_tokens"] + assert len(out_hist) == 1 + assert out_hist[0].sum == 5 + + def counter_value(name: str) -> int: + pts = points[name] + assert len(pts) == 1 + assert pts[0].attributes["gen_ai.token.modality"] == "unknown" + assert pts[0].attributes["gen_ai.provider.name"] == "openai" + return pts[0].value + + assert counter_value("gen_ai.client.inference.usage.input_tokens") == 13 + assert counter_value("gen_ai.client.inference.usage.output_tokens") == 5 + assert counter_value("gen_ai.client.inference.usage.cache_read.input_tokens") == 3 + assert counter_value("gen_ai.client.inference.usage.reasoning.output_tokens") == 2 + + +def test_agent_metrics_and_span_attributes( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + + def get_date() -> str: + "Return the current date" + return "2026-05-12" + + chat.register_tool(get_date) + + usage = SimpleNamespace( + input_tokens=10, + output_tokens=5, + input_tokens_details=SimpleNamespace(cached_tokens=0), + output_tokens_details=SimpleNamespace(reasoning_tokens=None), + ) + completion = SimpleNamespace( + model="gpt-4o-mini-2024-07-18", id="resp_123", usage=usage, service_tier=None + ) + turns = [ + AssistantTurn( + [ContentToolRequest(id="call_1", name="get_date", arguments={})], + tokens=(10, 5, 0), + finish_reason="tool_use", + completion=completion, + ), + AssistantTurn( + "The date is 2026-05-12.", + tokens=(20, 8, 0), + finish_reason="success", + completion=completion, + ), + ] + chat.provider.chat_perform = lambda *args, **kwargs: completion # type: ignore[method-assign] + chat.provider.value_turn = lambda *args, **kwargs: turns.pop(0) # type: ignore[method-assign] + + chat.chat("What is today's date?", stream=False) + + agent_span = _finished_span(otel_setup, "invoke_agent") + attrs = agent_span.attributes or {} + assert attrs.get("gen_ai.invoke_agent.inference_calls") == 2 + assert attrs.get("gen_ai.invoke_agent.tool_calls") == 1 + assert isinstance(attrs.get("gen_ai.invoke_agent.duration"), float) + assert attrs.get("gen_ai.usage.input_tokens") == 30 + assert attrs.get("gen_ai.usage.output_tokens") == 13 + assert agent_span.status.status_code.name == "UNSET" + + points = _metric_points(otel_metrics) + assert points["gen_ai.invoke_agent.inference_calls"][0].sum == 2 + assert points["gen_ai.invoke_agent.tool_calls"][0].sum == 1 + agent_duration = points["gen_ai.invoke_agent.duration"][0] + assert "error.type" not in agent_duration.attributes + assert agent_duration.attributes["gen_ai.operation.name"] == "invoke_agent" + + tool_duration = points["gen_ai.execute_tool.duration"][0] + assert tool_duration.attributes["gen_ai.tool.name"] == "get_date" + assert tool_duration.attributes["gen_ai.tool.type"] == "function" + assert "error.type" not in tool_duration.attributes + + +def test_tool_error_duration_metric(otel_metrics: InMemoryMetricReader): + chat = ChatOpenAI(model="gpt-4o-mini") + request = ContentToolRequest(id="missing-tool", name="missing_tool", arguments={}) + + results = list(chat._invoke_tool(request)) + assert isinstance(results[0].error, RuntimeError) + + points = _metric_points(otel_metrics) + tool_duration = points["gen_ai.execute_tool.duration"][0] + assert tool_duration.attributes["gen_ai.tool.name"] == "missing_tool" + assert tool_duration.attributes["error.type"] == "RuntimeError" + + +def test_chat_error_duration_metric( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + + def boom(*args, **kwargs): + raise RuntimeError("provider blew up") + + chat.provider.chat_perform = boom # type: ignore[method-assign] + + with pytest.raises(RuntimeError, match="provider blew up"): + chat.chat("Say hello.", stream=False) + + points = _metric_points(otel_metrics) + duration = points["gen_ai.client.inference.duration"][0] + assert duration.attributes["error.type"] == "RuntimeError" + # No usage info is available for a failed request + assert "gen_ai.client.inference.operation.input_tokens" not in points + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("error",) + + agent_duration = points["gen_ai.invoke_agent.duration"][0] + assert agent_duration.attributes["error.type"] == "RuntimeError" + + +def test_streaming_ttft_and_chunk_metrics( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_streaming_provider(chat, n_chunks=3) + list(chat.stream("Say hello.")) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("gen_ai.request.stream") is True + ttft = attrs.get("gen_ai.response.time_to_first_chunk") + assert isinstance(ttft, float) and ttft >= 0 + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("success",) + assert chat_span.status.status_code.name == "OK" + + points = _metric_points(otel_metrics) + assert len(points["gen_ai.client.inference.time_to_first_chunk"]) == 1 + # One point per chunk after the first + chunk_points = points["gen_ai.client.inference.time_per_output_chunk"] + assert len(chunk_points) == 1 + assert chunk_points[0].count == 2 + + +def test_cancelled_stream_recorded_with_error_status( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_streaming_provider(chat, n_chunks=10) + ctrl = StreamController() + + chunks = [] + for chunk in chat.stream("Say hello.", controller=ctrl): + chunks.append(chunk) + ctrl.cancel() + assert len(chunks) == 1 + + chat_span = _finished_span(otel_setup, "chat ") + assert chat_span.status.status_code.name == "ERROR" + attrs = chat_span.attributes or {} + assert attrs.get("error.type") == "cancelled" + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("cancelled",) + + agent_span = _finished_span(otel_setup, "invoke_agent") + assert agent_span.status.status_code.name == "ERROR" + assert (agent_span.attributes or {}).get("error.type") == "cancelled" + + points = _metric_points(otel_metrics) + duration = points["gen_ai.client.inference.duration"][0] + assert duration.attributes["error.type"] == "cancelled" + agent_duration = points["gen_ai.invoke_agent.duration"][0] + assert agent_duration.attributes["error.type"] == "cancelled" + + # The partial turn is still preserved in the chat history + last = chat.get_last_turn(role="assistant") + assert last is not None and last.is_partial + + +def test_abandoned_stream_recorded_as_interrupted( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_streaming_provider(chat, n_chunks=10) + + gen = chat.stream("Say hello.") + next(gen) + # Abandoning the stream unwinds it without a success or error record + gen.close() + + chat_span = _finished_span(otel_setup, "chat ") + assert chat_span.status.status_code.name == "ERROR" + attrs = chat_span.attributes or {} + assert attrs.get("error.type") == "interrupted" + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ( + "interrupted", + ) + + agent_span = _finished_span(otel_setup, "invoke_agent") + assert (agent_span.attributes or {}).get("error.type") == "interrupted" + + points = _metric_points(otel_metrics) + duration = points["gen_ai.client.inference.duration"][0] + assert duration.attributes["error.type"] == "interrupted" + agent_duration = points["gen_ai.invoke_agent.duration"][0] + assert agent_duration.attributes["error.type"] == "interrupted" + + +@pytest.mark.vcr("test_span_hierarchy_with_tools.yaml") +@pytest.mark.asyncio +async def test_closing_async_stream_finishes_tool_before_agent( + otel_setup: InMemorySpanExporter, otel_metrics: InMemoryMetricReader +) -> None: + chat = ChatOpenAI( + model="gpt-4o-mini", + system_prompt="Always use the get_date tool to answer questions about the date.", + ) + + def get_date() -> str: + "Return the current date" + return "2026-05-12" + + chat.register_tool(get_date) + stream = await chat.stream_async("What is today's date?", content="all") + try: + request = await stream.__anext__() + result = await stream.__anext__() + finally: + await stream.aclose() + + assert isinstance(request, ContentToolRequest) + assert isinstance(result, ContentToolResult) + assert result.value == "2026-05-12" + assert [span.name for span in otel_setup.get_finished_spans()] == [ + "chat gpt-4o-mini", + "execute_tool get_date", + "invoke_agent", + ] + tool_duration = _metric_points(otel_metrics)["gen_ai.execute_tool.duration"] + assert len(tool_duration) == 1 + assert tool_duration[0].count == 1 + assert tool_duration[0].attributes["error.type"] == "interrupted" + + +def test_content_tool_result_value_becomes_otel_part(): + # A `Content` tool-result value (e.g. an image) converts to an otel part + # rather than stringifying or dropping the message. + img = ContentImageInline(image_content_type="image/png", data="aW1hZ2U=") + part = _otel.as_otel_part(ContentToolResult(value=img)) + assert part["response"] == {"type": "generic", "class": "ContentImageInline"} + + # A list of `Content` values converts element-wise. + result = ContentToolResult( + value=[ContentText(text="a"), ContentText(text="b")] + ) + part = _otel.as_otel_part(result) + assert part["response"] == [ + {"type": "text", "content": "a"}, + {"type": "text", "content": "b"}, + ] + + +def test_error_during_turn_build_not_masked_by_ok_status( + otel_setup: InMemorySpanExporter, +): + # The request itself succeeds, but building the turn from the response + # fails (e.g. a truncated data_model response raising in the provider). + # The span must report the error, not the OK that was nearly stamped: + # the SDK treats Ok as final and would otherwise mask the late failure. + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + + def bad_value_turn(completion, has_data_model, turns=()): + raise ValueError("response cannot be parsed") + + chat.provider.value_turn = bad_value_turn # type: ignore[method-assign] + + with pytest.raises(ValueError, match="cannot be parsed"): + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + assert chat_span.status.status_code.name == "ERROR" + attrs = chat_span.attributes or {} + assert attrs.get("error.type") == "ValueError" + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("error",) + # Usage from the completed request is still recorded + assert attrs.get("gen_ai.usage.input_tokens") == 13 + exc_events = [e for e in chat_span.events if e.name == "exception"] + assert len(exc_events) == 1 + + +def test_error_during_stream_turn_build_not_masked_by_ok_status( + otel_setup: InMemorySpanExporter, +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_streaming_provider(chat, n_chunks=2) + + def bad_stream_turn(completion, has_data_model, turns=()): + raise ValueError("response cannot be parsed") + + chat.provider.stream_turn = bad_stream_turn # type: ignore[method-assign] + + with pytest.raises(ValueError, match="cannot be parsed"): + list(chat.stream("Say hello.")) + + chat_span = _finished_span(otel_setup, "chat ") + assert chat_span.status.status_code.name == "ERROR" + attrs = chat_span.attributes or {} + assert attrs.get("error.type") == "ValueError" + assert tuple(attrs.get("gen_ai.response.finish_reasons") or ()) == ("error",) + + +def test_server_attributes_google(otel_setup: InMemorySpanExporter): + chat = ChatGoogle(model="gemini-2.5-flash") + completion = SimpleNamespace(model="gemini-2.5-flash", id="resp_123") + chat.provider.chat_perform = lambda *args, **kwargs: completion # type: ignore[method-assign] + chat.provider.value_turn = lambda *args, **kwargs: AssistantTurn("hi") # type: ignore[method-assign] + + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("server.address") == "generativelanguage.googleapis.com" + assert attrs.get("server.port") == 443 + + +def test_reasoning_level_recorded_for_google(otel_setup: InMemorySpanExporter): + chat = ChatGoogle(model="gemini-3-flash", reasoning="low") + completion = SimpleNamespace(model="gemini-3-flash", id="resp_123") + chat.provider.chat_perform = lambda *args, **kwargs: completion # type: ignore[method-assign] + chat.provider.value_turn = lambda *args, **kwargs: AssistantTurn("hi") # type: ignore[method-assign] + + chat.chat("Say hello.", stream=False) + + chat_span = _finished_span(otel_setup, "chat ") + attrs = chat_span.attributes or {} + assert attrs.get("gen_ai.request.reasoning.level") == "low" + + +def test_histogram_buckets_follow_semconv_advisory( + otel_metrics: InMemoryMetricReader, +): + chat = ChatOpenAI(model="gpt-4o-mini") + _mock_completion(chat) + chat.chat("Say hello.", stream=False) + + points = _metric_points(otel_metrics) + bounds = list(points["gen_ai.client.inference.duration"][0].explicit_bounds) + assert bounds == _otel._DURATION_BUCKETS + token_bounds = list( + points["gen_ai.client.inference.operation.input_tokens"][0].explicit_bounds + ) + assert token_bounds == _otel._TOKEN_BUCKETS diff --git a/tests/test_provider_base_url.py b/tests/test_provider_base_url.py index 76a6e6a9b..358ba9c8c 100644 --- a/tests/test_provider_base_url.py +++ b/tests/test_provider_base_url.py @@ -1,5 +1,6 @@ """Tests for the `Provider.base_url` attribute used by telemetry.""" +import pytest from chatlas import ChatAnthropic, ChatGoogle, ChatGroq, ChatOpenAI from chatlas._provider import Provider @@ -34,3 +35,16 @@ def test_google_base_url(): ChatGoogle().provider.base_url == "https://generativelanguage.googleapis.com/" ) + + +def test_bedrock_converse_base_url(monkeypatch: pytest.MonkeyPatch): + # Construction is offline-safe by design (credentials resolve lazily), + # but the region must be supplied explicitly in a config-less environment. + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "dummy") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "dummy") + from chatlas import ChatBedrock + + assert ( + ChatBedrock(aws_region="us-east-1").provider.base_url + == "https://bedrock-runtime.us-east-1.amazonaws.com" + )