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/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..d5595b2 100644 --- a/src/rius/normalization.py +++ b/src/rius/normalization.py @@ -128,6 +128,7 @@ serialize, 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 +581,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 +634,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 +642,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 +713,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 +763,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 +791,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 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/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_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_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..03b8d71 100644 --- a/tests/test_sdk_cases.py +++ b/tests/test_sdk_cases.py @@ -5,8 +5,9 @@ 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 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"}``). """ @@ -27,6 +28,8 @@ from opentelemetry.trace import 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 @@ -249,3 +252,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_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"}]