diff --git a/README.md b/README.md index 35933b2..38791cc 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ variables: | `service_version` | `RIUS_SERVICE_VERSION` | none | Sets `service.version` on the resource. Unset leaves it off, so `OTEL_RESOURCE_ATTRIBUTES` can supply it. | | `disabled` | `RIUS_DISABLED` | `false` | Kill switch. When true, spans are created but never exported. | | `sample_rate` | `RIUS_SAMPLE_RATE` | `1.0` | Head sampling ratio `0.0`–`1.0` (whole-trace; children follow root). | -| `capture_content` | `RIUS_CAPTURE_CONTENT` | `true` | When false, prompt/response content is stripped at export (metadata still sent). | +| `capture_content` | `RIUS_CAPTURE_CONTENT` | `true` | When false, prompt/response content is stripped at export (metadata still sent). When `RIUS_CAPTURE_CONTENT` is unset, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT` is read (see below). | | `bridge_foreign_provider` | `RIUS_BRIDGE_FOREIGN_PROVIDER` | `false` | Also export the spans of another OpenTelemetry SDK that owns the global provider (see below). | | `agent_name` | `RIUS_AGENT_NAME` | `service_name` | The agent this process is. Also the `gen_ai.main_agent.id` when `main_agent_id` is unset, so renaming it changes that id. | | `main_agent_id` | `RIUS_MAIN_AGENT_ID` | a `gen_ai.main_agent.id` in `OTEL_RESOURCE_ATTRIBUTES`, else the agent name | A stable id for the agent (a registry id or an ARN), stamped as `gen_ai.main_agent.id`. Never a per-process value. | @@ -149,6 +149,18 @@ rius.init(mask=lambda value, *, key: hash_pii(value) if "input" in key else valu rius.init(capture_content=False) # drop content entirely, keep metadata ``` +Content capture also follows the OpenTelemetry GenAI setting +`OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT` when `RIUS_CAPTURE_CONTENT` is +unset. `NO_CONTENT` turns capture off, and so does `EVENT_ONLY`, because Rius +records content on spans. `SPAN_ONLY` and `SPAN_AND_EVENT` keep it on. The value +is case-insensitive. An unrecognised one keeps capture on and logs a warning +naming the valid values (the OpenTelemetry conventions fall back to +`NO_CONTENT` instead). An empty value of either variable counts as unset (an +empty `RIUS_CAPTURE_CONTENT` also logs a warning). +The `capture_content` argument wins over both variables, and +`RIUS_CAPTURE_CONTENT` wins over the OpenTelemetry one. With neither set, +capture is on, unlike the OpenTelemetry default of `NO_CONTENT`. + ### Sessions, users and workspaces Three context managers scope every span started inside them, including the diff --git a/src/rius/_media.py b/src/rius/_media.py index 9478b3e..099cc0e 100644 --- a/src/rius/_media.py +++ b/src/rius/_media.py @@ -239,20 +239,45 @@ def replacement(mime: str | None, byte_size: int | None) -> str: _REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL = _rest.split("") -def is_replacement(value: str) -> bool: - """Already a complete replacement: never stripped again, never context. +#: 2^53 - 1 has 16 digits, so a run with more significant digits is past it. +_MAX_BYTE_SIZE_DIGITS = 16 - The format with a mime that is unknown or token/token and a byte_size of - ASCII digits or unknown; anything that only looks like one is a token. + +def parse_replacement(value: str) -> tuple[str | None, int | None] | None: + """The mime and byte_size a complete replacement names, each None when + unknown; None when ``value`` is no complete replacement (see + ``is_replacement``). + + The byte_size is the digit run read as a decimal number, leading zeros of + any length allowed. A run with more significant digits than 2^53 - 1 has + is None and is never converted: ``int()`` refuses a string over 4300 + digits, and this runs inside the export chain. The caller still bounds a + shorter one to 2^53 - 1, as for a byte_size the part has. """ head, between, tail = _REPLACEMENT_HEAD, _REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL if len(value) < len(head) + len(between) + len(tail): - return False + return None if not (value.startswith(head) and value.endswith(tail)): - return False + return None mime, sep, size = value[len(head) : len(value) - len(tail)].rpartition(between) digits = bool(size) and all("0" <= ch <= "9" for ch in size) - return bool(sep) and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN) + if not (sep and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN)): + return None + byte_size = None + if digits: + significant = size.lstrip("0") or "0" + if len(significant) <= _MAX_BYTE_SIZE_DIGITS: + byte_size = int(significant) + return (None if mime == UNKNOWN else mime), byte_size + + +def is_replacement(value: str) -> bool: + """Already a complete replacement: never stripped again, never context. + + The format with a mime that is unknown or token/token and a byte_size of + ASCII digits or unknown; anything that only looks like one is a token. + """ + return parse_replacement(value) is not None # --- the strip --------------------------------------------------------------- @@ -1445,7 +1470,9 @@ def native_part(part: Part) -> Part | None: * A blob carrying content becomes a stripped blob: sized from it, ``not_captured``, its modality from its MIME type first (some producers - label every file an image), else the one it has, else document. + label every file an image), else the one it has, else document. Content + that is a complete replacement gives its size, and its mime when the + part has no valid MIME type. * Any other part keeps a modality it has, else takes one from its MIME type, else (a uri) from its filename extension, else document. A blob without content keeps a valid size and stripped_reason. @@ -1457,6 +1484,14 @@ def native_part(part: Part) -> Part | None: part_type = part.get("type") mime = part.get("mime_type") if part_type == "blob" and isinstance(part.get("content"), str): + replaced = parse_replacement(part["content"]) + if replaced is not None: + # Bytes a strip already measured (an OTLP bytes value, a byte + # object): the size the base64 of the same bytes would give, and + # the part's own MIME type before the replacement's. + replaced_mime, size = replaced + kept = mime if is_mime(mime) else replaced_mime + return blob_part(own or "document", kept, safe_size(size), NOT_CAPTURED) return base64_blob(part["content"], own or "document", mime) if part_type == "uri" and is_data_url(part.get("uri")): return data_url_blob(part["uri"], own or "document", mime) diff --git a/src/rius/_semconv_generated.py b/src/rius/_semconv_generated.py index ac321dd..0db58a3 100644 --- a/src/rius/_semconv_generated.py +++ b/src/rius/_semconv_generated.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv v1.10.0 out/python/_semconv_generated.py by +# Vendored from rius-semconv v1.13.0 out/python/_semconv_generated.py by # scripts/sync-semconv.sh. Do not edit: change the registry in rius-semconv. """Rius semantic conventions: the constants and tables, generated. @@ -186,6 +186,7 @@ # OTel GenAI (subset we emit) GEN_AI_OPERATION_NAME = "gen_ai.operation.name" +GEN_AI_OPERATION_NAME_COMPACTION = "compaction" GEN_AI_PROVIDER_NAME = "gen_ai.provider.name" GEN_AI_REQUEST_MODEL = "gen_ai.request.model" GEN_AI_REQUEST_REASONING_LEVEL = "gen_ai.request.reasoning.level" @@ -340,9 +341,17 @@ # A free string, not an enum, in the registry. GEN_AI_TOOL_TYPE = "gen_ai.tool.type" -# The request's tool/function definitions, serialized verbatim (provider -# shapes differ; the backend reads names and sizes from either). Content, -# not identity, so it is listed in CONTENT_ATTRIBUTES. +# The request's tool/function definitions, in the conventions' shape +# where the SDKs recognise the provider's spelling: a function tool +# (OpenAI, Anthropic, Bedrock toolSpec, Gemini function declarations, +# the Vercel AI SDK) becomes {type: function, name, description, +# parameters}, and a provider's built-in tool keeps its fields with its +# type prefixed by the provider name. A built-in tool without a name +# (OpenAI's web_search, Gemini's google_search) stays without one on +# purpose: an invented name would read as a tool that was offered and +# never called. A definition in a shape the SDKs do not recognise is +# recorded as given. Content, not identity, so it is listed in +# CONTENT_ATTRIBUTES. GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions" # The arguments the model passed to the tool. The TypeScript SDK writes it @@ -610,6 +619,53 @@ # the OpenTelemetry naming rules do not allow for an attribute. RIUS_COMPACTION_SUMMARY_TEXT = "rius.compaction.summary.text" +# --- Agent hints --- +# A hint is a short note Rius sends to a running agent about a problem it +# detected in the agent's current run ("search_docs has returned 0 results +# 5 times in this run; lookup_index covers the same pages"). The SDK +# receives it on the heartbeat response and hands it to the agent: the +# agent's code pulls it, an on_hint callback receives it, or a framework +# hook adds it to the next model call. The rius.hint.* keys are the +# attributes of the rius.hint.delivered event the SDK records at that +# moment, and are never set on a span. No convention defines a hint or +# its delivery. +# The hint's id exactly as Rius sent it, the same on every redelivery. It +# is the join key to the record Rius keeps for each hint it writes, which +# holds the run the hint is about, its code, the text the agent received +# and when it was written, so a reader finds what the hint said and how +# long it took to arrive without the event repeating any of it. +# The SDK de-duplicates on the id, so a hint Rius sends again gives no +# second event on the same channel. A hint can reach the agent through +# more than one channel and gives one event for each: at most one per +# (rius.hint.id, rius.hint.channel). A count of hints delivered must +# deduplicate on rius.hint.id. +RIUS_HINT_ID = "rius.hint.id" + +# Which problem the hint is about, as Rius named it. Copied from the hint +# so that measuring whether hints help can group deliveries by detector +# straight from the trace. The SDK copies it and never interprets it. +# Not gen_ai.prompt.name: a hint is not a managed prompt, and the model +# call a hint is injected into may carry the agent's own +# gen_ai.prompt.name and gen_ai.prompt.version, naming that call's prompt. +RIUS_HINT_CODE = "rius.hint.code" + +# Each code's wording is versioned, and a change of wording bumps the +# version, so two wordings of the same hint can be compared. An int, as +# Rius sends it. Not gen_ai.prompt.version, for the reason given on +# rius.hint.code. +RIUS_HINT_TEMPLATE_VERSION = "rius.hint.template_version" + +# drain when the agent's own code pulled the hint (drain_hints()), +# callback when the SDK passed it to an on_hint callback, inject when a +# framework hook added it to a model call just before the call. Only +# inject guarantees the model saw the hint; with drain and callback the +# agent's code decides what to do with it. Measuring whether hints help +# needs to tell the two apart. +RIUS_HINT_CHANNEL = "rius.hint.channel" +RIUS_HINT_CHANNEL_DRAIN = "drain" +RIUS_HINT_CHANNEL_CALLBACK = "callback" +RIUS_HINT_CHANNEL_INJECT = "inject" + # --- Span event names --- # Deprecated: replaced by the gen_ai.response.time_to_first_chunk span attribute. # First streamed token/chunk arrived. The standard signal is the span @@ -633,6 +689,35 @@ # compacted context sets gen_ai.conversation.compacted. RIUS_COMPACTION_EVENT = "rius.compaction" +# Recorded when the SDK hands a hint to the agent: drain_hints() returns +# it, an on_hint callback receives it, or a framework hook adds it to a +# model call. For every channel, the event goes on the root span of the +# run the hint is about (the hint's trace_id). The SDK keeps each run's +# root span while the run is open, and Rius delivers a hint only while +# its run is open. A hint with no trace_id is about the instance as a +# whole: its event goes on the current span if one is recording, and +# otherwise no event is recorded. +# One run can get several hints, so its root span can carry several of +# these events, one per hint and channel: at most one per +# (rius.hint.id, rius.hint.channel). A count of hints delivered must +# deduplicate on rius.hint.id. +# It carries the rius.hint.* attributes and never the hint's text, which +# the record Rius keeps for each hint it writes holds under the id. +# It records delivery, not the acknowledgement on the heartbeat: an ack +# only tells Rius to stop sending the hint, and the SDK acks hints it +# drops as well. +# For inject, nothing else is needed to measure whether a hint helped. The +# hint's run is the trace the event sits in, and the model calls after the +# hint are the LLM spans of that trace that start after the event's +# timestamp. The hint's id joins the event to the record Rius keeps for each +# hint it writes (its code, its run, when it was written). A key on each +# later model call naming the hints it carried would repeat what that join +# gives. With drain or callback, this event only says the agent's code +# received the hint: the SDK cannot know whether the code passed it to the +# model, acted on it itself, or ignored it, so measuring those needs a +# record from the agent's code. +RIUS_HINT_DELIVERED_EVENT = "rius.hint.delivered" + # --- Pending (partial) spans --- # Marks the content-free snapshot exported at span START; the backend maps it # to Finished=0 and the real span replaces it at end. This key knowingly bends @@ -1466,10 +1551,17 @@ class SpanKind(str, Enum): # are LLM calls the same way chat is, and create_agent is an AGENT span # just as invoke_agent is, so the mapping is many-to-one and only the # chat/invoke_agent entries round-trip. -# - CHAIN has no operation of its own, but four operations land on it. -# invoke_workflow and plan are real GenAI operations with no taxonomy -# value of their own; CHAIN is the honest home for both, and the reverse -# direction is the only one that can say so. agent_step is not a +# - CHAIN has no operation of its own, but five operations land on it. +# invoke_workflow, invoke_runner and plan are real GenAI operations with +# no taxonomy value of their own; CHAIN is the honest home for all three, +# and the reverse direction is the only one that can say so. +# invoke_runner is a framework entrypoint (the call that starts a +# framework's run loop), which the conventions define as not being an +# agent, so CHAIN rather than AGENT. The conventions name entrypoint +# operations invoke_{framework_entrypoint} in general, so a table cannot +# list them all: every consumer maps an operation that starts with +# invoke_ and is not in this table to CHAIN as well. invoke_agent is in +# the table, so it keeps AGENT. agent_step is not a # conventions operation: the Vercel AI SDK's @ai-sdk/otel writes it on # each step of an agent run (one model call and the tools it asked # for), a step within the run rather than an agent invocation, so @@ -1500,6 +1592,7 @@ class SpanKind(str, Enum): "retrieval": SpanKind.RETRIEVER, "rerank": SpanKind.RERANKER, "invoke_workflow": SpanKind.CHAIN, + "invoke_runner": SpanKind.CHAIN, "plan": SpanKind.CHAIN, "agent_step": SpanKind.CHAIN, "compaction": SpanKind.CHAIN, @@ -1613,6 +1706,7 @@ class SpanKind(str, Enum): "GEN_AI_MAIN_AGENT_ID", "GEN_AI_MAIN_AGENT_NAME", "GEN_AI_OPERATION_NAME", + "GEN_AI_OPERATION_NAME_COMPACTION", "GEN_AI_OUTPUT_MESSAGES", "GEN_AI_OUTPUT_TYPE", "GEN_AI_PROVIDER_NAME", @@ -1741,6 +1835,14 @@ class SpanKind(str, Enum): "RIUS_COMPACTION_TRIGGER_AUTO", "RIUS_COMPACTION_TRIGGER_MANUAL", "RIUS_CONTEXT_SIZES", + "RIUS_HINT_CHANNEL", + "RIUS_HINT_CHANNEL_CALLBACK", + "RIUS_HINT_CHANNEL_DRAIN", + "RIUS_HINT_CHANNEL_INJECT", + "RIUS_HINT_CODE", + "RIUS_HINT_DELIVERED_EVENT", + "RIUS_HINT_ID", + "RIUS_HINT_TEMPLATE_VERSION", "RIUS_MAIN_AGENT_DESCRIPTION", "RIUS_MAIN_AGENT_ID", "RIUS_MAIN_AGENT_NAME", diff --git a/src/rius/_serde.py b/src/rius/_serde.py index 5d84b4e..65ef5f6 100644 --- a/src/rius/_serde.py +++ b/src/rius/_serde.py @@ -349,21 +349,64 @@ def serialize(value: Any) -> str: return f"" -def _bounded_dumps(value: Any) -> str: +def json_text(value: Any) -> str: + """``value`` as JSON text in the one encoding, neither stripped nor cut. + + For a value another instrumentation set structured where the conventions + also allow its JSON text: the text is then read and stripped exactly as + that string would be. So it is encoded whole, neither cut at the attribute + cap, where ``serialize`` would, nor at the strip budget: the text is the + very string the JSON form of the value is, and every pass after this one + treats the two alike (a blob's base64 past the budget is rebuilt and + stripped, as it is in that string). The value is already whole in memory + on the span, as that string would be. Never raises: a value the encoder + refuses (a cycle, a key that is no string or number) is its repr, its + byte objects markers, for the strip to read. A caller that writes a byte + object as its replacement before encoding uses :func:`strict_json_text` + and falls back to this on the value as it came. + """ + text = strict_json_text(value) + if text is not None: + return text + try: + return safe_repr(value) + except Exception: + return f"" + + +def strict_json_text(value: Any) -> str | None: + """``value`` as JSON text as :func:`json_text` writes it, or None when the + encoder refuses it (a cycle, a key that is no string or number).""" + try: + return _dumps(value, _encode_whole) + except Exception: + return None + + +def _bounded_dumps(value: Any, finish: Callable[[str], str] = truncate) -> str: + return _dumps(value, lambda plain: _encode_within_budget(plain, finish)) + + +def _dumps(value: Any, encode: Callable[[Any], str]) -> str: # A lone non-finite number is its name, as the TypeScript SDK writes a # number with String(); inside a value it is null (see _finite). if isinstance(value, float) and not math.isfinite(value): return _non_finite_name(value) try: - return _encode_within_budget(value) + return encode(value) except ValueError: # The encoder refuses NaN and the infinities (allow_nan=False). Only # then is the value walked to replace them; a cycle raises again and # serialize falls back to repr, as it always has. - return _encode_within_budget(_finite(value)) + return encode(_finite(value)) + + +def _encode_whole(value: Any) -> str: + # The same text the budgeted walk renders, by the C encoder in one pass. + return LONE_SURROGATE.sub(_escape_surrogate, _encoder.encode(value)) -def _encode_within_budget(value: Any) -> str: +def _encode_within_budget(value: Any, finish: Callable[[str], str]) -> str: # iterencode without _one_shot takes the pure-Python path, which yields # chunks lazily as it walks the value; the C encoder renders everything # first. A small payload costs a few extra microseconds this way; a large @@ -386,4 +429,4 @@ def _encode_within_budget(value: Any) -> str: if size > MAX_STRIP_CHARS: kept = "".join(chunks)[:MAX_ATTR_CHARS] return _cut_past_budget(LONE_SURROGATE.sub(_escape_surrogate, kept)) - return truncate("".join(chunks)) + return finish("".join(chunks)) diff --git a/src/rius/_tool_definitions.py b/src/rius/_tool_definitions.py new file mode 100644 index 0000000..01a947b --- /dev/null +++ b/src/rius/_tool_definitions.py @@ -0,0 +1,242 @@ +"""Tool definitions in the GenAI conventions' shape (``gen_ai.tool.definitions``). + +The conventions define one tool type, ``function``: +``{"type": "function", "name", "description"?, "parameters"?}``, and a +definition whose ``type`` is ``function`` must match that shape: it can no +longer pass as the generic definition. Providers spell function tools their +own way, so each is rewritten: + +* OpenAI Chat Completions nests the function, ``{"type": "function", + "function": {"name", ...}}``: the nested object is lifted to the top level, + unless the top level already has a name (then the tool is already flat, + and ``function`` is one of its fields). +* Chat Completions nests a custom tool the same way, ``{"type": "custom", + "custom": {"name", "description", "format"}}``: the nested object is lifted + by the same rule, and the tool stays a custom tool (a provider tool, below), + unless the lifted tool is Anthropic's custom tool. +* Anthropic has no ``type`` (or ``"custom"``) and names the schema + ``input_schema``; OpenAI's legacy ``functions`` entries have no ``type`` + either. A definition with a name and no ``type`` is a function, and so is + a ``custom`` one with an ``input_schema``. +* A name is a non-empty string. An empty ``name`` is no name, as it is for a + tool call: no function tool is made with an empty name. +* The schema is ``parameters``; ``input_schema`` and the Vercel AI SDK's + ``inputSchema`` are renamed to it, in place. +* Bedrock Converse wraps the function, ``{"toolSpec": {"name", "description", + "inputSchema": {"json": schema}}}``: it is unwrapped, and ``json`` becomes + ``parameters``. +* A Gemini tool holds a list of declarations, ``{"function_declarations": + [...]}`` (``functionDeclarations`` in camel case; every spelling holding a + list expands, snake case first). Each declaration with a name + becomes its own function tool, its schema taken from ``parameters`` or, + failing that, ``parametersJsonSchema`` / ``parameters_json_schema`` / + ``input_schema`` / ``inputSchema``. A declaration without a name, and + whatever else the Gemini tool holds (a built-in such as ``google_search``), + is its own entry, rewritten by the rules for a single tool. +* A ``null`` ``parameters`` counts as no schema, so a schema under another + spelling still takes its place (a Python ``model_dump()`` of a Gemini + declaration holds both). + +Any other ``type`` is a provider's built-in tool (Anthropic's +``web_search_20250305``, OpenAI's ``web_search``). Its fields are kept, and its +``type`` is prefixed with the provider name, as the conventions recommend, so +it cannot collide with a type they define later: ``anthropic.web_search_20250305``. +An empty ``type`` is no type, and gets no prefix. +A type that already holds a dot is taken as namespaced and left alone, which +also keeps a second pass from stacking prefixes. Nothing is invented: a +built-in tool without a ``name`` (OpenAI's ``web_search``, Gemini's +``google_search``) stays without one. Tool names are read as the tools the +model was offered, and an invented name would be a tool offered and never +called by that name. + +An MCP tool (OpenAI Responses' ``type: "mcp"``, or any ``.mcp`` +type it is written as) loses its ``headers`` and its ``authorization``: the +headers are the requests' headers to the MCP server and can carry an +``Authorization`` credential, and ``authorization`` is an OAuth access token +for the server or connector. The Vercel AI SDK's ``openai.mcp`` provider tool +holds the same two members in its ``args``, and they go there too. +Credentials never belong in telemetry. This +applies to the definitions rewritten here, not to definitions another +instrumentation already wrote as ``gen_ai.tool.definitions``. + +Anything else (not an object, or no usable ``type`` or ``name``) is kept as +it is: it is the caller's data, and there is no shape to vouch for. + +Every rule's output is a fixed point: rewriting a rewritten list changes +nothing. The sink rewrites what an SDK exported, so this keeps one tool in one +shape. + +The TypeScript SDK's ``toolDefinitions.ts`` and the sink port this rule for +rule; all three write the same canonical JSON, key order included, and +rius-semconv's ``sdk_cases/tool_definitions.json`` holds them to it. Number +formatting is each language's own (Python writes ``1.0``, TypeScript ``1``), +and so is the order of integer-like keys in TypeScript. +""" + +from __future__ import annotations + +from typing import Any + +_FUNCTION = "function" +#: Schema spellings renamed to ``parameters``, first match wins. +_PARAMETER_SPELLINGS = ("input_schema", "inputSchema") +#: Gemini's own schema spellings, renamed to ``parameters`` on a declaration. +_GEMINI_PARAMETER_SPELLINGS = ("parametersJsonSchema", "parameters_json_schema") +#: A Gemini tool's list of function declarations, snake and camel case. +_GEMINI_DECLARATIONS = ("function_declarations", "functionDeclarations") +#: The Vercel AI SDK's provider tools, whose ``id`` is already ``.``. +_VERCEL_PROVIDER_TYPES = ("provider-defined", "provider") +_CUSTOM = "custom" +#: OpenAI Responses' MCP tool type; ``.mcp`` once namespaced. +_MCP = "mcp" +#: An MCP tool's members that hold credentials, dropped. +_MCP_CREDENTIALS = ("headers", "authorization") + + +def _named(value: Any) -> bool: + """A usable tool name: a non-empty string.""" + return isinstance(value, str) and bool(value) + + +def semconv_tool_definitions(tools: list[Any], provider: str | None) -> list[Any]: + """The definitions in the conventions' shape; the caller's list is not mutated. + + A Gemini tool expands to one entry per declaration, so the result can be + longer than ``tools``. + """ + definitions: list[Any] = [] + for tool in tools: + expanded = _gemini_declarations(tool, provider) + if expanded is None: + definitions.append(_semconv_tool_definition(tool, provider)) + else: + definitions.extend(expanded) + return definitions + + +def _gemini_declarations(tool: Any, provider: str | None) -> list[Any] | None: + """A Gemini tool as one entry per declaration, then the rest; None if not one.""" + if not isinstance(tool, dict) or tool.get("type") is not None: + return None + keys = [key for key in _GEMINI_DECLARATIONS if isinstance(tool.get(key), list)] + if not keys: + return None + entries: list[Any] = [] + for key in keys: + for declaration in tool[key]: + if isinstance(declaration, dict) and _named(declaration.get("name")): + entries.append(_gemini_declaration(declaration)) + else: + entries.extend(semconv_tool_definitions([declaration], provider)) + rest = {name: value for name, value in tool.items() if name not in keys} + if rest: + entries.extend(semconv_tool_definitions([rest], provider)) + return entries + + +def _gemini_declaration(declaration: dict[str, Any]) -> dict[str, Any]: + flat = {"type": _FUNCTION, **{k: v for k, v in declaration.items() if k != "type"}} + return _with_parameters(flat, _GEMINI_PARAMETER_SPELLINGS + _PARAMETER_SPELLINGS) + + +def _semconv_tool_definition(tool: Any, provider: str | None) -> Any: + if not isinstance(tool, dict): + return tool + kind = tool.get("type") + if kind == _FUNCTION: + nested = tool.get(_FUNCTION) + if not isinstance(nested, dict) or _named(tool.get("name")): + return _with_parameters(tool) + return _with_parameters(_lifted(tool, _FUNCTION, nested)) + if kind == _CUSTOM: + nested = tool.get(_CUSTOM) + if isinstance(nested, dict) and not _named(tool.get("name")): + return _semconv_tool_definition(_lifted(tool, _CUSTOM, nested), provider) + if _named(tool.get("name")) and (kind is None or (kind == _CUSTOM and "input_schema" in tool)): + rest = {key: value for key, value in tool.items() if key != "type"} + return _with_parameters({"type": _FUNCTION, **rest}) + spec = tool.get("toolSpec") + if kind is None and isinstance(spec, dict) and _named(spec.get("name")): + return _bedrock_tool(tool, spec) + if not isinstance(kind, str) or not kind: + return tool + if kind in _VERCEL_PROVIDER_TYPES: + identifier = tool.get("id") + if isinstance(identifier, str) and "." in identifier: + tool = {**tool, "type": identifier} + elif provider and "." not in kind: + tool = {**tool, "type": f"{provider}.{kind}"} + return _without_credentials(tool) + + +def _lifted(tool: dict[str, Any], kind: str, nested: dict[str, Any]) -> dict[str, Any]: + """The tool with its nested ``kind`` object's members at the top level. + + The nested members win; the top level's other members follow. + """ + flat: dict[str, Any] = {"type": kind} + flat.update((key, value) for key, value in nested.items() if key != "type") + flat.update( + (key, value) for key, value in tool.items() if key not in ("type", kind) and key not in flat + ) + return flat + + +def _without_credentials(tool: dict[str, Any]) -> dict[str, Any]: + """An MCP tool (``mcp`` or ``.mcp``) without its credential members. + + Dropped at the top level and in a Vercel provider tool's ``args``. Read + from the type the tool is written with, so a second pass drops the same + members. + """ + kind = tool.get("type") + if not isinstance(kind, str) or not (kind == _MCP or kind.endswith("." + _MCP)): + return tool + args = tool.get("args") + if isinstance(args, dict) and any(key in args for key in _MCP_CREDENTIALS): + tool = {**tool, "args": _without_members(args, _MCP_CREDENTIALS)} + if not any(key in tool for key in _MCP_CREDENTIALS): + return tool + return _without_members(tool, _MCP_CREDENTIALS) + + +def _without_members(members: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]: + return {key: value for key, value in members.items() if key not in keys} + + +def _bedrock_tool(tool: dict[str, Any], spec: dict[str, Any]) -> dict[str, Any]: + """Bedrock's ``toolSpec`` lifted to a function tool, ``inputSchema.json`` as parameters.""" + flat: dict[str, Any] = {"type": _FUNCTION} + for key, value in spec.items(): + if key == "type": + continue + if key == "inputSchema" and isinstance(value, dict) and "json" in value: + flat["parameters"] = value["json"] + else: + flat[key] = value + flat.update( + (key, value) + for key, value in tool.items() + if key not in ("type", "toolSpec") and key not in flat + ) + return _with_parameters(flat) + + +def _with_parameters( + tool: dict[str, Any], spellings: tuple[str, ...] = _PARAMETER_SPELLINGS +) -> dict[str, Any]: + """The tool with its schema under ``parameters``, renamed where it stood. + + A ``null`` ``parameters`` is no schema: when another spelling holds one, + the null goes and that spelling is renamed. + """ + if tool.get("parameters") is not None: + return tool + for spelling in spellings: + if spelling in tool: + return { + ("parameters" if key == spelling else key): value + for key, value in tool.items() + if key != "parameters" + } + return tool diff --git a/src/rius/client.py b/src/rius/client.py index c97f1d0..1d4f19f 100644 --- a/src/rius/client.py +++ b/src/rius/client.py @@ -363,7 +363,10 @@ def init( headers: Extra headers for the OTLP exporter. disabled: If True, no exporter is attached (spans are dropped). sample_rate: Head sampling ratio 0.0-1.0 (whole-trace). Default 1.0. - capture_content: If False, strip prompt/response content at export. Default True. + capture_content: If False, strip prompt/response content at export. Default True, + or ``RIUS_CAPTURE_CONTENT``, or when that is unset + ``OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT`` (``NO_CONTENT`` and + ``EVENT_ONLY`` turn capture off). mask: Redact content attribute values at export (applies to all spans). instruments: Auto-instrumentation selection. ``None`` (default) enables every bundled instrumentor whose package is installed; a list diff --git a/src/rius/compaction.py b/src/rius/compaction.py index b766826..c09a1ff 100644 --- a/src/rius/compaction.py +++ b/src/rius/compaction.py @@ -23,6 +23,7 @@ from .semconv import ( GEN_AI_CONVERSATION_COMPACTED, GEN_AI_OPERATION_NAME, + GEN_AI_OPERATION_NAME_COMPACTION, OPENINFERENCE_SPAN_KIND, RIUS_COMPACTION_EXECUTOR, RIUS_COMPACTION_EXECUTOR_CLIENT, @@ -58,9 +59,8 @@ ) _TRIGGERS = (RIUS_COMPACTION_TRIGGER_AUTO, RIUS_COMPACTION_TRIGGER_MANUAL) -#: ``gen_ai.operation.name`` of the span: the registry's taxonomy table knows -#: it (it maps to CHAIN) but has no constant for it, and semconv.py defines none. -OPERATION_COMPACTION = "compaction" +#: ``gen_ai.operation.name`` of the span (the registry's taxonomy maps it to CHAIN). +OPERATION_COMPACTION = GEN_AI_OPERATION_NAME_COMPACTION def dropped_tokens(before: int | None, after: int | None) -> int | None: diff --git a/src/rius/config.py b/src/rius/config.py index a00d1ba..87dd7e0 100644 --- a/src/rius/config.py +++ b/src/rius/config.py @@ -32,6 +32,9 @@ ENV_DISABLED = "RIUS_DISABLED" ENV_SAMPLE_RATE = "RIUS_SAMPLE_RATE" ENV_CAPTURE_CONTENT = "RIUS_CAPTURE_CONTENT" +# The GenAI conventions' content-capture setting, read when +# RIUS_CAPTURE_CONTENT is unset. +ENV_OTEL_CAPTURE_CONTENT = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT" ENV_HEARTBEAT = "RIUS_HEARTBEAT" ENV_HEARTBEAT_INTERVAL = "RIUS_HEARTBEAT_INTERVAL" ENV_AGENT_NAME = "RIUS_AGENT_NAME" @@ -84,6 +87,50 @@ def _env_bool(name: str, *, default: bool) -> bool: return default +#: The conventions' capture modes, by whether Rius captures content under +#: them. Rius records content on spans only, so EVENT_ONLY (content on events, +#: none on spans) captures none. +_OTEL_CAPTURE_MODES = { + "NO_CONTENT": False, + "EVENT_ONLY": False, + "SPAN_ONLY": True, + "SPAN_AND_EVENT": True, +} + + +def _capture_content_from_env() -> bool: + """``RIUS_CAPTURE_CONTENT`` when set, else the conventions' setting, else on. + + An empty (or blank) value of either variable counts as unset, as + OpenTelemetry reads its own variables: templated deployments render an + omitted value as an empty one. A blank ``RIUS_CAPTURE_CONTENT`` still logs + a warning, as the other blank ``RIUS_*`` flags do. The conventions' + ``OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT`` is read case-insensitively. + Its own default is ``NO_CONTENT``, and the conventions ask for that on an + unrecognised value too. Rius keeps capture on in both cases, on purpose: + capture is on by default, and an unrecognised value logs a warning naming + the valid ones. + """ + rius = os.getenv(ENV_CAPTURE_CONTENT) + if rius is not None: + if rius.strip(): + return _env_bool(ENV_CAPTURE_CONTENT, default=True) + logger.warning("%s is empty; treated as unset.", ENV_CAPTURE_CONTENT) + raw = os.getenv(ENV_OTEL_CAPTURE_CONTENT) + if raw is None or not raw.strip(): + return True + mode = _OTEL_CAPTURE_MODES.get(raw.strip().upper()) + if mode is not None: + return mode + logger.warning( + "%s=%r is not recognised; content capture stays on. " + "Valid values: NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT.", + ENV_OTEL_CAPTURE_CONTENT, + raw, + ) + return True + + def _env_float(name: str, *, default: float) -> float: raw = os.getenv(name) if raw is None: @@ -297,7 +344,10 @@ def resolve_config( sample_rate: Head-sampling ratio for root traces (``RIUS_SAMPLE_RATE``). capture_content: When ``False``, content attributes are stripped at - export (``RIUS_CAPTURE_CONTENT``). + export (``RIUS_CAPTURE_CONTENT``; when that is unset, the + conventions' ``OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT``: + ``NO_CONTENT`` and ``EVENT_ONLY`` turn capture off, ``SPAN_ONLY`` + and ``SPAN_AND_EVENT`` keep it on). On by default. heartbeat: Enable the agent-lifetime heartbeat thread (``RIUS_HEARTBEAT``). On by default; set ``False`` or ``RIUS_HEARTBEAT=false`` to opt out. @@ -372,7 +422,7 @@ def resolve_config( else _finite("sample_rate", sample_rate, 1.0) ) resolved_capture_content = ( - _env_bool(ENV_CAPTURE_CONTENT, default=True) if capture_content is None else capture_content + _capture_content_from_env() if capture_content is None else capture_content ) resolved_heartbeat = _env_bool(ENV_HEARTBEAT, default=True) if heartbeat is None else heartbeat diff --git a/src/rius/generation.py b/src/rius/generation.py index 5a84e99..65f1aae 100644 --- a/src/rius/generation.py +++ b/src/rius/generation.py @@ -19,8 +19,9 @@ from ._errors import record_error from ._media import media_parts from ._serde import serialize +from ._tool_definitions import semconv_tool_definitions from ._tracer import sdk_tracer -from .normalization import REQUEST_PARAMETER_GUARDS, SKIP +from .normalization import REQUEST_PARAMETER_GUARDS, SKIP, unnamed_tool_call_part from .semconv import ( GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, @@ -137,11 +138,15 @@ def _normalize_message(message: Any, default_role: str) -> dict[str, Any]: function = call.get("function") if not isinstance(function, dict): function = {} + name = function.get("name") + if not isinstance(name, str) or not name: + parts.append(unnamed_tool_call_part(call.get("id"), function.get("arguments"))) + continue parts.append( { "type": "tool_call", "id": call.get("id"), - "name": function.get("name"), + "name": name, "arguments": function.get("arguments"), } ) @@ -161,6 +166,30 @@ def normalize_messages(messages: Messages, default_role: str) -> list[dict[str, return [_normalize_message(message, default_role) for message in messages] +#: google-genai's package, whose pydantic models (``types.Tool``) are dumped. +_GOOGLE_GENAI = "google.genai" + + +def _plain(tool: Any) -> Any: + """A google-genai pydantic model (``types.Tool``) as its set fields, as JSON values. + + Only google-genai's models are dumped, since their fields are the provider + shape the definitions are rewritten from. Anything else (another library's + pydantic tool, such as a LangChain ``StructuredTool``), or a model whose + dump fails, is returned as it is. + """ + module = type(tool).__module__ + if module != _GOOGLE_GENAI and not module.startswith(_GOOGLE_GENAI + "."): + return tool + dump = getattr(tool, "model_dump", None) + if isinstance(tool, type) or not callable(dump): + return tool + try: + return dump(mode="json", exclude_none=True) + except Exception: + return tool + + class Generation: """Handle for recording gen_ai attributes on an LLM span. @@ -213,18 +242,21 @@ def set_output(self, messages: Messages) -> None: def set_tool_definitions(self, tools: list[Any]) -> None: """Record the request's tool/function definitions (``gen_ai.tool.definitions``). - Definitions are serialized verbatim, in whatever shape the provider - request used (OpenAI nests each tool under ``function``, Anthropic uses - top-level ``name``/``input_schema``) — no normalization, so what is - recorded is exactly what the model was shown. Definitions are content, - not identity: they are masked/stripped under ``capture_content=False`` - like messages are. + Definitions are recorded in the conventions' shape whatever shape the + provider request used: a function tool becomes ``{"type": "function", + "name", "description", "parameters"}`` (OpenAI's nested ``function`` + is lifted, Anthropic's ``input_schema`` becomes ``parameters``), and a + provider's built-in tool keeps its fields with its ``type`` prefixed + by the generation's provider (``anthropic.web_search_20250305``). + A pydantic model (google-genai's ``types.Tool``) is recorded as its + set fields. Definitions are content, not identity: they are + masked/stripped under ``capture_content=False`` like messages are. Args: - tools: The tools/functions list passed to the provider, verbatim. + tools: The tools/functions list passed to the provider, in its own shape. """ - self._tools = tools - self._span.set_attribute(GEN_AI_TOOL_DEFINITIONS, serialize(tools)) + self._tools = semconv_tool_definitions([_plain(tool) for tool in tools], self._provider) + self._span.set_attribute(GEN_AI_TOOL_DEFINITIONS, serialize(self._tools)) def _set_context_sizes(self) -> None: # Computed once, as the span ends (from end() and from the scoped @@ -563,7 +595,8 @@ def start_generation( ``reasoning.effort`` values. Provider-defined string, recorded verbatim. tools: The request's tool/function definitions, recorded immediately - via ``set_tool_definitions`` (verbatim, any provider shape). + via ``set_tool_definitions`` (any provider shape, recorded in the + conventions' shape). user_id: End-user identity (``user.id``) stamped on this span. Sugar for a single call; to attribute a whole request use ``user()``. output_type: The output modality the request asked for diff --git a/src/rius/normalization.py b/src/rius/normalization.py index 3df8e6f..2a6d541 100644 --- a/src/rius/normalization.py +++ b/src/rius/normalization.py @@ -87,6 +87,10 @@ reasons: the flattened ``llm.input_messages.N.message.*`` and ``llm.output_messages.N.message.*`` families become ``gen_ai.input.messages`` and ``gen_ai.output.messages``, which are content. +``structured_content_as_json`` comes first of all: the conventions now ask for +the content keys as maps and arrays rather than JSON strings, and every pass +after it reads them as JSON text, so a structured value is written as that +text before any of them runs. ``drop_embedding_vectors`` removes the indexed ``embedding.embeddings.N.embedding.vector`` family, which is never exported. @@ -113,21 +117,28 @@ from ._attributes import rebuilt_item_attributes, replacement_attributes from ._media import ( + is_mime, rebuild_native_parts, + replacement, url_part, ) from ._native_spans import native_error_type from ._provider_compaction import ProviderCompactions, compactions_in_response from ._provider_response import response_json from ._serde import ( + BYTE_OBJECTS, LONE_SURROGATE, UNREADABLE, attribute_value, + byte_object_size, + json_text, loads_json, loads_object, serialize, + strict_json_text, strip_within_budget, ) +from ._tool_definitions import semconv_tool_definitions from .aggregated_usage import WrappedCallTracker, move_aggregated_usage from .compaction import CompactedContextProcessor from .semconv import ( @@ -580,9 +591,10 @@ def normalize_tool_definitions(attributes: Mapping[str, Any] | None) -> dict[str * ``llm.tools.N.tool.json_schema``, which every bundled OpenInference instrumentor that sees tools writes (openai pops ``tools`` out of the request bag to do it). Each value is a JSON string; the schemas are - parsed and re-serialized as one array, in index order, VERBATIM — an - Anthropic ``input_schema`` stays an Anthropic ``input_schema``, as on - the native ``set_tool_definitions``. The indexed keys are then deleted. + parsed and re-serialized as one array, in index order, in the + conventions' shape, as on the native ``set_tool_definitions`` (see + ``_tool_definitions``; a built-in tool's type is prefixed with the + span's ``gen_ai.provider.name``). The indexed keys are then deleted. If any one schema does not parse, the family is left untouched rather than reassembled without it: it is content by prefix already, so nothing escapes, and a partial array would be a silent loss. @@ -632,7 +644,7 @@ def normalize_tool_definitions(attributes: Mapping[str, Any] | None) -> dict[str if stripped is not None: rebuilt = stripped[0] if not native: - rebuilt[GEN_AI_TOOL_DEFINITIONS] = serialize(schemas) + _set_definitions(rebuilt, schemas, _provider_of(attributes)) return rebuilt stripped = _bag_without_definitions(attributes) @@ -640,10 +652,27 @@ def normalize_tool_definitions(attributes: Mapping[str, Any] | None) -> dict[str return None rebuilt, definitions = stripped if not native: - rebuilt[GEN_AI_TOOL_DEFINITIONS] = serialize(definitions) + _set_definitions(rebuilt, definitions, _provider_of(attributes)) return rebuilt +def _set_definitions(attributes: dict[str, Any], tools: list[Any], provider: str | None) -> None: + """``gen_ai.tool.definitions`` from tools, unless they come to no definition. + + An empty list (no tools, or a Gemini tool with no declarations) writes + nothing, as the sink does; the sources are removed all the same. + """ + definitions = semconv_tool_definitions(tools, provider) + if definitions: + attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(definitions) + + +def _provider_of(attributes: Mapping[str, Any]) -> str | None: + """The span's ``gen_ai.provider.name``, which prefixes built-in tool types.""" + provider = attributes.get(GEN_AI_PROVIDER_NAME) + return provider if isinstance(provider, str) else None + + def _bag_without_definitions( attributes: Mapping[str, Any], ) -> tuple[dict[str, Any], list[Any]] | None: @@ -694,6 +723,25 @@ def _bag_without_definitions( #: ``tool_call.*`` field is consumed and dropped, as the sink does. _TOOL_CALL_FIELDS = (("id", "id"), ("function.name", "name"), ("function.arguments", "arguments")) + +def unnamed_tool_call_part(call_id: Any, arguments: Any) -> dict[str, Any]: + """A tool call without a name, as a text part holding its id and arguments. + + The conventions require a ``tool_call`` part's name (a string), and a part + of a known type may not fall back to the generic part, so a call without + one cannot be a ``tool_call`` part. Rather than drop it, it is kept the way + content with no part type is: as text, the call's id and arguments as JSON, + each left out when absent. Every writer of tool-call parts uses this, in + both SDKs and the sink, so the bytes agree. + """ + call = { + key: value + for key, value in (("id", call_id), ("arguments", arguments)) + if value is not None + } + return {"type": "text", "content": serialize(call)} + + #: An index as the sink's ``strconv.Atoi`` reads one: an optional sign and #: ASCII digits, within int64. The sink is the other producer of this key, and #: the two must agree on which keys are messages. @@ -725,6 +773,8 @@ def encode(self) -> dict[str, Any]: then the tool calls, each family in index order. An empty role, id, name or arguments is omitted rather than written empty, as the sink does; empty content is still a part, because empty content was said. + A tool call left without a name is a text part + (:func:`unnamed_tool_call_part`). """ message: dict[str, Any] = {} if self.role: @@ -751,6 +801,8 @@ def encode(self) -> dict[str, Any]: for field, name in _TOOL_CALL_FIELDS: if call.get(field): part[name] = call[field] + if "name" not in part: + part = unnamed_tool_call_part(part.get("id"), part.get("arguments")) parts.append(part) message["parts"] = parts return message @@ -1195,6 +1247,92 @@ def compactions_from_output_value(attributes: Mapping[str, Any] | None) -> Provi return compactions_in_response(raw) +#: The content keys the GenAI conventions ask for as structured values (maps +#: and arrays) rather than JSON strings. OpenTelemetry Python keeps such a +#: value on a span from 1.45. +_STRUCTURED_CONTENT_KEYS = ( + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, +) + + +def structured_content_as_json(attributes: Mapping[str, Any] | None) -> dict[str, Any] | None: + """The content keys set as structured values, each written as its JSON text. + + Returns the rebuilt attribute dict, or None when nothing changes. Every + pass after this one, the media rebuild and the strip included, reads these + keys as JSON text, as the conventions used to define them and as this SDK + still writes them. A mapping or an array is written as that text (the one + JSON encoding, see ``_serde``), and from then on it is that string: a + span carrying the structured value and a span carrying its JSON text + export the same attributes. A string, a scalar or a lone byte object is + not structured, and is left to the passes as it is. + + A blob part's byte content (``{"type": "blob", "content": b"..."}``) is + written as the replacement the strip writes for media + (``[stripped bytes]``), its mime the part's MIME type, + so the part is rebuilt with its size and MIME type as the same blob with + base64 content is, without rendering the bytes at all. A byte object + anywhere else is the marker, as everywhere this SDK writes one. + """ + if not attributes: + return None + rebuilt: dict[str, Any] | None = None + for key in _STRUCTURED_CONTENT_KEYS: + value = attributes.get(key) + if not isinstance(value, (Mapping, list, tuple)): + continue + if rebuilt is None: + rebuilt = dict(attributes) + rebuilt[key] = _structured_json_text(value) + return rebuilt + + +def _structured_json_text(value: Mapping[str, Any] | list[Any] | tuple[Any, ...]) -> str: + """``value`` as JSON text, a blob part's bytes as their replacement. + + The text is encoded whole (see ``json_text``), so a blob's base64 past the + strip budget is still found and stripped by the media rebuild, as it is in + the JSON text of the same value. A value the encoder refuses (a cycle, a + key that is no string or number) is the fallback text of the value as it + came, whose byte objects are markers. + """ + try: + text = strict_json_text(_plain_content(value, [])) + except RecursionError: + text = None + return json_text(value) if text is None else text + + +def _plain_content(value: Any, ancestors: list[int]) -> Any: + """``value`` with every mapping a dict and every array a list, for the encoder. + + A blob part's byte content becomes its replacement (see + :func:`structured_content_as_json`). A cycle is left as it is, for the + encoder to refuse. + """ + if not isinstance(value, (Mapping, list, tuple)): + return value + if id(value) in ancestors: + return value + ancestors.append(id(value)) + try: + if isinstance(value, Mapping): + plain = {key: _plain_content(item, ancestors) for key, item in value.items()} + content = plain.get("content") + if plain.get("type") == "blob" and isinstance(content, BYTE_OBJECTS): + size = byte_object_size(content) + if size is not None: + mime = plain.get("mime_type") + plain["content"] = replacement(mime if is_mime(mime) else None, size) + return plain + return [_plain_content(item, ancestors) for item in value] + finally: + ancestors.pop() + + #: The message keys whose parts a normalizer builds (the contract's #: ``raw_payloads.message_keys`` that hold semconv JSON). The system #: instructions are read and rewritten here, never emitted. @@ -1345,7 +1483,14 @@ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult: return self._inner.export([self._normalized(span) for span in spans]) def _normalized(self, span: ReadableSpan) -> ReadableSpan: - new_attributes = self._table.normalize(span.attributes) + # First, so every pass below reads the content keys as JSON text, + # however the instrumentation set them. + structured = structured_content_as_json(span.attributes) + new_attributes = self._table.normalize( + span.attributes if structured is None else structured + ) + if new_attributes is None: + new_attributes = structured # After the table, which maps the dialects' usage onto the canonical # keys, so a zero it mapped goes with the native ones. On every span, # the SDK's own generations included, not only third-party ones. diff --git a/src/rius/semconv.py b/src/rius/semconv.py index 039b061..4e135f8 100644 --- a/src/rius/semconv.py +++ b/src/rius/semconv.py @@ -76,9 +76,20 @@ def operation_for_kind(kind: str) -> str | None: def kind_for_operation(operation: str) -> str | None: - """The taxonomy value for a ``gen_ai.operation.name``, or None if unknown.""" + """The taxonomy value for a ``gen_ai.operation.name``, or None if unknown. + + The conventions name a framework entrypoint ``invoke_{framework_entrypoint}`` + (``invoke_runner`` is one) and define it as not being an agent, so no table + can list them all. An ``invoke_`` operation the table does not know is a + CHAIN span; ``invoke_agent`` is in the table and stays AGENT. + """ kind = _KIND_BY_OPERATION.get(operation) - return kind.value if kind is not None else None + if kind is not None: + return kind.value + entrypoint = operation.removeprefix("invoke_") + if entrypoint and entrypoint != operation: + return SpanKind.CHAIN.value + return None def otel_span_kind(kind: SpanKind) -> OtelSpanKind: diff --git a/tests/conformance/_recording.py b/tests/conformance/_recording.py index 15c7248..8953011 100644 --- a/tests/conformance/_recording.py +++ b/tests/conformance/_recording.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 fixtures/_recording.py by +# Vendored from rius-semconv a5808570bf015dee2c61a83ee2ab489cefb570e5 fixtures/_recording.py by # scripts/sync-semconv-fixtures.sh. Do not edit: change it in rius-semconv. """Shared helpers for the recorders under fixtures//record.py. diff --git a/tests/conformance/_replay.py b/tests/conformance/_replay.py index 074047d..b20019a 100644 --- a/tests/conformance/_replay.py +++ b/tests/conformance/_replay.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 fixtures/_replay.py by +# Vendored from rius-semconv a5808570bf015dee2c61a83ee2ab489cefb570e5 fixtures/_replay.py by # scripts/sync-semconv-fixtures.sh. Do not edit: change it in rius-semconv. """Turn a stored recording back into OpenTelemetry ReadableSpans (Python). diff --git a/tests/conformance/known_differences.json b/tests/conformance/known_differences.json index d8b06f8..053b4a4 100644 --- a/tests/conformance/known_differences.json +++ b/tests/conformance/known_differences.json @@ -55,6 +55,66 @@ "family": "vercel-ai-v6", "key": "*", "reason": "As vercel-ai-v5." + }, + { + "family": "openinference-openai", + "key": "gen_ai.tool.definitions", + "reason": "The stored expected results record tool definitions in the provider's own shape (OpenAI's nested function, Anthropic's input_schema). This normalizer now records them in the conventions' function-tool shape, {type: function, name, description, parameters}, which the conventions' schema requires for a function tool. The expected results are regenerated in rius-semconv from this SDK once the change is released, and this entry goes in that re-sync." + }, + { + "family": "openinference-anthropic", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-js-anthropic", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-js-langchain", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-js-langchain-openai", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-js-openai", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-langchain", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-langchain-openai", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-litellm", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-litellm-openai", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-llama-index", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." + }, + { + "family": "openinference-llama-index-openai", + "key": "gen_ai.tool.definitions", + "reason": "As openinference-openai." } ] } diff --git a/tests/fixtures/openinference_messages.json b/tests/fixtures/openinference_messages.json index 9d2ef66..f73805d 100644 --- a/tests/fixtures/openinference_messages.json +++ b/tests/fixtures/openinference_messages.json @@ -185,7 +185,7 @@ } }, { - "name": "tool-call fields: missing or empty ones are omitted, unknown ones are consumed and dropped", + "name": "tool-call fields: missing or empty ones are omitted, unknown ones are consumed and dropped, a call left without a name is text", "sink_identical": true, "attributes": { "llm.input_messages.0.message.role": "assistant", @@ -198,7 +198,25 @@ "llm.input_messages.0.message.tool_calls.3.tool_call.reasoning_signature": "sig" }, "expected": { - "gen_ai.input.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"name\":\"only_name\"},{\"type\":\"tool_call\",\"name\":\"empty_id\"},{\"type\":\"tool_call\"},{\"type\":\"tool_call\",\"id\":\"call_3\"}]}]" + "gen_ai.input.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"name\":\"only_name\"},{\"type\":\"tool_call\",\"name\":\"empty_id\"},{\"type\":\"text\",\"content\":\"{}\"},{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"call_3\\\"}\"}]}]" + } + }, + { + "name": "a tool call without a name is kept as a text part holding its id and arguments", + "sink_identical": true, + "attributes": { + "llm.output_messages.0.message.role": "assistant", + "llm.output_messages.0.message.tool_calls.0.tool_call.id": "call_1", + "llm.output_messages.0.message.tool_calls.0.tool_call.function.arguments": "{\"q\":\"otel\"}", + "llm.output_messages.0.message.tool_calls.1.tool_call.id": "call_2", + "llm.output_messages.0.message.tool_calls.1.tool_call.function.name": "", + "llm.output_messages.0.message.tool_calls.1.tool_call.function.arguments": "{}", + "llm.output_messages.0.message.tool_calls.2.tool_call.id": "call_3", + "llm.output_messages.0.message.tool_calls.2.tool_call.function.name": "search", + "llm.output_messages.0.message.tool_calls.2.tool_call.function.arguments": "{}" + }, + "expected": { + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"call_1\\\",\\\"arguments\\\":\\\"{\\\\\\\"q\\\\\\\":\\\\\\\"otel\\\\\\\"}\\\"}\"},{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"call_2\\\",\\\"arguments\\\":\\\"{}\\\"}\"},{\"type\":\"tool_call\",\"id\":\"call_3\",\"name\":\"search\",\"arguments\":\"{}\"}]}]" } }, { @@ -410,7 +428,7 @@ "llm.output_messages.2.message.contents.0.tool_call.id": "toolu_C" }, "expected": { - "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"tool_call.id\\\":\\\"toolu_B\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"tool_call\",\"id\":\"toolu_A\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"tool_call.function.name\\\":\\\"orphan\\\",\\\"type\\\":\\\"tool_use\\\"}\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"text\\\":\\\"an extra field\\\",\\\"tool_call.id\\\":\\\"toolu_C\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"tool_call\",\"id\":\"toolu_C\"}]}]" + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"tool_call.id\\\":\\\"toolu_B\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"toolu_A\\\"}\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"tool_call.function.name\\\":\\\"orphan\\\",\\\"type\\\":\\\"tool_use\\\"}\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"text\\\":\\\"an extra field\\\",\\\"tool_call.id\\\":\\\"toolu_C\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"toolu_C\\\"}\"}]}]" } }, { @@ -424,7 +442,7 @@ "llm.output_messages.0.message.contents.0.tool_call.id": "toolu_D" }, "expected": { - "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"text\\\":\\\"\\\",\\\"tool_call.id\\\":\\\"toolu_D\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"tool_call\",\"id\":\"toolu_D\"}]}]" + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"{\\\"text\\\":\\\"\\\",\\\"tool_call.id\\\":\\\"toolu_D\\\",\\\"type\\\":\\\"tool_use\\\"}\"},{\"type\":\"text\",\"content\":\"{\\\"id\\\":\\\"toolu_D\\\"}\"}]}]" } }, { diff --git a/tests/fixtures/semconv/SOURCE b/tests/fixtures/semconv/SOURCE index 63631e0..1321055 100644 --- a/tests/fixtures/semconv/SOURCE +++ b/tests/fixtures/semconv/SOURCE @@ -1 +1 @@ -rius-semconv ab957f21453782a0e47350f3b6f964533785cf17 +rius-semconv a5808570bf015dee2c61a83ee2ab489cefb570e5 diff --git a/tests/fixtures/semconv/media_parts.yaml b/tests/fixtures/semconv/media_parts.yaml index 3e66333..ecc5fac 100644 --- a/tests/fixtures/semconv/media_parts.yaml +++ b/tests/fixtures/semconv/media_parts.yaml @@ -1453,7 +1453,7 @@ part_shapes: - 'Every native media part in a message key (blob, uri or file) is always rebuilt into its canonical shape: members in the pinned order, extra members dropped, and every member that is unknown omitted. The only exception is a uri part whose uri is not a string, or a file part whose file_id is not a string: it is left as it came. Any string is a usable uri or file_id, the empty string included. An object of type file that holds a base64 or a url that is a string is no native file part but a LangChain v1 file block, read by the v1 rule below: so {"type":"file","file_id":5,"url":"https://example.com/a.wav"} is a uri, while {"type":"file","file_id":5} is a native file part left as it came. Every other normalized media part carries a modality. generators/media_parts.py native_part(data, part) is the reference: each example''s native part, and the part in each in_place example, is its test.' - 'Parts are rebuilt only in a message-key value that parses as JSON and nests at most 1000 levels deep. Arrays and objects count together from the value''s root, which is level 1: the message array, a message, its parts array and a tool call part are 4 levels. A value nested deeper (a tool call whose arguments add 997 more arrays makes 1001 levels) is left as it came, every part in it included; at 1000 levels its parts are rebuilt. The implementation counts the depth itself and never relies on its parser''s or its language''s recursion limit. The strip still runs on a value left this way.' - 'The modality that the part already has is kept, when it is one of modalities (any other value is ignored), except for a blob whose content is a string and a uri holding a data URL (below). Otherwise it is taken from the MIME type. Failing that, a provider item whose kind names a modality takes it from the kind: an image, image_url, input_image or image_generation_call item is image, an input_audio item audio, a document item document. A LangChain v1 block of type image, audio or video is that modality; a block of type file names none, so by a url that is not a data URL it takes the modality from the extension of the URL''s path (see extensions), and otherwise it is document. A text-plain block by base64 names none either and is document (one by url or file_id makes no part). A Bedrock Converse image, video, audio or document block is that modality. An OpenAI file or input_file item names none; its modality comes from the extension of its filename member alone (never from a file_url), and with no filename, or an empty one, it is document. A Gemini file_data, a native uri and a Vercel file part by URL take it from the extension of their URI''s path (see extensions), the Vercel part whether its URL is a plain string or v7''s {"type":"url"} data; a Vercel image part is an image. Otherwise it is document. So an Anthropic document by URL ending in .png is a document, an OpenAI input_file named a.png is an image, and an input_file by a file_url ending in .png with no filename is a document; a LangChain v1 image block by a URL ending in .bin is an image, and a v1 file block by a URL ending in .wav is audio. A native file part with no valid modality and no MIME type gets document; no member of it is read for an extension. Any other part with no MIME type and no other hint also gets document.' - - 'A blob whose `content` is a string is rebuilt with stripped_reason not_captured and a byte_size taken from the content under the size rule of the strip (omitted when the size is unknown). Its modality comes from its MIME type first, then from the modality it has, then document: a PDF blob labelled image is a document. A content string that is itself a data URL follows the data URL rules below, with the part''s mime_type as the hint and the same modality order. A blob in a message key never carries content.' + - 'A blob whose `content` is a string is rebuilt with stripped_reason not_captured and a byte_size taken from the content under the size rule of the strip (omitted when the size is unknown). A content string that is a complete replacement (see raw_payloads idempotence), such as the marker `[stripped unknown bytes]` an OTLP bytes value or an SDK byte object becomes (raw_payloads byte_objects), names bytes a strip already measured: its byte_size is the replacement''s, read as a decimal number (leading zeros allowed) and omitted when unknown or larger than 2^53 - 1, and its MIME type is the part''s mime_type when that is valid, else the replacement''s when that is not unknown. Every complete replacement is read this way, not only the bytes marker: each is a strip''s record of bytes it removed. So a blob whose content is base64, with its MIME type under mime_type or with none, makes the same part whether it is rebuilt before or after a strip. That is all this promises. A blob whose MIME type is under another key the strip reads (mimeType, media_type, mediaType or output_format), or whose content is a data URL, can make a different part after a strip: the strip reads more keys and replaces a data URL whole, while the part rules read only mime_type and size a data URL from its run. A string that is not a complete replacement (a near one such as `[stripped image/png lots bytes]`, or one inside other text) is sized as base64 like any other. Its modality comes from its MIME type first, then from the modality it has, then document: a PDF blob labelled image is a document. A content string that is itself a data URL follows the data URL rules below, with the part''s mime_type as the hint and the same modality order. A blob in a message key never carries content.' - 'A blob with no string `content` keeps a stripped_reason that is one of stripped_reasons. Otherwise its stripped_reason is redacted_upstream when it has no content member or a null one, and not_captured when its content is any other value. It keeps a byte_size that is a whole, non-negative number no larger than 2^53 - 1 (8, 8.0 and 8e0 alike, written 8); any other byte_size is omitted.' - 'A uri part, or a provider URI, whose URI is a data URL is never a uri: it becomes a blob under the data URL rules below. A data URL is a value that starts with data:, or with data%3A (rule (b)''s percent_scheme: a data URL percent-encoded whole, as encodeURIComponent writes it), in any ASCII case. Nor is a native uri part or a provider URI whose value holds data: anywhere else, in any ASCII case (a value led by whitespace, or a link with a data URL after it, wrapped, percent-encoded or not): it becomes a blob with the stripped_reason not_captured and no byte_size, its MIME type kept when valid, so no byte of the data URL survives. The provider URIs are an OpenAI image_url''s url and input_image''s image_url, an Anthropic image or document by a url source, an OpenAI input_file''s file_url, a Gemini file_data''s file_uri, a Vercel file or image part by URL (a plain string that starts with a URL scheme, or v7''s {"type":"url"} data), and the image url OpenInference flattens; a LangChain v1 url is read the same way (below). Any other value stays a uri as it came, a link that holds data%3A and no data: included (a proxy link with an encoded data URL in its query): the strip then replaces the encoded data URL inside it where it sits, as rule (b) does wherever it runs. A native uri part takes that blob''s modality as a blob whose content is a string does: from the MIME type first, then the modality it has, then document. A provider URI takes it from the MIME type the item gives (an Anthropic source''s media_type, a Gemini file_data''s mime_type, a Vercel part''s mediaType, the image media_type OpenInference flattens beside its url), then from the item''s kind (an image_url, an input_image and a Vercel image part are image, an Anthropic image or document that kind, an input_file the modality its filename names), then document: such a value has no path to read an extension from. The test is one search for [dD][aA][tT][aA]: with no trimming and no word boundary, so a link with data: in its path (https://e/metadata:x.png) becomes this blob too: a lost link, never a leak. generators/media_parts.py provider_uri_part(data, item) is the reference for a provider URI, and each example''s provider item is its test.' - 'A URL of any scheme other than data: is a uri, its link kept as written: http, https, gs, s3, file and any other scheme alike. Only a data: URL, or inline data, becomes a blob, and a native uri, a provider URI or a LangChain v1 url that holds data: anywhere else (above and below). Where one value may hold either a URL or bare base64 (a Vercel file part''s data or image part''s image, as a plain string or as v7''s {"type":"data"} data), it is a URL when it starts with a scheme: an ASCII letter, then any ASCII letters, digits, `+`, `-` or `.`, then a colon. Base64 holds no colon, so the two never meet; anything else is base64, but a value that starts with data%3A, which is a data URL (above). A value v7 tags {"type":"url"} is a URL whatever it holds. The strip reads these values the same way: rule (e) leaves a value that starts with a scheme to rule (b) (raw_payloads, rule (e)''s url_scheme and keeps_urls), except a value holding data: that rule (b)''s pattern does not match in full (a percent-encoded data URL, a link with a data URL after it), which rule (e) replaces whole, as the part rules make it a blob.' @@ -1486,6 +1486,10 @@ part_shapes: from: 'The string base64 makes the object a v1 file block, and as a usable reference it wins over the __REDACTED__ file_id, so it is a blob of 3 bytes.' input: '[ {"role": "user", "parts": [ {"type": "file", "file_id": "__REDACTED__", "base64": "QUJD"} ] } ]' output: '[ {"role": "user", "parts": [ {"type":"blob","modality":"document","byte_size":3,"stripped_reason":"not_captured"} ] } ]' + - name: blob_whose_content_is_the_bytes_marker + from: 'A spaced message value holding a native blob whose content is the bytes marker: the part takes the size the marker names.' + input: '[ {"role": "user", "parts": [ {"type": "blob", "modality": "image", "mime_type": "image/png", "content": "[stripped unknown 16 bytes]"} ] } ]' + output: '[ {"role": "user", "parts": [ {"type":"blob","modality":"image","mime_type":"image/png","byte_size":16,"stripped_reason":"not_captured"} ] } ]' examples: - name: blob_with_a_known_size from: 'A base64 data URL of image/png, 8 bytes decoded.' @@ -1511,6 +1515,54 @@ part_shapes: from: 'A native blob part with the mime_type image/png and a content member holding data:;base64, which names no mime type and has an empty run: the part''s mime_type is the hint.' native: '{"type":"blob","mime_type":"image/png","content":"data:;base64,"}' part: '{"type":"blob","modality":"image","mime_type":"image/png","byte_size":0,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_the_bytes_marker + from: 'A native blob part whose content is the marker [stripped unknown 16 bytes], as a bytes value inside a structured message becomes before the part is rebuilt: the same 16 bytes sent as base64 make the same part.' + native: '{"type":"blob","modality":"image","mime_type":"image/png","content":"[stripped unknown 16 bytes]"}' + part: '{"type":"blob","modality":"image","mime_type":"image/png","byte_size":16,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_with_a_mime_and_no_hint + from: 'A native blob part whose content is the complete replacement [stripped image/jpeg 10 bytes] and that has neither a MIME type nor a modality: the replacement''s mime is the MIME type, and gives the modality.' + native: '{"type":"blob","content":"[stripped image/jpeg 10 bytes]"}' + part: '{"type":"blob","modality":"image","mime_type":"image/jpeg","byte_size":10,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_and_its_own_mime_type + from: 'A native blob part with the mime_type application/pdf whose content is the complete replacement [stripped image/png 8 bytes]: the part''s own valid mime_type wins over the replacement''s.' + native: '{"type":"blob","mime_type":"application/pdf","content":"[stripped image/png 8 bytes]"}' + part: '{"type":"blob","modality":"document","mime_type":"application/pdf","byte_size":8,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_of_unknown_size + from: 'A native blob part with the modality audio whose content is the complete replacement [stripped unknown unknown bytes]: its size and mime are unknown, so both are omitted.' + native: '{"type":"blob","modality":"audio","content":"[stripped unknown unknown bytes]"}' + part: '{"type":"blob","modality":"audio","stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_too_large_to_keep + from: 'A native blob part whose content is the complete replacement [stripped unknown 9007199254740992 bytes]: a size larger than 2^53 - 1 is omitted, as for a byte_size the part has.' + native: '{"type":"blob","content":"[stripped unknown 9007199254740992 bytes]"}' + part: '{"type":"blob","modality":"document","stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_with_leading_zeros + from: 'A native blob part whose content is the complete replacement [stripped image/png 0008 bytes]: its size is the decimal number 8.' + native: '{"type":"blob","content":"[stripped image/png 0008 bytes]"}' + part: '{"type":"blob","modality":"image","mime_type":"image/png","byte_size":8,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_with_thousands_of_leading_zeros + from: 'A native blob part whose content is a complete replacement whose size is 5000 zeros then 8: leading zeros of any length are allowed, so its size is 8.' + native: '{"type":"blob","content":"[stripped unknown 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008 bytes]"}' + part: '{"type":"blob","modality":"document","byte_size":8,"stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_whose_size_overflows_int64 + from: 'A native blob part whose content is the complete replacement [stripped image/png 99999999999999999999 bytes]: a size past any 64-bit integer is larger than 2^53 - 1, so it is omitted, and the replacement''s mime is still read.' + native: '{"type":"blob","content":"[stripped image/png 99999999999999999999 bytes]"}' + part: '{"type":"blob","modality":"image","mime_type":"image/png","stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_with_thousands_of_digits + from: 'A native blob part whose content is a complete replacement whose size is 5000 nines: far larger than 2^53 - 1, so it is omitted, and reading it never fails.' + native: '{"type":"blob","content":"[stripped unknown 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 bytes]"}' + part: '{"type":"blob","modality":"document","stripped_reason":"not_captured"}' + - name: blob_with_content_that_only_looks_like_a_replacement + from: 'A native blob part with the mime_type image/png whose content is [stripped image/png lots bytes]: not a complete replacement, so it is sized as base64, which it is not, and has no byte_size.' + native: '{"type":"blob","mime_type":"image/png","content":"[stripped image/png lots bytes]"}' + part: '{"type":"blob","modality":"image","mime_type":"image/png","stripped_reason":"not_captured"}' + - name: blob_with_content_that_is_a_replacement_with_an_invalid_mime + from: 'A native blob part whose content is [stripped a b 3 bytes]: a b is no valid mime, so it is not a complete replacement, and its 3 is never read.' + native: '{"type":"blob","content":"[stripped a b 3 bytes]"}' + part: '{"type":"blob","modality":"document","stripped_reason":"not_captured"}' + - name: blob_with_content_that_holds_a_replacement_in_text + from: 'A native blob part whose content is the text see [stripped unknown 16 bytes]: a replacement inside other text is not a complete replacement, so the content is sized as base64, which it is not, and has no byte_size.' + native: '{"type":"blob","content":"see [stripped unknown 16 bytes]"}' + part: '{"type":"blob","modality":"document","stripped_reason":"not_captured"}' - name: blob_with_no_content_and_no_stripped_reason from: 'A native blob part with the modality audio and neither content nor stripped_reason.' native: '{"type":"blob","modality":"audio"}' diff --git a/tests/fixtures/semconv/sdk_cases/README.md b/tests/fixtures/semconv/sdk_cases/README.md index 05ad26c..bdc4a1a 100644 --- a/tests/fixtures/semconv/sdk_cases/README.md +++ b/tests/fixtures/semconv/sdk_cases/README.md @@ -7,6 +7,8 @@ result. The Python SDK and the TypeScript SDK both vendor this directory (`scripts/sync-semconv-fixtures.sh` copies it to `tests/fixtures/semconv/sdk_cases/`) and run every case through their own code, so the two SDKs agree with each other by agreeing with these files. +The sink (argus-core) vendors `tool_definitions.json` too, since it rewrites +tool definitions by the same rules. | File | What it checks | Through | | -- | -- | -- | @@ -17,6 +19,8 @@ code, so the two SDKs agree with each other by agreeing with these files. | `env.json` | `RIUS_*` variables: booleans (blank or unrecognised keeps the default), blank strings (unset), numbers (as Python's `float()` reads them, clamped to range). | `resolve_config()` / `resolveConfig({}, env)` | | `resource.json` | `OTEL_RESOURCE_ATTRIBUTES` merged under the SDK's own resource keys, and the `unknown_service` placeholder never stamped as an agent name. | `init()` | | `anthropic_error_type.json` | `error.type` on a span the Anthropic SDK made itself: the exception class it raises for the HTTP status, for the statuses every Anthropic client in both languages maps alike (400, 401, 403, 404, 409, 422, 429, and every 5xx but 503, 504 and 529); anything else kept. | the SDK's span normalization | +| `structured_content.json` | `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions` and `gen_ai.tool.definitions` set by another instrumentation as maps and arrays: each written as its compact JSON and then normalized as that string, so it exports as its JSON string does; a blob part's byte content as its base64, any other byte object the marker. | the SDK's span normalization | +| `tool_definitions.json` | `gen_ai.tool.definitions` in the conventions' shape from each provider's own: OpenAI chat and Responses, Anthropic, Gemini declarations, Bedrock `toolSpec`, Vercel AI SDK and MCP tools, and Chat Completions `custom` tools, and the edge cases (null `parameters`, an empty `type`, an empty `name` as no name, an MCP tool's `headers` and `authorization` dropped, in a Vercel provider tool's `args` too). Rewriting an output again writes it unchanged. | `semconv_tool_definitions` / `semconvToolDefinitions`, and the sink's | Each file holds an `about`, which says what a case's fields mean, and `cases`, each with a unique `name`. A field an SDK spells differently is named @@ -50,8 +54,9 @@ mapping with one tagged key, which each SDK's test decodes: A case belongs here only when both SDKs must give the same result. Where the languages differ by nature it is left out: JavaScript has one number type, so -`1.0` is `"1"` in TypeScript and `"1.0"` in Python; Python writes a boolean a -mask returns for the status description as `True`, TypeScript as `true`. +`1.0` is `"1"` in TypeScript and `"1.0"` in Python, and `1e-7` is `"1e-7"` in +TypeScript and `"1e-07"` in Python, inside JSON text as anywhere else; Python +writes a boolean a mask returns for the status description as `True`, TypeScript as `true`. Behaviour only one SDK has is tested in that SDK alone. ## Changing a case diff --git a/tests/fixtures/semconv/sdk_cases/structured_content.json b/tests/fixtures/semconv/sdk_cases/structured_content.json new file mode 100644 index 0000000..1fa57c4 --- /dev/null +++ b/tests/fixtures/semconv/sdk_cases/structured_content.json @@ -0,0 +1,399 @@ +{ + "about": "How an SDK exports the content keys another instrumentation set as structured values (maps and arrays) rather than JSON strings, as the GenAI conventions now ask: gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions and gen_ai.tool.definitions. Each such value is written as its JSON text in the one encoding (compact, raw UTF-8, no HTML escaping, a non-finite number null) and then normalized exactly as that string would be, so a structured value and its JSON string export the same attributes. A byte object that is a blob part's content is written as its base64, as a blob part's JSON carries it, at any depth, so a part in `parts` is rebuilt with its byte_size and its bytes stripped, and one elsewhere (inside a tool call response, say) has its base64 stripped to the blob's marker; any other byte object is the marker. A data URL in a uri part is rebuilt as a blob part, as in its JSON string. A string, a number or a boolean is not structured and is kept; a lone byte object is the marker. A float's text is the SDK's own (an integral float is `2.0` in Python and `2` in TypeScript), so the cases hold no integral float and no exponent. `attributes` are the span's attributes as it ends, as the third-party instrumentation set them, and `expected` every attribute the span is exported with, after normalization and before masking. Keys are never integer-like, since JavaScript orders those first in an object.", + "cases": [ + { + "name": "input_messages_structured", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "Weather in Zürich? & 天気" + } + ] + }, + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": { + "city": "Zürich", + "days": 2, + "units": null + } + } + ] + }, + { + "role": "tool", + "parts": [ + { + "type": "tool_call_response", + "id": "call_1", + "response": { + "temperature": 21.5, + "sunny": true + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + } + }, + { + "name": "input_messages_as_their_json_string", + "attributes": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"temperature\":21.5,\"sunny\":true}}]}]" + } + }, + { + "name": "output_messages_blob_with_byte_content", + "attributes": { + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "text", + "content": "Here it is" + }, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + ] + } + ] + }, + "expected": { + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Here it is\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "output_messages_blob_with_base64_content", + "attributes": { + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "text", + "content": "Here it is" + }, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": "AAAAAAAAAAA=" + } + ] + } + ] + }, + "expected": { + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Here it is\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "system_instructions_structured", + "attributes": { + "gen_ai.system_instructions": [ + { + "type": "text", + "content": "Be brief." + }, + { + "type": "text", + "content": "Answer in French." + } + ] + }, + "expected": { + "gen_ai.system_instructions": "[{\"type\":\"text\",\"content\":\"Be brief.\"},{\"type\":\"text\",\"content\":\"Answer in French.\"}]" + } + }, + { + "name": "system_instructions_array_of_strings", + "attributes": { + "gen_ai.system_instructions": [ + "Be brief.", + "Answer in French." + ] + }, + "expected": { + "gen_ai.system_instructions": "[\"Be brief.\",\"Answer in French.\"]" + } + }, + { + "name": "system_instructions_blob_with_byte_content", + "attributes": { + "gen_ai.system_instructions": [ + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + ] + }, + "expected": { + "gen_ai.system_instructions": "[{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]" + } + }, + { + "name": "tool_definitions_structured_non_finite_number", + "attributes": { + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "days": { + "type": "integer", + "default": { + "$number": "NaN" + } + } + }, + "required": [ + "city" + ] + } + } + ] + }, + "expected": { + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\",\"default\":null}},\"required\":[\"city\"]}}]" + } + }, + { + "name": "byte_object_outside_a_blob_part", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "custom", + "data": { + "$bytes": 4 + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"custom\",\"data\":\"[stripped unknown 4 bytes]\"}]}]" + } + }, + { + "name": "every_content_key_at_once", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "Weather in Zürich? & 天気" + } + ] + } + ], + "gen_ai.output.messages": [ + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": { + "city": "Zürich", + "days": 2, + "units": null + } + } + ] + } + ], + "gen_ai.system_instructions": [ + { + "type": "text", + "content": "Be brief." + } + ], + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "days": { + "type": "integer", + "default": { + "$number": "NaN" + } + } + }, + "required": [ + "city" + ] + } + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Weather in Zürich? & 天気\"}]}]", + "gen_ai.output.messages": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"tool_call\",\"id\":\"call_1\",\"name\":\"get_weather\",\"arguments\":{\"city\":\"Zürich\",\"days\":2,\"units\":null}}]}]", + "gen_ai.system_instructions": "[{\"type\":\"text\",\"content\":\"Be brief.\"}]", + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\",\"default\":null}},\"required\":[\"city\"]}}]" + } + }, + { + "name": "lone_byte_object", + "attributes": { + "gen_ai.input.messages": { + "$bytes": 4 + } + }, + "expected": { + "gen_ai.input.messages": "[stripped unknown 4 bytes]" + } + }, + { + "name": "tool_definitions_non_integral_floats", + "attributes": { + "gen_ai.tool.definitions": [ + { + "type": "function", + "name": "set_thermostat", + "description": "Set a target temperature", + "parameters": { + "type": "object", + "properties": { + "celsius": { + "type": "number", + "minimum": -12.5, + "maximum": 32.75, + "default": 21.5 + }, + "step": { + "type": "number", + "default": 0.25 + } + }, + "required": [ + "celsius" + ] + } + } + ] + }, + "expected": { + "gen_ai.tool.definitions": "[{\"type\":\"function\",\"name\":\"set_thermostat\",\"description\":\"Set a target temperature\",\"parameters\":{\"type\":\"object\",\"properties\":{\"celsius\":{\"type\":\"number\",\"minimum\":-12.5,\"maximum\":32.75,\"default\":21.5},\"step\":{\"type\":\"number\",\"default\":0.25}},\"required\":[\"celsius\"]}}]" + } + }, + { + "name": "input_messages_uri_part_with_data_url", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "user", + "parts": [ + { + "type": "text", + "content": "What is in this image?" + }, + { + "type": "uri", + "modality": "image", + "mime_type": "image/png", + "uri": "data:image/png;base64,AAAAAAAAAAA=" + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"What is in this image?\"},{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"byte_size\":8,\"stripped_reason\":\"not_captured\"}]}]" + } + }, + { + "name": "blob_nested_outside_parts", + "attributes": { + "gen_ai.input.messages": [ + { + "role": "tool", + "parts": [ + { + "type": "tool_call_response", + "id": "call_1", + "response": { + "screenshot": { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": { + "$bytes": 8 + } + } + } + } + ] + } + ] + }, + "expected": { + "gen_ai.input.messages": "[{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call_1\",\"response\":{\"screenshot\":{\"type\":\"blob\",\"modality\":\"image\",\"mime_type\":\"image/png\",\"content\":\"[stripped image/png 8 bytes]\"}}}]}]" + } + }, + { + "name": "string_value_kept", + "attributes": { + "gen_ai.input.messages": "plain text, not JSON" + }, + "expected": { + "gen_ai.input.messages": "plain text, not JSON" + } + }, + { + "name": "scalar_value_kept", + "attributes": { + "gen_ai.input.messages": 3 + }, + "expected": { + "gen_ai.input.messages": 3 + } + } + ] +} diff --git a/tests/fixtures/semconv/sdk_cases/tool_definitions.json b/tests/fixtures/semconv/sdk_cases/tool_definitions.json new file mode 100644 index 0000000..2fa34c1 --- /dev/null +++ b/tests/fixtures/semconv/sdk_cases/tool_definitions.json @@ -0,0 +1,987 @@ +{ + "about": "gen_ai.tool.definitions in the GenAI conventions' shape, from tools in each provider's own shape: `tools` is the list as the provider request or another instrumentation gave it, `provider` the span's gen_ai.provider.name (null for none), and `expected` the rewritten list's compact JSON, key order included. Each implementation (the Python SDK's semconv_tool_definitions, the TypeScript SDK's semconvToolDefinitions, the sink's semconvToolDefinitions) must write `expected`, and rewriting its own output must write `expected` again: the sink rewrites what an SDK exported, so every output is a fixed point. A name is a non-empty string, as for tool calls: an empty `name` is no name, so no function tool is made with one. An MCP tool (`mcp` or any `.mcp`) loses its `headers` and `authorization`, and so do the `args` of a Vercel AI SDK provider tool written as one. An empty result here is `[]`; a span whose definitions come to an empty list is written without gen_ai.tool.definitions, which each implementation tests on its own. The cases hold no float and no integer-like key, whose text differs by language.", + "cases": [ + { + "name": "openai_chat_function_with_strict", + "provider": "openai", + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + }, + "strict": true + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]},\"strict\":true}]" + }, + { + "name": "openai_responses_function", + "provider": "openai", + "tools": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + }, + "strict": true + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]},\"strict\":true}]" + }, + { + "name": "openai_responses_built_ins", + "provider": "openai", + "tools": [ + { + "type": "web_search_preview", + "search_context_size": "low" + }, + { + "type": "file_search", + "vector_store_ids": [ + "vs_1" + ], + "max_num_results": 5 + }, + { + "type": "computer_use_preview", + "display_width": 1024, + "display_height": 768, + "environment": "browser" + } + ], + "expected": "[{\"type\":\"openai.web_search_preview\",\"search_context_size\":\"low\"},{\"type\":\"openai.file_search\",\"vector_store_ids\":[\"vs_1\"],\"max_num_results\":5},{\"type\":\"openai.computer_use_preview\",\"display_width\":1024,\"display_height\":768,\"environment\":\"browser\"}]" + }, + { + "name": "openai_responses_custom_freeform", + "provider": "openai", + "tools": [ + { + "type": "custom", + "name": "code_exec", + "description": "Runs code", + "format": { + "type": "text" + } + } + ], + "expected": "[{\"type\":\"openai.custom\",\"name\":\"code_exec\",\"description\":\"Runs code\",\"format\":{\"type\":\"text\"}}]" + }, + { + "name": "openai_responses_mcp_headers_dropped", + "provider": "openai", + "tools": [ + { + "type": "mcp", + "server_label": "docs", + "server_url": "https://mcp.example.com", + "headers": { + "Authorization": "Bearer secret" + }, + "require_approval": "never" + } + ], + "expected": "[{\"type\":\"openai.mcp\",\"server_label\":\"docs\",\"server_url\":\"https://mcp.example.com\",\"require_approval\":\"never\"}]" + }, + { + "name": "mcp_headers_dropped_once_namespaced", + "provider": null, + "tools": [ + { + "type": "openai.mcp", + "server_label": "docs", + "headers": { + "X-Api-Key": "secret" + } + }, + { + "type": "mcp", + "headers": {} + } + ], + "expected": "[{\"type\":\"openai.mcp\",\"server_label\":\"docs\"},{\"type\":\"mcp\"}]" + }, + { + "name": "openai_legacy_functions", + "provider": "openai", + "tools": [ + { + "name": "get_weather", + "description": "Weather for a city", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "anthropic_custom_with_cache_control", + "provider": "anthropic", + "tools": [ + { + "name": "search_kb", + "description": "Search", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + }, + "cache_control": { + "type": "ephemeral" + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"search_kb\",\"description\":\"Search\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}},\"cache_control\":{\"type\":\"ephemeral\"}}]" + }, + { + "name": "anthropic_explicit_custom_type", + "provider": "anthropic", + "tools": [ + { + "type": "custom", + "name": "search_kb", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"search_kb\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "anthropic_server_and_client_tools", + "provider": "anthropic", + "tools": [ + { + "type": "web_search_20250305", + "name": "web_search", + "max_uses": 5 + }, + { + "type": "text_editor_20250124", + "name": "str_replace_editor" + }, + { + "type": "bash_20250124", + "name": "bash" + }, + { + "type": "computer_20250124", + "name": "computer", + "display_width_px": 1024, + "display_height_px": 768 + } + ], + "expected": "[{\"type\":\"anthropic.web_search_20250305\",\"name\":\"web_search\",\"max_uses\":5},{\"type\":\"anthropic.text_editor_20250124\",\"name\":\"str_replace_editor\"},{\"type\":\"anthropic.bash_20250124\",\"name\":\"bash\"},{\"type\":\"anthropic.computer_20250124\",\"name\":\"computer\",\"display_width_px\":1024,\"display_height_px\":768}]" + }, + { + "name": "gemini_snake_declarations_with_a_built_in", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "get_weather", + "description": "Weather", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + { + "name": "get_time" + } + ], + "google_search": {} + }, + { + "code_execution": {} + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}},{\"type\":\"function\",\"name\":\"get_time\"},{\"google_search\":{}},{\"code_execution\":{}}]" + }, + { + "name": "gemini_camel_parameters_json_schema", + "provider": "gcp.gemini", + "tools": [ + { + "functionDeclarations": [ + { + "name": "get_weather", + "parametersJsonSchema": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + ] + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "gemini_snake_parameters_json_schema", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "get_weather", + "parameters_json_schema": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + ] + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "gemini_both_declaration_spellings", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "a" + } + ], + "functionDeclarations": [ + { + "name": "b" + } + ] + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"a\"},{\"type\":\"function\",\"name\":\"b\"}]" + }, + { + "name": "gemini_declarations_spelling_not_a_list_stays", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "a" + } + ], + "functionDeclarations": "odd" + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"a\"},{\"functionDeclarations\":\"odd\"}]" + }, + { + "name": "gemini_declaration_with_input_schema", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "a", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + }, + { + "name": "b", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + ] + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"a\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}},{\"type\":\"function\",\"name\":\"b\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "gemini_nameless_typed_declaration", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "type": "web_search" + } + ] + } + ], + "expected": "[{\"type\":\"gcp.gemini.web_search\"}]" + }, + { + "name": "gemini_nameless_declarations_kept", + "provider": "gcp.gemini", + "tools": [ + { + "functionDeclarations": [ + { + "description": "no name" + }, + "odd", + { + "name": 3 + } + ] + } + ], + "expected": "[{\"description\":\"no name\"},\"odd\",{\"name\":3}]" + }, + { + "name": "gemini_rest_with_a_name", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "a" + } + ], + "name": "x" + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"a\"},{\"type\":\"function\",\"name\":\"x\"}]" + }, + { + "name": "gemini_declarations_not_a_list", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": { + "name": "f" + } + } + ], + "expected": "[{\"function_declarations\":{\"name\":\"f\"}}]" + }, + { + "name": "gemini_no_declarations", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [] + } + ], + "expected": "[]" + }, + { + "name": "gemini_model_dump_null_parameters", + "provider": "gcp.gemini", + "tools": [ + { + "function_declarations": [ + { + "name": "f", + "description": "d", + "parameters": null, + "parameters_json_schema": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + ] + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"f\",\"description\":\"d\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "null_parameters_gives_way_to_input_schema", + "provider": "anthropic", + "tools": [ + { + "name": "g", + "parameters": null, + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"g\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "null_parameters_alone_kept", + "provider": "openai", + "tools": [ + { + "type": "function", + "name": "f", + "parameters": null + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"f\",\"parameters\":null}]" + }, + { + "name": "bedrock_tool_spec", + "provider": "aws.bedrock", + "tools": [ + { + "toolSpec": { + "name": "get_weather", + "description": "Weather for a city", + "inputSchema": { + "json": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather for a city\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "bedrock_cache_point_system_tool_and_nameless_spec", + "provider": "aws.bedrock", + "tools": [ + { + "cachePoint": { + "type": "default" + } + }, + { + "systemTool": { + "name": "nova_grounding" + } + }, + { + "toolSpec": { + "inputSchema": { + "json": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + } + } + ], + "expected": "[{\"cachePoint\":{\"type\":\"default\"}},{\"systemTool\":{\"name\":\"nova_grounding\"}},{\"toolSpec\":{\"inputSchema\":{\"json\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}}}]" + }, + { + "name": "bedrock_input_schema_without_json", + "provider": "aws.bedrock", + "tools": [ + { + "toolSpec": { + "name": "f", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"f\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "vercel_function_tools", + "provider": "openai", + "tools": [ + { + "type": "function", + "name": "get_weather", + "description": "Weather", + "inputSchema": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + { + "type": "function", + "name": "lookup", + "parameters": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"get_weather\",\"description\":\"Weather\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}},{\"type\":\"function\",\"name\":\"lookup\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "vercel_provider_tools", + "provider": "anthropic", + "tools": [ + { + "type": "provider-defined", + "id": "anthropic.web_search_20250305", + "name": "web_search", + "args": {} + }, + { + "type": "provider", + "id": "openai.web_search", + "name": "web_search", + "args": {} + }, + { + "type": "provider-defined", + "id": "nodot", + "name": "x" + } + ], + "expected": "[{\"type\":\"anthropic.web_search_20250305\",\"id\":\"anthropic.web_search_20250305\",\"name\":\"web_search\",\"args\":{}},{\"type\":\"openai.web_search\",\"id\":\"openai.web_search\",\"name\":\"web_search\",\"args\":{}},{\"type\":\"provider-defined\",\"id\":\"nodot\",\"name\":\"x\"}]" + }, + { + "name": "mcp_server_tool", + "provider": null, + "tools": [ + { + "name": "read_file", + "description": "Read a file", + "inputSchema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + }, + "outputSchema": { + "type": "object" + }, + "annotations": { + "readOnlyHint": true + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"read_file\",\"description\":\"Read a file\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}},\"outputSchema\":{\"type\":\"object\"},\"annotations\":{\"readOnlyHint\":true}}]" + }, + { + "name": "nested_function_not_lifted_over_a_name", + "provider": "openai", + "tools": [ + { + "name": "x", + "function": { + "name": "y" + } + }, + { + "type": "function", + "name": "x", + "function": { + "name": "y" + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"x\",\"function\":{\"name\":\"y\"}},{\"type\":\"function\",\"name\":\"x\",\"function\":{\"name\":\"y\"}}]" + }, + { + "name": "both_schema_spellings_first_wins", + "provider": null, + "tools": [ + { + "name": "x", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + }, + "inputSchema": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"x\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}},\"inputSchema\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}]" + }, + { + "name": "built_in_without_a_provider", + "provider": null, + "tools": [ + { + "type": "web_search_20250305", + "name": "web_search" + } + ], + "expected": "[{\"type\":\"web_search_20250305\",\"name\":\"web_search\"}]" + }, + { + "name": "already_namespaced_type", + "provider": "azure.ai.openai", + "tools": [ + { + "type": "anthropic.web_search_20250305", + "name": "web_search" + } + ], + "expected": "[{\"type\":\"anthropic.web_search_20250305\",\"name\":\"web_search\"}]" + }, + { + "name": "empty_type_and_name", + "provider": "openai", + "tools": [ + { + "type": "", + "size": 1 + }, + { + "name": "" + } + ], + "expected": "[{\"type\":\"\",\"size\":1},{\"name\":\"\"}]" + }, + { + "name": "openai_responses_mcp_authorization_dropped", + "provider": "openai", + "tools": [ + { + "type": "mcp", + "server_label": "gmail", + "connector_id": "connector_gmail", + "authorization": "ya29.token", + "require_approval": "never" + }, + { + "type": "mcp", + "server_label": "docs", + "server_url": "https://mcp.example.com", + "authorization": "token", + "headers": { + "Authorization": "Bearer secret" + } + } + ], + "expected": "[{\"type\":\"openai.mcp\",\"server_label\":\"gmail\",\"connector_id\":\"connector_gmail\",\"require_approval\":\"never\"},{\"type\":\"openai.mcp\",\"server_label\":\"docs\",\"server_url\":\"https://mcp.example.com\"}]" + }, + { + "name": "mcp_credentials_dropped_for_any_provider_prefix", + "provider": null, + "tools": [ + { + "type": "azure.mcp", + "server_label": "docs", + "authorization": "token", + "headers": { + "X-Api-Key": "secret" + } + }, + { + "type": "provider", + "id": "openai.mcp", + "name": "mcp", + "authorization": "token" + }, + { + "type": "web_search", + "authorization": "kept" + } + ], + "expected": "[{\"type\":\"azure.mcp\",\"server_label\":\"docs\"},{\"type\":\"openai.mcp\",\"id\":\"openai.mcp\",\"name\":\"mcp\"},{\"type\":\"web_search\",\"authorization\":\"kept\"}]" + }, + { + "name": "vercel_mcp_provider_tool_args_credentials_dropped", + "provider": "openai", + "tools": [ + { + "type": "provider", + "id": "openai.mcp", + "name": "mcp", + "args": { + "serverLabel": "docs", + "serverUrl": "https://mcp.example.com", + "authorization": "token", + "headers": { + "Authorization": "Bearer secret" + }, + "requireApproval": "never" + } + }, + { + "type": "provider-defined", + "id": "openai.mcp", + "name": "mcp", + "args": { + "serverLabel": "gmail", + "connectorId": "connector_gmail", + "authorization": "ya29.token" + } + }, + { + "type": "provider", + "id": "openai.web_search", + "name": "web_search", + "args": { + "authorization": "kept" + } + } + ], + "expected": "[{\"type\":\"openai.mcp\",\"id\":\"openai.mcp\",\"name\":\"mcp\",\"args\":{\"serverLabel\":\"docs\",\"serverUrl\":\"https://mcp.example.com\",\"requireApproval\":\"never\"}},{\"type\":\"openai.mcp\",\"id\":\"openai.mcp\",\"name\":\"mcp\",\"args\":{\"serverLabel\":\"gmail\",\"connectorId\":\"connector_gmail\"}},{\"type\":\"openai.web_search\",\"id\":\"openai.web_search\",\"name\":\"web_search\",\"args\":{\"authorization\":\"kept\"}}]" + }, + { + "name": "openai_chat_custom_lifted", + "provider": "openai", + "tools": [ + { + "type": "custom", + "custom": { + "name": "code_exec", + "description": "Runs code", + "format": { + "type": "text" + } + } + }, + { + "type": "custom", + "custom": { + "description": "No name" + } + } + ], + "expected": "[{\"type\":\"openai.custom\",\"name\":\"code_exec\",\"description\":\"Runs code\",\"format\":{\"type\":\"text\"}},{\"type\":\"openai.custom\",\"description\":\"No name\"}]" + }, + { + "name": "custom_nested_not_lifted_over_a_name", + "provider": "openai", + "tools": [ + { + "type": "custom", + "name": "x", + "custom": { + "name": "y" + } + } + ], + "expected": "[{\"type\":\"openai.custom\",\"name\":\"x\",\"custom\":{\"name\":\"y\"}}]" + }, + { + "name": "custom_lifted_with_input_schema_is_a_function", + "provider": null, + "tools": [ + { + "type": "custom", + "custom": { + "name": "search_kb", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"search_kb\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}]" + }, + { + "name": "empty_name_is_no_name", + "provider": "anthropic", + "tools": [ + { + "name": "", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + }, + { + "type": "custom", + "name": "", + "input_schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + }, + { + "toolSpec": { + "name": "", + "inputSchema": { + "json": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + } + }, + { + "function_declarations": [ + { + "name": "", + "description": "d" + } + ] + }, + { + "type": "function", + "name": "", + "function": { + "name": "f" + } + } + ], + "expected": "[{\"name\":\"\",\"input_schema\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}},{\"type\":\"anthropic.custom\",\"name\":\"\",\"input_schema\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}},{\"toolSpec\":{\"name\":\"\",\"inputSchema\":{\"json\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}}},{\"name\":\"\",\"description\":\"d\"},{\"type\":\"function\",\"name\":\"f\"}]" + }, + { + "name": "unreadable_entries_kept", + "provider": "openai", + "tools": [ + "plain", + 3, + null, + [ + "x" + ], + { + "description": "no name or type" + }, + { + "type": 7, + "name": "n" + }, + { + "name": false + } + ], + "expected": "[\"plain\",3,null,[\"x\"],{\"description\":\"no name or type\"},{\"type\":7,\"name\":\"n\"},{\"name\":false}]" + }, + { + "name": "proto_key_kept_as_a_member", + "provider": "openai", + "tools": [ + { + "name": "p", + "__proto__": { + "x": 1 + } + } + ], + "expected": "[{\"type\":\"function\",\"name\":\"p\",\"__proto__\":{\"x\":1}}]" + }, + { + "name": "empty_list", + "provider": "openai", + "tools": [], + "expected": "[]" + } + ] +} diff --git a/tests/test_byte_objects.py b/tests/test_byte_objects.py index a76a75f..972ba0b 100644 --- a/tests/test_byte_objects.py +++ b/tests/test_byte_objects.py @@ -519,3 +519,95 @@ def test_model_parameters_holding_byte_objects(exported_spans: InMemorySpanExpor assert written assert not any(_leaks(str(v)) for v in written.values()) assert all(MARKER in str(v) for v in written.values()), written + + +def test_a_blob_of_bytes_in_messages_is_stored_as_its_base64_twin() -> None: + # The SDK's serializer writes the bytes as the marker and strips the + # base64 to a replacement, and the exporter rebuilds each blob with the + # size its replacement names: both forms keep byte_size and store alike. + def messages(content: Any) -> str: + blob = {"type": "blob", "modality": "image", "mime_type": "image/png", "content": content} + return serialize([{"role": "user", "parts": [blob]}]) + + inner = InMemorySpanExporter() + client = init(span_exporter=inner, set_global=False) + for name, content in (("bytes", PNG), ("base64", "iVBORw0KGgo=")): + span = client.get_tracer().start_span(name) + span.set_attribute("gen_ai.input.messages", messages(content)) + span.end() + client.flush() + stored = { + s.name: (s.attributes or {})["gen_ai.input.messages"] for s in inner.get_finished_spans() + } + assert stored["bytes"] == stored["base64"] + [part] = json.loads(str(stored["bytes"]))[0]["parts"] + assert part == { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "byte_size": 8, + "stripped_reason": "not_captured", + } + + +#: A complete replacement whose size has more digits than Python's int() +#: converts from a string (4300, leading zeros included). +_LONG_REPLACEMENT = "[stripped unknown " + "9" * 4301 + " bytes]" + + +@pytest.mark.parametrize( + ("key", "value", "stored"), + [ + pytest.param( + "gen_ai.input.messages", + json.dumps( + [{"role": "user", "parts": [{"type": "blob", "content": _LONG_REPLACEMENT}]}] + ), + # Rebuilt with no byte_size: the size is past 2^53 - 1. + '"parts": [{"type":"blob","modality":"document","stripped_reason":"not_captured"}]', + id="blob-content", + ), + pytest.param( + "output", + json.dumps({"mime_type": _LONG_REPLACEMENT, "data": "QUJD"}), + _LONG_REPLACEMENT, + id="mime-type", + ), + pytest.param( + "output", + json.dumps({"type": "image", "source_type": "base64", "data": _LONG_REPLACEMENT}), + _LONG_REPLACEMENT, + id="data", + ), + ], +) +def test_a_replacement_with_a_long_digit_run_is_exported(key: str, value: str, stored: str) -> None: + # int() refuses such a run, and the strip asks whether each of these + # strings is a replacement: the export must still deliver the span. + inner = InMemorySpanExporter() + client = init(span_exporter=inner, set_global=False) + span = client.get_tracer().start_span("long") + span.set_attribute(key, value) + span.end() + client.flush() + [exported] = inner.get_finished_spans() + assert stored in str((exported.attributes or {})[key]) + + +def test_a_replacement_with_thousands_of_leading_zeros_names_its_size() -> None: + content = "[stripped unknown " + "0" * 5000 + "8 bytes]" + value = json.dumps([{"role": "user", "parts": [{"type": "blob", "content": content}]}]) + inner = InMemorySpanExporter() + client = init(span_exporter=inner, set_global=False) + span = client.get_tracer().start_span("zeros") + span.set_attribute("gen_ai.input.messages", value) + span.end() + client.flush() + [exported] = inner.get_finished_spans() + [part] = json.loads(str((exported.attributes or {})["gen_ai.input.messages"]))[0]["parts"] + assert part == { + "type": "blob", + "modality": "document", + "byte_size": 8, + "stripped_reason": "not_captured", + } diff --git a/tests/test_config.py b/tests/test_config.py index 36664ac..76f18b1 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -19,11 +19,12 @@ "PARTIAL_SPANS_DELAY", ] ENV_VARS = [f"RIUS_{suffix}" for suffix in _SUFFIXES] +OTEL_CAPTURE_CONTENT = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT" @pytest.fixture(autouse=True) def _clear_env(monkeypatch: pytest.MonkeyPatch) -> None: - for var in ENV_VARS: + for var in [*ENV_VARS, OTEL_CAPTURE_CONTENT]: monkeypatch.delenv(var, raising=False) @@ -223,6 +224,101 @@ def test_the_agent_definition_version_is_not_the_service_version( assert resolve_config(main_agent_version="7").service_version is None +# --- the conventions' OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT --- + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("NO_CONTENT", False), + # Rius records content on spans only, so a request for events alone + # asks for no content on the spans Rius keeps. + ("EVENT_ONLY", False), + ("SPAN_ONLY", True), + ("SPAN_AND_EVENT", True), + # Case-insensitive, as the conventions define it. + ("no_content", False), + (" span_only ", True), + ], +) +def test_capture_content_follows_the_otel_setting_when_rius_is_unset( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, raw: str, expected: bool +) -> None: + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, raw) + with caplog.at_level(logging.WARNING, logger="rius.config"): + assert resolve_config().capture_content is expected + assert not caplog.records + + +@pytest.mark.parametrize("raw", ["maybe", "true", "false", "SPAN", "NO-CONTENT"]) +def test_an_unrecognised_otel_capture_setting_keeps_capture_on_and_warns( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, raw: str +) -> None: + # Deliberately not the conventions' NO_CONTENT: capture is on by default in + # Rius, and the warning names the value and what to set instead. + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, raw) + with caplog.at_level(logging.WARNING, logger="rius.config"): + assert resolve_config().capture_content is True + (record,) = caplog.records + message = record.getMessage() + assert f"{OTEL_CAPTURE_CONTENT}={raw!r} is not recognised" in message + assert "content capture stays on" in message + for valid in ("NO_CONTENT", "SPAN_ONLY", "EVENT_ONLY", "SPAN_AND_EVENT"): + assert valid in message + + +@pytest.mark.parametrize("raw", ["", " "]) +def test_an_empty_otel_capture_setting_is_unset( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, raw: str +) -> None: + # OpenTelemetry reads an empty variable as unset; templated deployments + # render an omitted value as one. + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, raw) + with caplog.at_level(logging.WARNING, logger="rius.config"): + assert resolve_config().capture_content is True + assert not caplog.records + + +@pytest.mark.parametrize("raw", ["", " "]) +@pytest.mark.parametrize( + ("otel", "expected"), [("NO_CONTENT", False), ("SPAN_ONLY", True), (None, True)] +) +def test_an_empty_rius_capture_content_is_unset_so_the_otel_setting_applies( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + raw: str, + otel: str | None, + expected: bool, +) -> None: + # Still a warning, as for the other blank RIUS_* flags, but it does not + # shadow the OpenTelemetry setting. + monkeypatch.setenv("RIUS_CAPTURE_CONTENT", raw) + if otel is not None: + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, otel) + with caplog.at_level(logging.WARNING, logger="rius.config"): + assert resolve_config().capture_content is expected + (record,) = caplog.records + assert "RIUS_CAPTURE_CONTENT is empty; treated as unset" in record.getMessage() + + +@pytest.mark.parametrize(("rius", "expected"), [("true", True), ("false", False)]) +def test_rius_capture_content_wins_over_the_otel_setting( + monkeypatch: pytest.MonkeyPatch, rius: str, expected: bool +) -> None: + monkeypatch.setenv("RIUS_CAPTURE_CONTENT", rius) + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, "SPAN_ONLY" if not expected else "NO_CONTENT") + assert resolve_config().capture_content is expected + + +@pytest.mark.parametrize("argument", [True, False]) +def test_the_capture_content_argument_wins_over_both_variables( + monkeypatch: pytest.MonkeyPatch, argument: bool +) -> None: + monkeypatch.setenv("RIUS_CAPTURE_CONTENT", str(not argument).lower()) + monkeypatch.setenv(OTEL_CAPTURE_CONTENT, "SPAN_ONLY" if not argument else "NO_CONTENT") + assert resolve_config(capture_content=argument).capture_content is argument + + # --- an unrecognised boolean keeps the default, with a warning --- diff --git a/tests/test_crash_safety.py b/tests/test_crash_safety.py index b38c95c..b811974 100644 --- a/tests/test_crash_safety.py +++ b/tests/test_crash_safety.py @@ -313,13 +313,12 @@ def test_malformed_tool_calls_do_not_raise_out_of_a_generation( assert [s.name for s in exported_spans.get_finished_spans()] == ["g"] -def test_a_tool_call_whose_function_is_not_a_mapping_keeps_its_id() -> None: +def test_a_tool_call_whose_function_is_not_a_mapping_is_kept_as_text() -> None: + # It has no name, and the conventions require one on a tool_call part. (message,) = normalize_messages( [{"role": "assistant", "tool_calls": [{"id": "c1", "function": "x"}]}], "user" ) - (part,) = message["parts"] - assert part["type"] == "tool_call" - assert part["id"] == "c1" + assert message["parts"] == [{"type": "text", "content": '{"id":"c1"}'}] # --- observe() on a callable without __qualname__ ----------------------------------- diff --git a/tests/test_generation.py b/tests/test_generation.py index 3ec973f..1fc2e4a 100644 --- a/tests/test_generation.py +++ b/tests/test_generation.py @@ -390,6 +390,51 @@ def test_openai_tool_call_message_converted_to_tool_call_part( ] +@pytest.mark.parametrize( + ("function", "content"), + [ + ({"arguments": "{}"}, '{"id":"call_1","arguments":"{}"}'), + ({"name": None, "arguments": "{}"}, '{"id":"call_1","arguments":"{}"}'), + ({"name": 3}, '{"id":"call_1"}'), + ({"name": "", "arguments": '{"q":1}'}, '{"id":"call_1","arguments":"{\\"q\\":1}"}'), + (None, '{"id":"call_1"}'), + ], +) +def test_a_tool_call_without_a_name_is_kept_as_a_text_part( + exported_spans: InMemorySpanExporter, function: Any, content: str +) -> None: + # The conventions require a tool_call part's name, and a part with a known + # type may no longer fall back to the generic part. The call is kept as a + # text part holding its id and arguments, as other content with no part + # type is. + call: dict[str, Any] = {"id": "call_1", "type": "function"} + if function is not None: + call["function"] = function + named = {"id": "call_2", "function": {"name": "lookup", "arguments": "{}"}} + with start_as_current_generation("chat") as gen: + gen.set_output([{"role": "assistant", "content": "hi", "tool_calls": [call, named]}]) + assert _output_messages(exported_spans) == [ + { + "role": "assistant", + "parts": [ + {"type": "text", "content": "hi"}, + {"type": "text", "content": content}, + {"type": "tool_call", "id": "call_2", "name": "lookup", "arguments": "{}"}, + ], + } + ] + + +def test_a_tool_call_without_a_name_or_an_id_keeps_what_it_has( + exported_spans: InMemorySpanExporter, +) -> None: + with start_as_current_generation("chat") as gen: + gen.set_output([{"role": "assistant", "tool_calls": [{}]}]) + assert _output_messages(exported_spans) == [ + {"role": "assistant", "parts": [{"type": "text", "content": "{}"}]} + ] + + def test_tool_response_message_converted_to_tool_call_response_part( exported_spans: InMemorySpanExporter, ) -> None: @@ -554,42 +599,119 @@ def set_attribute(self, key: str, value: Any) -> None: # --- tool definitions --- -def test_cm_tools_kwarg_records_definitions_verbatim( +def test_cm_tools_kwarg_records_openai_tools_in_the_semconv_shape( exported_spans: InMemorySpanExporter, ) -> None: - tools = [ - { - "type": "function", - "function": { - "name": "get_weather", - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}, - }, - } - ] + parameters = {"type": "object", "properties": {"city": {"type": "string"}}} + tools = [{"type": "function", "function": {"name": "get_weather", "parameters": parameters}}] with start_as_current_generation("chat", tools=tools): pass attrs = exported_spans.get_finished_spans()[0].attributes - assert json.loads(attrs["gen_ai.tool.definitions"]) == tools + assert json.loads(attrs["gen_ai.tool.definitions"]) == [ + {"type": "function", "name": "get_weather", "parameters": parameters} + ] -def test_set_tool_definitions_accepts_anthropic_shape( +def test_set_tool_definitions_records_anthropic_tools_in_the_semconv_shape( exported_spans: InMemorySpanExporter, ) -> None: - # Verbatim on purpose: provider tool formats differ (OpenAI nests under - # "function", Anthropic uses top-level name/input_schema) and the backend - # reads names and sizes from either shape. + # Anthropic's custom tool becomes a function tool, and its built-in tool + # keeps its fields with the type prefixed by the provider. + parameters = {"type": "object", "properties": {"q": {"type": "string"}}} tools = [ { "name": "search_kb", "description": "Search the knowledge base", - "input_schema": {"type": "object", "properties": {"q": {"type": "string"}}}, - } + "input_schema": parameters, + }, + {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}, ] gen = start_generation("chat", model="claude-sonnet-5", provider="anthropic") gen.set_tool_definitions(tools) gen.end() attrs = exported_spans.get_finished_spans()[0].attributes - assert json.loads(attrs["gen_ai.tool.definitions"]) == tools + assert json.loads(attrs["gen_ai.tool.definitions"]) == [ + { + "type": "function", + "name": "search_kb", + "description": "Search the knowledge base", + "parameters": parameters, + }, + {"type": "anthropic.web_search_20250305", "name": "web_search", "max_uses": 5}, + ] + + +def test_set_tool_definitions_records_a_pydantic_tool_as_its_fields( + exported_spans: InMemorySpanExporter, +) -> None: + # google-genai's types.Tool is a pydantic model: recorded as its fields + # (unset ones left out), not as its repr. + pydantic = pytest.importorskip("pydantic") + + class Declaration(pydantic.BaseModel): # type: ignore[name-defined,misc] + name: str + description: str | None = None + parameters: dict[str, Any] | None = None + parameters_json_schema: dict[str, Any] | None = None + + class Tool(pydantic.BaseModel): # type: ignore[name-defined,misc] + function_declarations: list[Declaration] | None = None + google_search: dict[str, Any] | None = None + + # Only google-genai's models are dumped: stand in for its module. + Declaration.__module__ = Tool.__module__ = "google.genai.types" + schema = {"type": "object", "properties": {"city": {"type": "string"}}} + tool = Tool(function_declarations=[Declaration(name="f", parameters_json_schema=schema)]) + gen = start_generation("chat", model="gemini-3-pro", provider="gcp.gemini") + gen.set_tool_definitions([tool, {"code_execution": {}}]) + gen.end() + attrs = exported_spans.get_finished_spans()[0].attributes + assert json.loads(attrs["gen_ai.tool.definitions"]) == [ + {"type": "function", "name": "f", "parameters": schema}, + {"code_execution": {}}, + ] + + +def test_set_tool_definitions_does_not_dump_other_pydantic_models( + exported_spans: InMemorySpanExporter, +) -> None: + # A pydantic tool from elsewhere (a LangChain StructuredTool) has no + # known shape: it is recorded as before, not as its dumped fields. + pydantic = pytest.importorskip("pydantic") + + class StructuredTool(pydantic.BaseModel): # type: ignore[name-defined,misc] + name: str + description: str + args_schema: dict[str, Any] + + def __repr__(self) -> str: + return "StructuredTool(add)" + + tool = StructuredTool(name="add", description="Add.", args_schema={"type": "object"}) + gen = start_generation("chat", provider="openai") + gen.set_tool_definitions([tool]) + gen.end() + attrs = exported_spans.get_finished_spans()[0].attributes + recorded = attrs["gen_ai.tool.definitions"] + assert "args_schema" not in recorded + assert "StructuredTool(add)" in recorded + + +def test_set_tool_definitions_keeps_a_model_whose_dump_fails( + exported_spans: InMemorySpanExporter, +) -> None: + class Broken: + def model_dump(self, **_: Any) -> Any: + raise RuntimeError("no") + + def __repr__(self) -> str: + return "Broken()" + + gen = start_generation("chat", provider="gcp.gemini") + gen.set_tool_definitions([Broken()]) + gen.end() + attrs = exported_spans.get_finished_spans()[0].attributes + assert "gen_ai.tool.definitions" in attrs def test_tools_omitted_attribute_absent(exported_spans: InMemorySpanExporter) -> None: @@ -682,7 +804,8 @@ def test_context_sizes_combine_input_output_and_tools( sizes = _sizes_of(exported_spans.get_finished_spans()[0]) call_part = {"type": "tool_call", "id": "c1", "name": "lookup", "arguments": "{}"} call_bytes = len(json.dumps(call_part, separators=(",", ":")).encode()) - tool_bytes = len(json.dumps(tools[0], separators=(",", ":")).encode()) + recorded = {"type": "function", "name": "lookup", "parameters": {}} + tool_bytes = len(json.dumps(recorded, separators=(",", ":")).encode()) assert sizes == { "version": 1, "tool_definitions": [{"name": "lookup", "bytes": tool_bytes}], diff --git a/tests/test_instrumentation.py b/tests/test_instrumentation.py index a74eb08..ece5792 100644 --- a/tests/test_instrumentation.py +++ b/tests/test_instrumentation.py @@ -418,7 +418,9 @@ def test_openai_instrumentor_emits_tool_definitions() -> None: (llm,) = inner.get_finished_spans() assert llm.attributes is not None - assert json.loads(str(llm.attributes["gen_ai.tool.definitions"])) == _TOOLS_OPENAI + assert json.loads(str(llm.attributes["gen_ai.tool.definitions"])) == [ + {"type": "function", **tool["function"]} for tool in _TOOLS_OPENAI + ] assert not [key for key in llm.attributes if key.startswith("llm.tools")] finally: instrumentor.uninstrument() @@ -428,8 +430,8 @@ def test_openai_instrumentor_emits_tool_definitions() -> None: @pytest.mark.integration def test_anthropic_instrumentor_emits_tool_definitions_and_system_message() -> None: """Same contract for Anthropic: `llm.tools.{i}.tool.json_schema` per tool, - reassembled into `gen_ai.tool.definitions` in Anthropic's own shape - (`input_schema`), not rewritten into OpenAI's. + reassembled into `gen_ai.tool.definitions` as conventions function tools + (Anthropic's `input_schema` becomes `parameters`). Also pins that the request's `system` param surfaces as a role=system input message — the segmentation the backend's context attribution @@ -461,8 +463,15 @@ def test_anthropic_instrumentor_emits_tool_definitions_and_system_message() -> N (llm,) = inner.get_finished_spans() assert llm.attributes is not None recorded = json.loads(str(llm.attributes["gen_ai.tool.definitions"])) - assert recorded == _TOOLS_ANTHROPIC - assert "input_schema" in recorded[0] + assert recorded == [ + { + "type": "function", + "name": tool["name"], + "description": tool["description"], + "parameters": tool["input_schema"], + } + for tool in _TOOLS_ANTHROPIC + ] assert not [key for key in llm.attributes if key.startswith("llm.tools")] # The instrumentor's flattened messages leave the process reassembled. messages = json.loads(str(llm.attributes["gen_ai.input.messages"])) diff --git a/tests/test_media_parts.py b/tests/test_media_parts.py index 5c9c9e1..09ce4eb 100644 --- a/tests/test_media_parts.py +++ b/tests/test_media_parts.py @@ -116,6 +116,59 @@ def test_a_part_with_canonical_values_is_canonical(part: dict[str, Any]) -> None }, "blob_with_no_content_and_no_stripped_reason": {"type": "blob", "modality": "audio"}, "blob_with_content_that_is_not_a_string": {"type": "blob", "content": 5, "byte_size": 8.0}, + "blob_with_content_that_is_the_bytes_marker": { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": "[stripped unknown 16 bytes]", + }, + "blob_with_content_that_is_a_replacement_with_a_mime_and_no_hint": { + "type": "blob", + "content": "[stripped image/jpeg 10 bytes]", + }, + "blob_with_content_that_is_a_replacement_and_its_own_mime_type": { + "type": "blob", + "mime_type": "application/pdf", + "content": "[stripped image/png 8 bytes]", + }, + "blob_with_content_that_is_a_replacement_of_unknown_size": { + "type": "blob", + "modality": "audio", + "content": "[stripped unknown unknown bytes]", + }, + "blob_with_content_that_is_a_replacement_too_large_to_keep": { + "type": "blob", + "content": "[stripped unknown 9007199254740992 bytes]", + }, + "blob_with_content_that_is_a_replacement_with_leading_zeros": { + "type": "blob", + "content": "[stripped image/png 0008 bytes]", + }, + "blob_with_content_that_is_a_replacement_with_thousands_of_leading_zeros": { + "type": "blob", + "content": "[stripped unknown " + "0" * 5000 + "8 bytes]", + }, + "blob_with_content_that_is_a_replacement_whose_size_overflows_int64": { + "type": "blob", + "content": "[stripped image/png 99999999999999999999 bytes]", + }, + "blob_with_content_that_is_a_replacement_with_thousands_of_digits": { + "type": "blob", + "content": "[stripped unknown " + "9" * 5000 + " bytes]", + }, + "blob_with_content_that_only_looks_like_a_replacement": { + "type": "blob", + "mime_type": "image/png", + "content": "[stripped image/png lots bytes]", + }, + "blob_with_content_that_is_a_replacement_with_an_invalid_mime": { + "type": "blob", + "content": "[stripped a b 3 bytes]", + }, + "blob_with_content_that_holds_a_replacement_in_text": { + "type": "blob", + "content": "see [stripped unknown 16 bytes]", + }, "uri_with_no_mime_type_and_no_modality": { "type": "uri", "uri": "https://example.com/download", diff --git a/tests/test_normalization_structured_content.py b/tests/test_normalization_structured_content.py new file mode 100644 index 0000000..0a45360 --- /dev/null +++ b/tests/test_normalization_structured_content.py @@ -0,0 +1,365 @@ +"""Content attributes another instrumentation sets as structured values. + +The GenAI conventions now ask for ``gen_ai.input.messages``, +``gen_ai.output.messages``, ``gen_ai.system_instructions`` and +``gen_ai.tool.definitions`` to be maps and arrays rather than JSON strings, +and OpenTelemetry Python keeps such values on a span from 1.45. The exporter +writes each one as the JSON text this SDK writes for the same content, then +treats it exactly as that string: its media parts are rebuilt and stripped, so +no byte of a blob leaves. A span carrying the string and a span carrying the +structured value export the same attributes. + +The spans are built directly rather than through a tracer: OpenTelemetry +before 1.45 drops a mapping attribute when it is set, and the floor CI job runs +this suite on 1.25. +""" + +from __future__ import annotations + +import base64 +import json +import math +from types import MappingProxyType +from typing import Any + +import pytest +from opentelemetry.sdk.trace import ReadableSpan, TracerProvider +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter +from opentelemetry.trace import SpanContext + +from rius._serde import MAX_ATTR_CHARS, MAX_STRIP_CHARS, TRUNCATION_MARKER, byte_object_marker +from rius.normalization import NormalizingSpanExporter +from rius.semconv import ( + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, +) + +PNG = bytes(range(8)) + + +def _export(attributes: dict[str, Any]) -> dict[str, Any]: + context = SpanContext(trace_id=1, span_id=2, is_remote=False) + span = ReadableSpan(name="chat", context=context, attributes=attributes) + sink = InMemorySpanExporter() + NormalizingSpanExporter(sink).export([span]) + [out] = sink.get_finished_spans() + return dict(out.attributes or {}) + + +def _json(value: Any) -> str: + return json.dumps(value, separators=(",", ":"), ensure_ascii=False) + + +_MESSAGES = [ + {"role": "user", "parts": [{"type": "text", "content": "Weather in Paris? & é"}]}, + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "get_weather", + "arguments": {"city": "Paris", "days": 2}, + } + ], + }, +] + + +@pytest.mark.parametrize( + "key", [GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS] +) +def test_a_structured_message_key_is_written_as_its_json(key: str) -> None: + value = _MESSAGES if key != GEN_AI_SYSTEM_INSTRUCTIONS else _MESSAGES[0]["parts"] + exported = _export({key: value}) + assert exported[key] == _json(value) + + +def test_structured_tool_definitions_are_written_as_their_json() -> None: + tools = [ + { + "type": "function", + "name": "get_weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}, + } + ] + assert _export({GEN_AI_TOOL_DEFINITIONS: tools})[GEN_AI_TOOL_DEFINITIONS] == _json(tools) + + +def test_the_value_as_opentelemetry_stores_it_exports_as_the_string_does() -> None: + # OpenTelemetry 1.45 stores a list as a tuple and keeps byte objects, so + # the value a third-party span carries is this shape, not the one it set. + stored = ( + { + "role": "user", + "parts": ( + {"type": "text", "content": "describe"}, + {"type": "blob", "modality": "image", "mime_type": "image/png", "content": PNG}, + ), + }, + ) + as_string = _json( + [ + { + "role": "user", + "parts": [ + {"type": "text", "content": "describe"}, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "content": base64.b64encode(PNG).decode(), + }, + ], + } + ] + ) + structured = _export({GEN_AI_INPUT_MESSAGES: stored, "other": "x"}) + assert structured == _export({GEN_AI_INPUT_MESSAGES: as_string, "other": "x"}) + parts = json.loads(structured[GEN_AI_INPUT_MESSAGES])[0]["parts"] + assert parts[1] == { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "byte_size": 8, + "stripped_reason": "not_captured", + } + + +def test_a_blob_in_the_system_instructions_and_tool_definitions_loses_its_bytes() -> None: + blob = {"type": "blob", "mime_type": "image/png", "content": PNG} + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: [blob], GEN_AI_TOOL_DEFINITIONS: [blob]}) + encoded = base64.b64encode(PNG).decode() + for key in (GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS): + assert encoded not in exported[key] + assert json.loads(exported[key])[0]["type"] == "blob" + + +def test_a_byte_object_anywhere_else_is_the_marker() -> None: + exported = _export( + {GEN_AI_OUTPUT_MESSAGES: [{"role": "assistant", "parts": [{"type": "x", "data": PNG}]}]} + ) + part = json.loads(exported[GEN_AI_OUTPUT_MESSAGES])[0]["parts"][0] + assert part == {"type": "x", "data": byte_object_marker(PNG)} + + +def test_a_memoryview_blob_is_read_as_its_bytes() -> None: + blob = {"type": "blob", "mime_type": "image/png", "content": memoryview(PNG)} + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: [blob]}) + assert json.loads(exported[GEN_AI_SYSTEM_INSTRUCTIONS])[0]["byte_size"] == 8 + + +@pytest.mark.parametrize( + "key", [GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS] +) +def test_a_released_memoryview_blob_is_not_sized_as_empty(key: str) -> None: + # Its bytes cannot be read, so the size is unknown: never 0, which would + # read as an empty blob once the marker's size is taken as the blob's. + view = memoryview(PNG) + view.release() + blob = {"type": "blob", "mime_type": "image/png", "content": view} + value: Any = ( + [blob] if key == GEN_AI_SYSTEM_INSTRUCTIONS else [{"role": "user", "parts": [blob]}] + ) + exported = _export({key: value}) + payload = json.loads(exported[key]) + part = payload[0] if key == GEN_AI_SYSTEM_INSTRUCTIONS else payload[0]["parts"][0] + assert part["type"] == "blob" + assert "byte_size" not in part + + +#: A phone photo's size: its base64 is past the strip budget (1 MiB). +LARGE_PNG = b"\x89PNG\r\n\x1a\n" + bytes(800_000 - 8) +_LARGE_KEYS = [GEN_AI_INPUT_MESSAGES, GEN_AI_OUTPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS] + + +def _with_large_blob(key: str, content: Any) -> Any: + parts = [ + {"type": "text", "content": "describe this"}, + {"type": "blob", "mime_type": "image/png", "modality": "image", "content": content}, + {"type": "text", "content": "and this"}, + ] + if key == GEN_AI_SYSTEM_INSTRUCTIONS: + return parts + return [{"role": "user", "parts": parts}, {"role": "assistant", "parts": [parts[0]]}] + + +def _large_blob_parts(key: str, exported: dict[str, Any]) -> list[Any]: + payload = json.loads(exported[key]) + if key == GEN_AI_SYSTEM_INSTRUCTIONS: + return list(payload) + assert payload[1] == { + "role": "assistant", + "parts": [{"type": "text", "content": "describe this"}], + } + return list(payload[0]["parts"]) + + +@pytest.mark.parametrize("key", _LARGE_KEYS) +@pytest.mark.parametrize("form", ["bytes", "base64"]) +def test_a_blob_past_the_strip_budget_is_stripped_and_sized(key: str, form: str) -> None: + encoded = base64.b64encode(LARGE_PNG).decode() + content: Any = LARGE_PNG if form == "bytes" else encoded + exported = _export({key: _with_large_blob(key, content)}) + assert encoded[:64] not in exported[key] + assert _large_blob_parts(key, exported) == [ + {"type": "text", "content": "describe this"}, + { + "type": "blob", + "modality": "image", + "mime_type": "image/png", + "byte_size": 800_000, + "stripped_reason": "not_captured", + }, + {"type": "text", "content": "and this"}, + ] + + +@pytest.mark.parametrize("key", _LARGE_KEYS) +def test_a_blob_past_the_strip_budget_exports_as_its_json_text(key: str) -> None: + # The bytes, their base64 and the JSON text of the base64 form are one + # content: they export the same attribute. + as_base64 = _with_large_blob(key, base64.b64encode(LARGE_PNG).decode()) + as_text = _export({key: _json(as_base64)}) + assert _export({key: as_base64}) == as_text + assert _export({key: _with_large_blob(key, LARGE_PNG)}) == as_text + + +def test_a_value_past_the_strip_budget_with_no_blob_is_cut_with_its_media_stripped() -> None: + # Encoding whole leaves the strip as the bound: a structured value past + # the budget still lands at the cap, and base64 inside it never exports. + encoded = base64.b64encode(bytes(range(256)) * 8192).decode() + value = [ + {"role": "user", "parts": [{"type": "text", "content": "word " * 400_000}]}, + { + "role": "assistant", + "parts": [ + { + "type": "tool_call", + "id": "call_1", + "name": "upload", + "arguments": {"file": encoded}, + } + ], + }, + ] + assert len(_json(value)) > MAX_STRIP_CHARS + out = _export({GEN_AI_INPUT_MESSAGES: value})[GEN_AI_INPUT_MESSAGES] + assert len(out) <= MAX_ATTR_CHARS + len(TRUNCATION_MARKER) + assert encoded[:64] not in out + + +def test_a_blob_with_no_mime_type_is_sized_from_its_bytes() -> None: + blob = {"type": "blob", "modality": "image", "content": LARGE_PNG} + as_text = {"type": "blob", "modality": "image", "content": base64.b64encode(LARGE_PNG).decode()} + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: [blob]}) + assert exported == _export({GEN_AI_SYSTEM_INSTRUCTIONS: _json([as_text])}) + [part] = json.loads(exported[GEN_AI_SYSTEM_INSTRUCTIONS]) + assert part["byte_size"] == 800_000 + assert "mime_type" not in part + + +def test_any_mapping_is_an_object() -> None: + value = [MappingProxyType({"type": "text", "content": "hi"})] + assert _export({GEN_AI_SYSTEM_INSTRUCTIONS: value})[GEN_AI_SYSTEM_INSTRUCTIONS] == _json( + [{"type": "text", "content": "hi"}] + ) + + +def test_a_non_finite_number_inside_is_null() -> None: + tools = [{"name": "t", "parameters": {"default": math.nan, "max": math.inf}}] + exported = _export({GEN_AI_TOOL_DEFINITIONS: tools}) + assert ( + exported[GEN_AI_TOOL_DEFINITIONS] + == '[{"name":"t","parameters":{"default":null,"max":null}}]' + ) + + +def test_an_array_of_strings_is_its_json_array() -> None: + exported = _export({GEN_AI_SYSTEM_INSTRUCTIONS: ("be brief", "be kind")}) + assert exported[GEN_AI_SYSTEM_INSTRUCTIONS] == '["be brief","be kind"]' + + +def test_a_large_value_is_not_cut_at_the_attribute_cap() -> None: + # A string under the strip budget keeps its length; so does the same + # content as a structured value. + text = "word " * (MAX_ATTR_CHARS // 2) + value = [{"role": "user", "parts": [{"type": "text", "content": text}]}] + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + assert exported[GEN_AI_INPUT_MESSAGES] == _json(value) + assert exported == _export({GEN_AI_INPUT_MESSAGES: _json(value)}) + + +def test_a_value_that_cannot_be_encoded_never_fails_the_export() -> None: + cycle: list[Any] = [{"type": "text", "content": "hi"}] + cycle.append(cycle) + exported = _export({GEN_AI_INPUT_MESSAGES: cycle, "other": "x"}) + assert isinstance(exported[GEN_AI_INPUT_MESSAGES], str) + assert exported["other"] == "x" + + +def test_a_byte_key_never_fails_the_export_or_leaks_its_bytes() -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: [{b"k": PNG}]}) + assert isinstance(exported[GEN_AI_INPUT_MESSAGES], str) + assert "\\x00\\x01" not in exported[GEN_AI_INPUT_MESSAGES] + + +_IMAGE = bytes(range(256)) * 40 +_IMAGE_BASE64 = base64.b64encode(_IMAGE).decode("ascii") + + +def _cyclic_messages_with_a_blob() -> list[Any]: + blob = {"type": "blob", "mime_type": "image/png", "content": _IMAGE} + messages: list[Any] = [{"role": "user", "parts": [blob]}] + messages[0]["self"] = messages + return messages + + +@pytest.mark.parametrize( + "value", + [ + pytest.param(_cyclic_messages_with_a_blob(), id="blob-in-a-cycle"), + pytest.param( + [{b"k": 1, "type": "blob", "mime_type": "image/png", "content": _IMAGE}], + id="blob-in-a-byte-keyed-map", + ), + pytest.param( + [{("a", 1): 1, "parts": [{"type": "blob", "content": _IMAGE}]}], + id="blob-beside-a-tuple-key", + ), + ], +) +def test_a_blob_in_a_value_that_cannot_be_encoded_never_leaks_its_bytes(value: Any) -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + text = exported[GEN_AI_INPUT_MESSAGES] + assert isinstance(text, str) + assert _IMAGE_BASE64[:64] not in text + assert "\\x00\\x01" not in text + assert "[stripped" in text + + +@pytest.mark.parametrize("value", ["already text", 3, True, PNG]) +def test_a_value_that_is_not_structured_is_not_reencoded(value: Any) -> None: + exported = _export({GEN_AI_INPUT_MESSAGES: value}) + expected = byte_object_marker(PNG) if value is PNG else value + assert exported[GEN_AI_INPUT_MESSAGES] == expected + + +def test_other_keys_keep_their_structured_values() -> None: + exported = _export({"app.payload": {"a": [1, 2]}}) + assert exported["app.payload"] == {"a": [1, 2]} + + +def test_a_span_from_a_real_tracer_is_converted() -> None: + probe = TracerProvider().get_tracer("probe").start_span("p", attributes={"m": {"a": 1}}) + if "m" not in (probe.attributes or {}): + pytest.skip("this OpenTelemetry SDK drops mapping attributes (before 1.45)") + sink = InMemorySpanExporter() + tracer = TracerProvider().get_tracer("third.party") + span = tracer.start_span("chat", attributes={GEN_AI_INPUT_MESSAGES: _MESSAGES}) + span.end() + NormalizingSpanExporter(sink).export([span]) # type: ignore[list-item] + [out] = sink.get_finished_spans() + assert (out.attributes or {})[GEN_AI_INPUT_MESSAGES] == _json(_MESSAGES) diff --git a/tests/test_normalization_tools.py b/tests/test_normalization_tools.py index d27c64d..c3a0e98 100644 --- a/tests/test_normalization_tools.py +++ b/tests/test_normalization_tools.py @@ -62,8 +62,7 @@ # openinference-instrumentation-anthropic 2.1.4, _wrappers.py:567-569: the # request's tools, one json_schema per index, in Anthropic's own shape -# (top-level name / input_schema) — which must survive verbatim, not be -# rewritten into OpenAI's. +# (top-level name / input_schema). _ANTHROPIC_TOOLS = [ { "name": "get_weather", @@ -77,6 +76,18 @@ ] +# Both recorded in the conventions' function-tool shape. +_OPENAI_SEMCONV = [{"type": "function", **tool["function"]} for tool in _OPENAI_TOOLS] +_ANTHROPIC_SEMCONV = [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": _ANTHROPIC_TOOLS[0]["input_schema"], + } +] + + def _indexed(tools: list[dict[str, Any]]) -> dict[str, str]: return {f"llm.tools.{i}.tool.json_schema": json.dumps(tool) for i, tool in enumerate(tools)} @@ -122,7 +133,7 @@ def test_openai_function_tools_become_one_definitions_array() -> None: **_indexed(_OPENAI_TOOLS), } out = _exported_attributes(raw) - assert _definitions(out) == _OPENAI_TOOLS + assert _definitions(out) == _OPENAI_SEMCONV assert out == { "openinference.span.kind": "LLM", GEN_AI_OPERATION_NAME: "chat", @@ -134,7 +145,7 @@ def test_openai_function_tools_become_one_definitions_array() -> None: assert not [key for key in out if key.startswith("llm.tools")] -def test_anthropic_input_schema_tools_survive_verbatim() -> None: +def test_anthropic_input_schema_tools_become_function_tools() -> None: raw = { "openinference.span.kind": "LLM", "llm.provider": "anthropic", @@ -142,7 +153,7 @@ def test_anthropic_input_schema_tools_survive_verbatim() -> None: **_indexed(_ANTHROPIC_TOOLS), } out = _exported_attributes(raw) - assert _definitions(out) == _ANTHROPIC_TOOLS + assert _definitions(out) == _ANTHROPIC_SEMCONV assert not [key for key in out if key.startswith("llm.tools")] @@ -153,7 +164,7 @@ def test_the_definitions_are_spelled_like_the_native_path() -> None: out = normalize_tool_definitions(_indexed(_ANTHROPIC_TOOLS)) assert out is not None - assert out[GEN_AI_TOOL_DEFINITIONS] == serialize(_ANTHROPIC_TOOLS) + assert out[GEN_AI_TOOL_DEFINITIONS] == serialize(_ANTHROPIC_SEMCONV) def test_indices_are_ordered_numerically_not_lexically() -> None: @@ -162,7 +173,7 @@ def test_indices_are_ordered_numerically_not_lexically() -> None: attributes = dict(reversed(list(_indexed(tools).items()))) out = normalize_tool_definitions(attributes) assert out is not None - assert _definitions(out) == tools + assert _definitions(out) == [{"type": "function", **tool} for tool in tools] def test_a_native_definitions_key_wins_and_the_indexed_keys_still_go() -> None: @@ -210,7 +221,7 @@ def test_bag_tools_are_promoted_when_llm_tools_is_absent() -> None: ), } out = _exported_attributes(raw) - assert _definitions(out) == _OPENAI_TOOLS + assert _definitions(out) == _OPENAI_SEMCONV assert out[GEN_AI_REQUEST_MODEL] == "gpt-4o" assert out["rius.request.tool_choice"] == "auto" # Every member was promoted somewhere, so the bag goes rather than riding as "{}". @@ -225,7 +236,7 @@ def test_legacy_bag_functions_are_promoted() -> None: {LLM_INVOCATION_PARAMETERS: json.dumps({"functions": functions, "temperature": 0.1})} ) assert out is not None - assert _definitions(out) == functions + assert _definitions(out) == [{"type": "function", **functions[0]}] assert json.loads(out[LLM_INVOCATION_PARAMETERS]) == {"temperature": 0.1} @@ -236,7 +247,10 @@ def test_bag_tools_and_functions_are_both_kept_in_one_array() -> None: {LLM_INVOCATION_PARAMETERS: json.dumps({"tools": tools, "functions": functions})} ) assert out is not None - assert _definitions(out) == tools + functions + assert _definitions(out) == [ + {"type": "function", "name": "a"}, + {"type": "function", "name": "b"}, + ] # Nothing else was in the bag, so the bag goes rather than riding as "{}". assert LLM_INVOCATION_PARAMETERS not in out @@ -249,7 +263,7 @@ def test_llm_tools_wins_over_the_bag_and_the_bag_member_still_goes() -> None: {LLM_INVOCATION_PARAMETERS: bag, **_indexed([{"name": "from-llm-tools"}])} ) assert out is not None - assert _definitions(out) == [{"name": "from-llm-tools"}] + assert _definitions(out) == [{"type": "function", "name": "from-llm-tools"}] assert json.loads(out[LLM_INVOCATION_PARAMETERS]) == {"tool_choice": "auto"} @@ -289,6 +303,38 @@ def test_a_native_definitions_key_wins_over_the_bag_and_the_member_still_goes() } +def test_a_built_in_tool_is_prefixed_with_the_span_provider() -> None: + raw = { + "openinference.span.kind": "LLM", + "llm.provider": "anthropic", + **_indexed([{"type": "web_search_20250305", "name": "web_search"}]), + } + out = _exported_attributes(raw) + assert _definitions(out) == [{"type": "anthropic.web_search_20250305", "name": "web_search"}] + + +@pytest.mark.parametrize( + "route", + ["llm_tools", "bag_tools", "bag_declarations"], +) +def test_definitions_that_come_to_nothing_write_nothing(route: str) -> None: + # The sink writes nothing for an empty list, and the SDK must agree with + # it; the sources still go. + if route == "llm_tools": + attributes = _indexed([{"function_declarations": []}]) + elif route == "bag_tools": + attributes = {LLM_INVOCATION_PARAMETERS: json.dumps({"tools": [], "seed": 1})} + else: + bag = {"tools": [{"function_declarations": []}], "seed": 1} + attributes = {LLM_INVOCATION_PARAMETERS: json.dumps(bag)} + out = normalize_tool_definitions(attributes) + assert out is not None + assert GEN_AI_TOOL_DEFINITIONS not in out + assert not any(key.startswith("llm.tools.") for key in out) + if route != "llm_tools": + assert json.loads(out[LLM_INVOCATION_PARAMETERS]) == {"seed": 1} + + @pytest.mark.parametrize( "bag", [ @@ -336,7 +382,7 @@ def test_promoted_definitions_are_content(capture_content: bool, route: str) -> exported = dict(span.attributes or {}) assert not [key for key in exported if key.startswith("llm.tools")] if capture_content: - assert _definitions(exported) == secret + assert _definitions(exported) == [{"type": "function", **secret[0]}] else: assert GEN_AI_TOOL_DEFINITIONS not in exported assert "SECRET" not in json.dumps(exported) diff --git a/tests/test_sdk_cases.py b/tests/test_sdk_cases.py index 47cc39b..8165755 100644 --- a/tests/test_sdk_cases.py +++ b/tests/test_sdk_cases.py @@ -5,8 +5,10 @@ both SDKs are held to one expected result for each: how input.value and output.value are written, how set_attribute encodes a value, how messages and rius.context.sizes are recorded, what the masking exporter keeps, how RIUS_* -variables resolve, how the resource takes in OTEL_RESOURCE_ATTRIBUTES and how -error.type is named on the Anthropic SDK's own spans. +variables resolve, how the resource takes in OTEL_RESOURCE_ATTRIBUTES, how +error.type is named on the Anthropic SDK's own spans, how a content key +another instrumentation set as a structured value is exported and how tool +definitions are rewritten into the conventions' shape (the sink runs those too). Their README describes the format, including the tagged values JSON cannot hold (``{"$bytes": N}``, ``{"$number": "NaN"}``). """ @@ -21,14 +23,17 @@ from typing import Any import pytest -from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace import ReadableSpan, TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter -from opentelemetry.trace import Status, StatusCode +from opentelemetry.trace import SpanContext, Status, StatusCode import rius +from rius._serde import serialize +from rius._tool_definitions import semconv_tool_definitions from rius.config import resolve_config from rius.masking import MaskingSpanExporter +from rius.normalization import NormalizingSpanExporter CASES = Path(__file__).parent / "fixtures" / "semconv" / "sdk_cases" @@ -123,6 +128,21 @@ def test_anthropic_error_type(case: dict[str, Any], exporter: _Spans) -> None: assert exporter.attributes()["error.type"] == case["expected"] +@pytest.mark.parametrize("case", _cases("structured_content"), ids=_ids("structured_content")) +def test_structured_content(case: dict[str, Any]) -> None: + # Built directly rather than through a tracer: OpenTelemetry before 1.45 + # drops a mapping attribute when it is set, and the floor CI job runs + # this suite on 1.25. + attributes = {key: _value(raw) for key, raw in case["attributes"].items()} + context = SpanContext(trace_id=1, span_id=2, is_remote=False) + sink = InMemorySpanExporter() + NormalizingSpanExporter(sink).export( + [ReadableSpan(name="chat", context=context, attributes=attributes)] + ) + (span,) = sink.get_finished_spans() + assert dict(span.attributes or {}) == case["expected"] + + @pytest.mark.parametrize("case", _cases("attributes"), ids=_ids("attributes")) def test_set_attribute(case: dict[str, Any], exporter: _Spans) -> None: span = rius.start_span("s") @@ -249,3 +269,11 @@ def test_resource(case: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None client.shutdown() assert {key: attributes.get(key) for key in case["expected"]} == case["expected"] assert [key for key in case["absent"] if key in attributes] == [] + + +@pytest.mark.parametrize("case", _cases("tool_definitions"), ids=_ids("tool_definitions")) +def test_tool_definitions(case: dict[str, Any]) -> None: + once = semconv_tool_definitions(case["tools"], case["provider"]) + assert serialize(once) == case["expected"] + # The sink rewrites what the SDK exported: a second pass changes nothing. + assert serialize(semconv_tool_definitions(once, case["provider"])) == case["expected"] diff --git a/tests/test_semconv.py b/tests/test_semconv.py index 848c835..1f9773a 100644 --- a/tests/test_semconv.py +++ b/tests/test_semconv.py @@ -91,6 +91,29 @@ def test_reranker_round_trips_with_the_ai_sdks_rerank_operation() -> None: assert kind_for_operation("rerank") == "RERANKER" +def test_framework_entrypoint_operations_are_chain_spans() -> None: + """The conventions name a framework entrypoint ``invoke_runner``, and + ``invoke_{framework_entrypoint}`` in general, and define it as not being an + agent. The table lists ``invoke_runner``; any other ``invoke_`` operation + the table does not list lands on CHAIN too, while ``invoke_agent`` stays + AGENT.""" + from rius.semconv import kind_for_operation + + assert kind_for_operation("invoke_runner") == "CHAIN" + assert kind_for_operation("invoke_crew") == "CHAIN" + assert kind_for_operation("invoke_workflow") == "CHAIN" + assert kind_for_operation("invoke_agent") == "AGENT" + + +def test_an_unknown_operation_without_the_entrypoint_prefix_has_no_kind() -> None: + from rius.semconv import kind_for_operation + + assert kind_for_operation("invoke_") is None + assert kind_for_operation("invoke") is None + assert kind_for_operation("reinvoke_runner") is None + assert kind_for_operation("made_up") is None + + def test_data_source_id_is_set_only_on_retriever_spans() -> None: from rius.semconv import GEN_AI_DATA_SOURCE_ID, kind_attributes diff --git a/tests/test_span_limits.py b/tests/test_span_limits.py index ccb952a..036bc8d 100644 --- a/tests/test_span_limits.py +++ b/tests/test_span_limits.py @@ -331,7 +331,7 @@ def test_a_twenty_turn_agent_span_keeps_model_tools_usage_and_first_messages( assert attributes["gen_ai.request.model"] == "gpt-4o" assert attributes["gen_ai.request.temperature"] == 0.2 tools = json.loads(str(attributes["gen_ai.tool.definitions"])) - assert [t["function"]["name"] for t in tools] == [f"tool_{i}" for i in range(10)] + assert [t["name"] for t in tools] == [f"tool_{i}" for i in range(10)] assert attributes["gen_ai.usage.input_tokens"] == 1200 assert attributes["gen_ai.usage.output_tokens"] == 30 messages = json.loads(str(attributes["gen_ai.input.messages"])) diff --git a/tests/test_tool_definitions.py b/tests/test_tool_definitions.py new file mode 100644 index 0000000..620e240 --- /dev/null +++ b/tests/test_tool_definitions.py @@ -0,0 +1,466 @@ +"""Tool definitions recorded in the GenAI conventions' shape. + +A ``function`` tool must be ``{"type": "function", "name", "description"?, +"parameters"?}``: the conventions' schema no longer lets a ``function`` tool +that misses that shape fall back to the generic definition. A provider's +built-in tool keeps its own fields, with its ``type`` prefixed by the +provider name (``anthropic.web_search_20250305``). +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from rius._tool_definitions import semconv_tool_definitions + +_PARAMETERS = {"type": "object", "properties": {"city": {"type": "string"}}} + + +def test_openai_nested_function_is_flattened() -> None: + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Weather for a city", + "parameters": _PARAMETERS, + "strict": True, + }, + } + ] + assert semconv_tool_definitions(tools, "openai") == [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": _PARAMETERS, + "strict": True, + } + ] + + +def test_anthropic_custom_tool_becomes_a_function_with_parameters() -> None: + tools = [{"name": "search_kb", "description": "Search", "input_schema": _PARAMETERS}] + assert semconv_tool_definitions(tools, "anthropic") == [ + { + "type": "function", + "name": "search_kb", + "description": "Search", + "parameters": _PARAMETERS, + } + ] + + +def test_anthropic_explicit_custom_type_becomes_a_function() -> None: + tools = [{"type": "custom", "name": "search_kb", "input_schema": _PARAMETERS}] + assert semconv_tool_definitions(tools, "anthropic") == [ + {"type": "function", "name": "search_kb", "parameters": _PARAMETERS} + ] + + +def test_legacy_openai_function_without_type_becomes_a_function() -> None: + tools = [{"name": "get_weather", "parameters": _PARAMETERS}] + assert semconv_tool_definitions(tools, None) == [ + {"type": "function", "name": "get_weather", "parameters": _PARAMETERS} + ] + + +def test_flat_function_with_camel_case_input_schema_names_it_parameters() -> None: + # The Vercel AI SDK's function tool spells the schema inputSchema. + tools = [{"type": "function", "name": "get_weather", "inputSchema": _PARAMETERS}] + assert semconv_tool_definitions(tools, "openai") == [ + {"type": "function", "name": "get_weather", "parameters": _PARAMETERS} + ] + + +def test_semconv_function_tool_is_unchanged() -> None: + tool = {"type": "function", "name": "get_weather", "parameters": _PARAMETERS} + assert semconv_tool_definitions([tool], "openai") == [tool] + + +def test_provider_built_in_tool_type_is_prefixed() -> None: + tools = [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}] + assert semconv_tool_definitions(tools, "anthropic") == [ + {"type": "anthropic.web_search_20250305", "name": "web_search", "max_uses": 5} + ] + + +def test_built_in_tool_without_a_name_gets_none_invented() -> None: + assert semconv_tool_definitions([{"type": "web_search"}], "openai") == [ + {"type": "openai.web_search"} + ] + + +def test_built_in_tool_is_left_unprefixed_without_a_provider() -> None: + tool = {"type": "web_search_20250305", "name": "web_search"} + assert semconv_tool_definitions([tool], None) == [tool] + assert semconv_tool_definitions([tool], "") == [tool] + + +def test_an_already_namespaced_type_is_not_prefixed_again() -> None: + tool = {"type": "anthropic.web_search_20250305", "name": "web_search"} + assert semconv_tool_definitions([tool], "anthropic") == [tool] + # A provider whose name has dots of its own does not stack a second prefix. + assert semconv_tool_definitions([tool], "azure.ai.openai") == [tool] + + +def test_vercel_provider_tool_takes_its_namespaced_id_as_type() -> None: + tool = { + "type": "provider-defined", + "id": "anthropic.web_search_20250305", + "name": "web_search", + "args": {}, + } + assert semconv_tool_definitions([tool], "anthropic") == [ + {**tool, "type": "anthropic.web_search_20250305"} + ] + + +def test_bedrock_tool_spec_becomes_a_function_with_its_json_schema() -> None: + # Bedrock Converse wraps the function in toolSpec and the schema in + # inputSchema.json. + tools = [ + { + "toolSpec": { + "name": "get_weather", + "description": "Weather for a city", + "inputSchema": {"json": _PARAMETERS}, + } + } + ] + assert semconv_tool_definitions(tools, "aws.bedrock") == [ + { + "type": "function", + "name": "get_weather", + "description": "Weather for a city", + "parameters": _PARAMETERS, + } + ] + + +def test_bedrock_tool_spec_without_a_name_or_a_cache_point_is_kept() -> None: + nameless = {"toolSpec": {"inputSchema": {"json": _PARAMETERS}}} + cache_point = {"cachePoint": {"type": "default"}} + assert semconv_tool_definitions([nameless, cache_point], "aws.bedrock") == [ + nameless, + cache_point, + ] + + +@pytest.mark.parametrize( + ("container", "schema"), + [("function_declarations", "parameters"), ("functionDeclarations", "parametersJsonSchema")], +) +def test_gemini_declarations_become_one_function_tool_each(container: str, schema: str) -> None: + tools = [ + { + container: [ + {"name": "get_weather", "description": "Weather", schema: _PARAMETERS}, + {"name": "get_time"}, + ] + }, + {"name": "lookup", "input_schema": _PARAMETERS}, + ] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + { + "type": "function", + "name": "get_weather", + "description": "Weather", + "parameters": _PARAMETERS, + }, + {"type": "function", "name": "get_time"}, + {"type": "function", "name": "lookup", "parameters": _PARAMETERS}, + ] + + +def test_gemini_snake_case_json_schema_is_named_parameters() -> None: + tools = [{"function_declarations": [{"name": "f", "parameters_json_schema": _PARAMETERS}]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "f", "parameters": _PARAMETERS} + ] + + +def test_gemini_built_ins_beside_declarations_are_kept_without_a_name() -> None: + # A built-in has no name of its own: inventing one would record a tool + # that is offered but never called by that name. + tools = [ + {"function_declarations": [{"name": "f"}], "google_search": {}}, + {"code_execution": {}}, + ] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "f"}, + {"google_search": {}}, + {"code_execution": {}}, + ] + + +def test_gemini_declaration_without_a_name_is_kept_as_given() -> None: + tools = [{"functionDeclarations": [{"description": "no name"}, "odd"]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [{"description": "no name"}, "odd"] + + +def test_gemini_container_that_is_not_a_list_is_kept() -> None: + tool = {"function_declarations": {"name": "f"}} + assert semconv_tool_definitions([tool], "gcp.gemini") == [tool] + + +@pytest.mark.parametrize("tool", ["plain", 3, None, ["x"], {"description": "no name or type"}]) +def test_anything_unreadable_is_kept_as_it_is(tool: Any) -> None: + assert semconv_tool_definitions([tool], "openai") == [tool] + + +def test_normalizing_twice_equals_once() -> None: + tools = [ + {"type": "function", "function": {"name": "a", "parameters": _PARAMETERS}}, + {"name": "b", "input_schema": _PARAMETERS}, + {"type": "web_search_20250305", "name": "web_search"}, + {"toolSpec": {"name": "c", "inputSchema": {"json": _PARAMETERS}}}, + {"functionDeclarations": [{"name": "d", "parametersJsonSchema": _PARAMETERS}]}, + {"function_declarations": [{"name": "e"}], "google_search": {}}, + ] + once = semconv_tool_definitions(tools, "anthropic") + assert semconv_tool_definitions(once, "anthropic") == once + + +def test_the_caller_list_is_not_mutated() -> None: + tools = [{"name": "b", "input_schema": _PARAMETERS}, {"type": "web_search"}] + semconv_tool_definitions(tools, "openai") + assert tools == [{"name": "b", "input_schema": _PARAMETERS}, {"type": "web_search"}] + + +# --- second-pass stability: every output is already in the conventions' shape + + +def test_every_list_valued_declarations_key_expands() -> None: + tools = [{"function_declarations": [{"name": "a"}], "functionDeclarations": [{"name": "b"}]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "a"}, + {"type": "function", "name": "b"}, + ] + + +def test_a_declarations_spelling_that_is_not_a_list_stays_in_the_rest() -> None: + tools = [{"function_declarations": [{"name": "a"}], "functionDeclarations": "odd"}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "a"}, + {"functionDeclarations": "odd"}, + ] + + +@pytest.mark.parametrize("spelling", ["input_schema", "inputSchema"]) +def test_a_declaration_schema_in_any_spelling_is_named_parameters(spelling: str) -> None: + tools = [{"function_declarations": [{"name": "a", spelling: _PARAMETERS}]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "a", "parameters": _PARAMETERS} + ] + + +def test_a_nameless_declaration_takes_the_single_tool_rule() -> None: + tools = [{"function_declarations": [{"type": "web_search"}]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [{"type": "gcp.gemini.web_search"}] + + +def test_the_rest_of_a_gemini_tool_takes_the_single_tool_rule() -> None: + tools = [{"function_declarations": [{"name": "a"}], "name": "x"}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "a"}, + {"type": "function", "name": "x"}, + ] + + +def test_a_nested_function_is_not_lifted_over_a_top_level_name() -> None: + named = {"name": "x", "function": {"name": "y"}} + typed = {"type": "function", "name": "x", "function": {"name": "y"}} + assert semconv_tool_definitions([named, typed], "openai") == [ + {"type": "function", "name": "x", "function": {"name": "y"}}, + typed, + ] + + +def test_a_null_parameters_gives_way_to_a_schema_spelling() -> None: + # A Python model_dump() of a google-genai FunctionDeclaration. + tools = [ + { + "function_declarations": [ + {"name": "f", "parameters": None, "parameters_json_schema": _PARAMETERS} + ] + }, + {"name": "g", "parameters": None, "input_schema": _PARAMETERS}, + ] + assert semconv_tool_definitions(tools, "gcp.gemini") == [ + {"type": "function", "name": "f", "parameters": _PARAMETERS}, + {"type": "function", "name": "g", "parameters": _PARAMETERS}, + ] + + +def test_a_null_parameters_without_another_schema_is_kept() -> None: + tool = {"type": "function", "name": "f", "parameters": None} + assert semconv_tool_definitions([tool], "openai") == [tool] + + +def test_an_empty_type_gets_no_provider_prefix() -> None: + tool = {"type": "", "size": 1} + assert semconv_tool_definitions([tool], "openai") == [tool] + + +def test_mcp_tool_headers_are_dropped() -> None: + # OpenAI Responses' MCP tool carries the server's request headers, which + # can hold an Authorization credential. + tool = { + "type": "mcp", + "server_label": "docs", + "server_url": "https://mcp.example.com", + "headers": {"Authorization": "Bearer secret"}, + "require_approval": "never", + } + assert semconv_tool_definitions([tool], "openai") == [ + { + "type": "openai.mcp", + "server_label": "docs", + "server_url": "https://mcp.example.com", + "require_approval": "never", + } + ] + namespaced = {"type": "openai.mcp", "server_label": "docs", "headers": {"X-Key": "k"}} + assert semconv_tool_definitions([namespaced], None) == [ + {"type": "openai.mcp", "server_label": "docs"} + ] + assert semconv_tool_definitions([{"type": "mcp", "headers": {}}], None) == [{"type": "mcp"}] + + +@pytest.mark.parametrize("kind", ["mcp", "openai.mcp", "azure.mcp"]) +def test_mcp_tool_authorization_is_dropped_with_its_headers(kind: str) -> None: + # OpenAI's MCP tool also carries `authorization`, an OAuth access token + # for the remote server or connector. + tool = { + "type": kind, + "server_label": "gh", + "connector_id": "connector_gmail", + "authorization": "ya29.token", + "headers": {"Authorization": "Bearer secret"}, + } + once = semconv_tool_definitions([tool], "openai") + assert once == [ + { + "type": "openai.mcp" if kind == "mcp" else kind, + "server_label": "gh", + "connector_id": "connector_gmail", + } + ] + assert semconv_tool_definitions(once, "openai") == once + + +def test_a_vercel_mcp_provider_tool_loses_its_credentials() -> None: + # The Vercel AI SDK's id becomes the type: once it reads `*.mcp`, the + # credentials go, as they would on a second pass. + tool = {"type": "provider", "id": "openai.mcp", "name": "mcp", "authorization": "t"} + once = semconv_tool_definitions([tool], None) + assert once == [{"type": "openai.mcp", "id": "openai.mcp", "name": "mcp"}] + assert semconv_tool_definitions(once, None) == once + + +def test_other_tools_keep_an_authorization_member() -> None: + tool = {"type": "web_search", "authorization": "kept"} + assert semconv_tool_definitions([tool], "openai") == [ + {"type": "openai.web_search", "authorization": "kept"} + ] + + +def test_chat_completions_custom_tool_is_lifted_and_stays_custom() -> None: + # Chat Completions nests a custom tool's fields under `custom`; they are + # lifted as `function`'s are, and the tool stays a provider tool. + tool = { + "type": "custom", + "custom": {"name": "code_exec", "description": "Runs code", "format": {"type": "text"}}, + } + once = semconv_tool_definitions([tool], "openai") + assert once == [ + { + "type": "openai.custom", + "name": "code_exec", + "description": "Runs code", + "format": {"type": "text"}, + } + ] + assert semconv_tool_definitions(once, "openai") == once + + +def test_a_nested_custom_is_not_lifted_over_a_top_level_name() -> None: + tool = {"type": "custom", "name": "x", "custom": {"name": "y"}} + assert semconv_tool_definitions([tool], "openai") == [ + {"type": "openai.custom", "name": "x", "custom": {"name": "y"}} + ] + + +def test_a_lifted_custom_tool_with_an_input_schema_is_a_function() -> None: + # Anthropic's custom tool rule applies to the lifted tool too, so the + # output is the same whether or not the provider prefixed it. + tool = {"type": "custom", "custom": {"name": "f", "input_schema": _PARAMETERS}} + for provider in ("anthropic", None): + once = semconv_tool_definitions([tool], provider) + assert once == [{"type": "function", "name": "f", "parameters": _PARAMETERS}] + assert semconv_tool_definitions(once, provider) == once + + +@pytest.mark.parametrize( + "tool", + [ + {"name": ""}, + {"name": "", "input_schema": _PARAMETERS}, + {"type": "custom", "name": "", "input_schema": _PARAMETERS}, + {"toolSpec": {"name": "", "inputSchema": {"json": _PARAMETERS}}}, + ], +) +def test_an_empty_name_is_no_name(tool: dict[str, Any]) -> None: + # As for tool calls, an empty name is a missing one: no function tool + # with an empty name is made. + once = semconv_tool_definitions([tool], None) + assert once == [tool] + assert semconv_tool_definitions(once, None) == once + + +def test_a_gemini_declaration_with_an_empty_name_is_not_a_function() -> None: + tools = [{"function_declarations": [{"name": "", "description": "d"}]}] + assert semconv_tool_definitions(tools, "gcp.gemini") == [{"name": "", "description": "d"}] + + +def test_a_nested_function_is_lifted_over_an_empty_top_level_name() -> None: + tool = {"type": "function", "name": "", "function": {"name": "f"}} + assert semconv_tool_definitions([tool], "openai") == [{"type": "function", "name": "f"}] + + +def test_a_vercel_mcp_provider_tool_loses_the_credentials_in_its_args() -> None: + # The AI SDK's openai.mcp tool carries the request's credentials in args. + tool = { + "type": "provider", + "id": "openai.mcp", + "name": "mcp", + "args": { + "serverLabel": "docs", + "serverUrl": "https://mcp.example.com", + "authorization": "token", + "headers": {"Authorization": "Bearer secret"}, + "requireApproval": "never", + }, + } + once = semconv_tool_definitions([tool], None) + assert once == [ + { + "type": "openai.mcp", + "id": "openai.mcp", + "name": "mcp", + "args": { + "serverLabel": "docs", + "serverUrl": "https://mcp.example.com", + "requireApproval": "never", + }, + } + ] + assert semconv_tool_definitions(once, None) == once + + +def test_other_tools_keep_the_credentials_in_their_args() -> None: + tool = {"type": "provider", "id": "openai.web_search", "args": {"authorization": "kept"}} + assert semconv_tool_definitions([tool], None) == [{**tool, "type": "openai.web_search"}]