diff --git a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py index ed98af54c..c43e3f810 100644 --- a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py +++ b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py @@ -318,8 +318,8 @@ def _record_tool_content(self, span: Span, input: object, output: object) -> Non _set_json_attribute(span, GenAiAttr.TOOL_CALL_RESULT, output) if self._capture_on_event: event_attrs: dict[str, AttributeValue] = { - GenAiAttr.TOOL_CALL_ARGUMENTS: json.dumps(input, default=str), - GenAiAttr.TOOL_CALL_RESULT: json.dumps(output, default=str), + GenAiAttr.TOOL_CALL_ARGUMENTS: _encode_json_value(input), + GenAiAttr.TOOL_CALL_RESULT: _encode_json_value(output), } _emit_operation_details(self._otel_logger, event_attrs) @@ -519,11 +519,27 @@ def _pick(config: Mapping[str, object], *keys: str) -> object: return None +def _encode_json_value(value: object) -> str: + """Encode an object as a JSON string, dumping Pydantic models to dicts first. + + Strings are encoded too (``'ORD-555'`` -> ``'"ORD-555"'``), so every JSON + attribute round-trips through ``json.loads``. Same shape as JS ``JSON.stringify`` + for JSON-safe values. + """ + + def _json_default(obj: object) -> object: + if isinstance(obj, BaseModel): + return obj.model_dump(mode='json', by_alias=True, exclude_none=True) + return str(obj) + + return json.dumps(value, default=_json_default) + + def _set_json_attribute(span: Span, key: str, value: object) -> None: if value is None: return try: - encoded = value if isinstance(value, str) else json.dumps(value, default=str) + encoded = _encode_json_value(value) except (TypeError, ValueError) as exc: encoded = f'Unable to encode: {exc}' span.set_attribute(key, encoded) diff --git a/packages/genkit-otel/tests/genai_encoding_test.py b/packages/genkit-otel/tests/genai_encoding_test.py new file mode 100644 index 000000000..91681fc79 --- /dev/null +++ b/packages/genkit-otel/tests/genai_encoding_test.py @@ -0,0 +1,56 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tool call content attributes encode Pydantic values with wire aliases and no null fields.""" + +import json + +from genkit_otel._genai_instrumentation import _encode_json_value +from pydantic import BaseModel, ConfigDict, Field + + +class Reservation(BaseModel): + model_config = ConfigDict(populate_by_name=True) + + party_size: int = Field(alias='partySize') + notes: str | None = None + + +def test_pydantic_value_uses_wire_aliases_and_drops_none() -> None: + """A model with an alias and a None field encodes as {"partySize": 4}, the shape core's genkit:input uses.""" + booking = Reservation.model_validate({'partySize': 4}) + + assert json.loads(_encode_json_value(booking)) == {'partySize': 4} + + +def test_nested_pydantic_values_are_encoded() -> None: + """Models inside lists and dicts encode the same way.""" + value = { + 'bookings': [ + Reservation.model_validate({'partySize': 2}), + Reservation.model_validate({'partySize': 6, 'notes': 'window'}), + ] + } + + assert json.loads(_encode_json_value(value)) == { + 'bookings': [{'partySize': 2}, {'partySize': 6, 'notes': 'window'}], + } + + +def test_plain_string_is_json_encoded() -> None: + """A str is JSON-encoded like every other value, so json.loads round-trips it (JS JSON.stringify).""" + assert _encode_json_value('table for two') == '"table for two"' + assert json.loads(_encode_json_value('table for two')) == 'table for two' diff --git a/packages/genkit-otel/tests/genai_instrumentation_test.py b/packages/genkit-otel/tests/genai_instrumentation_test.py index c064d5ae2..14c898f2b 100644 --- a/packages/genkit-otel/tests/genai_instrumentation_test.py +++ b/packages/genkit-otel/tests/genai_instrumentation_test.py @@ -15,6 +15,7 @@ # SPDX-License-Identifier: Apache-2.0 import asyncio +import json from collections.abc import Mapping from typing import get_args @@ -394,6 +395,98 @@ async def test_span_and_event_records_tool_arguments_on_span_and_event(harness) assert 'classified' in attrs[GenAiAttr.TOOL_CALL_RESULT] +@pytest.mark.asyncio +async def test_tool_arguments_pydantic_serialized_as_valid_json(harness) -> None: + """Pydantic tool input and result serialize to valid JSON on tool spans and events.""" + from pydantic import BaseModel + + class OrderInput(BaseModel): + dish: str + quantity: int + + class OrderOutput(BaseModel): + status: str + + instr = harness.instrumentation(content_capturing_mode='SPAN_AND_EVENT', emit_tool_spans=True) + + async def order_tool(span=None): + return OrderOutput(status='confirmed') + + await instr.run_in_new_span( + SpanMetadata(name='order_food', action_type='tool.v2', input=OrderInput(dish='pad thai', quantity=2)), + order_tool, + ) + span = harness.span_named('execute_tool order_food') + assert span is not None + raw_args = harness.attr(span, GenAiAttr.TOOL_CALL_ARGUMENTS) + assert raw_args is not None + parsed = json.loads(raw_args) + assert parsed == {'dish': 'pad thai', 'quantity': 2} + raw_result = harness.attr(span, GenAiAttr.TOOL_CALL_RESULT) + assert raw_result is not None + assert json.loads(raw_result) == {'status': 'confirmed'} + + record = _operation_details_record(harness) + assert record is not None + attrs = dict(record.attributes or {}) + raw_event_args = attrs[GenAiAttr.TOOL_CALL_ARGUMENTS] + assert isinstance(raw_event_args, str) + event_parsed = json.loads(raw_event_args) + assert event_parsed == {'dish': 'pad thai', 'quantity': 2} + raw_event_result = attrs[GenAiAttr.TOOL_CALL_RESULT] + assert isinstance(raw_event_result, str) + assert json.loads(raw_event_result) == {'status': 'confirmed'} + + +@pytest.mark.asyncio +async def test_tool_arguments_nested_pydantic_serialized_as_valid_json(harness) -> None: + """Nested Pydantic models in lists/dicts serialize to valid JSON.""" + from pydantic import BaseModel + + class Item(BaseModel): + name: str + qty: int + + instr = harness.instrumentation(content_capturing_mode='SPAN_AND_EVENT', emit_tool_spans=True) + + await instr.run_in_new_span( + SpanMetadata( + name='bulk_order', + action_type='tool.v2', + input={'items': [Item(name='spring roll', qty=4)], 'special': Item(name='pad thai', qty=1)}, + ), + lambda span=None: _awaitable({'status': 'ok'}), + ) + span = harness.span_named('execute_tool bulk_order') + assert span is not None + raw_args = harness.attr(span, GenAiAttr.TOOL_CALL_ARGUMENTS) + assert raw_args is not None + parsed = json.loads(raw_args) + assert parsed == {'items': [{'name': 'spring roll', 'qty': 4}], 'special': {'name': 'pad thai', 'qty': 1}} + + +@pytest.mark.asyncio +async def test_tool_string_arguments_and_result_are_json_encoded(harness) -> None: + """A str tool input and output land as JSON strings, so json.loads round-trips them.""" + instr = harness.instrumentation(content_capturing_mode='SPAN_AND_EVENT', emit_tool_spans=True) + + await instr.run_in_new_span( + SpanMetadata(name='confirm_order', action_type='tool', input='ORD-555'), + lambda span=None: _awaitable('CONFIRMED:ORD-555'), + ) + span = harness.span_named('execute_tool confirm_order') + assert span is not None + assert harness.attr(span, GenAiAttr.TOOL_CALL_ARGUMENTS) == '"ORD-555"' + assert json.loads(harness.attr(span, GenAiAttr.TOOL_CALL_ARGUMENTS)) == 'ORD-555' + assert json.loads(harness.attr(span, GenAiAttr.TOOL_CALL_RESULT)) == 'CONFIRMED:ORD-555' + + record = _operation_details_record(harness) + assert record is not None + attrs = dict(record.attributes or {}) + assert json.loads(str(attrs[GenAiAttr.TOOL_CALL_ARGUMENTS])) == 'ORD-555' + assert json.loads(str(attrs[GenAiAttr.TOOL_CALL_RESULT])) == 'CONFIRMED:ORD-555' + + @pytest.mark.asyncio async def test_does_not_capture_action_io_by_default(harness) -> None: instr = harness.instrumentation() @@ -433,8 +526,8 @@ async def sunny(span=None): ) tool = harness.span_named('execute_tool weather') assert tool is not None - assert 'Paris' in harness.attr(tool, GenkitAttr.INPUT) - assert 'sunny' in harness.attr(tool, GenkitAttr.OUTPUT) + assert harness.attr(tool, GenkitAttr.INPUT) == '"Paris"' + assert harness.attr(tool, GenkitAttr.OUTPUT) == '"sunny"' assert harness.attr(tool, GenAiAttr.INPUT_MESSAGES) is None assert harness.attr(tool, GenAiAttr.OUTPUT_MESSAGES) is None @@ -444,8 +537,8 @@ async def flow_out(span=None): await instr.run_in_new_span(SpanMetadata(name='myFlow', action_type='flow', input='in'), flow_out) flow = harness.span_named('myFlow') assert flow is not None - assert 'in' in harness.attr(flow, GenkitAttr.INPUT) - assert 'out' in harness.attr(flow, GenkitAttr.OUTPUT) + assert harness.attr(flow, GenkitAttr.INPUT) == '"in"' + assert harness.attr(flow, GenkitAttr.OUTPUT) == '"out"' assert harness.attr(flow, GenAiAttr.INPUT_MESSAGES) is None