Skip to content

fix(py/otel): serialize Pydantic tool call arguments as valid JSON - #7098

Closed
huangjeff5 wants to merge 2 commits into
mainfrom
fix/py-otel-tool-call-arguments-json
Closed

huangjeff5 wants to merge 2 commits into
mainfrom
fix/py-otel-tool-call-arguments-json

Conversation

@huangjeff5

Copy link
Copy Markdown
Contributor

Problem

When instrumenting Genkit tool executions with GenAiInstrumentation (with emit_tool_spans=True or content capturing modes enabled), tool input is typically a Pydantic BaseModel instance. _set_json_attribute and _record_tool_content previously serialized inputs directly via json.dumps(value, default=str). Because Pydantic models fall through to str(model), gen_ai.tool.call.arguments was written as a stringified Python repr (e.g. "OrderInput(dish='pad thai', quantity=2)") rather than valid JSON ({"dish": "pad thai", "quantity": 2}), violating OpenTelemetry GenAI semantic conventions.

Mechanism

Introduced _encode_json_value(value: object) -> str:

  • When value is an instance of pydantic.BaseModel, calls value.model_dump(mode='json') before JSON serialization.
  • Used in both _set_json_attribute and _record_tool_content for both span attributes and OTel log events.

Verification

  • Added test_tool_arguments_pydantic_serialized_as_valid_json in packages/genkit-otel/tests/genai_instrumentation_test.py verifying that Pydantic inputs are serialized to valid JSON readable via json.loads() on both tool spans and operation details log events.
  • Ran pytest packages/genkit-otel (77 passed).
  • Verified ruff check, ruff format, and pyright clean.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a helper function _encode_json_value to serialize Pydantic models to JSON before setting span attributes or recording tool content, along with a unit test to verify this behavior. However, the current implementation only handles top-level BaseModel instances and fails to serialize nested Pydantic models inside lists or dictionaries. It is recommended to use a custom default encoder function within json.dumps to dynamically handle nested Pydantic models.

@huangjeff5

Copy link
Copy Markdown
Contributor Author

Closing: migrated to standalone repository genkit-ai/genkit-python (PR #39): genkit-ai/genkit-python#39

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant