Skip to content

fix: sanitize Pydantic V2 schemas for Gemini API compatibility#183

Open
jnMetaCode wants to merge 1 commit intoIntelligent-Internet:mainfrom
jnMetaCode:fix/gemini-schema-validation
Open

fix: sanitize Pydantic V2 schemas for Gemini API compatibility#183
jnMetaCode wants to merge 1 commit intoIntelligent-Internet:mainfrom
jnMetaCode:fix/gemini-schema-validation

Conversation

@jnMetaCode
Copy link

Problem

When using Gemini models, tool schemas generated by Pydantic V2 contain
JSON Schema keywords that Gemini rejects with extra_forbidden validation
errors:

function_declarations.8.parameters.properties.prNumber.exclusiveMinimum
Extra inputs are not permitted [type=extra_forbidden]

function_declarations.9.parameters.properties.ecosystem.const
Extra inputs are not permitted [type=extra_forbidden]

The Gemini API expects a restricted OpenAPI-style subset of JSON Schema,
but tool.input_schema is passed through without any sanitization.

Fix

Added _sanitize_schema_for_gemini() which recursively walks the schema
and converts incompatible keywords:

Pydantic V2 keyword Converted to
exclusiveMinimum minimum
exclusiveMaximum maximum
const enum (single element)
anyOf [T, null] flattened to T
$schema, title, default, examples removed

Applied to tool.input_schema in the generate() method before
building the function declarations.

Related issue

Fixes #171

Gemini rejects JSON Schema keywords like exclusiveMinimum, const, and
anyOf that Pydantic V2 emits by default. Add a recursive sanitizer
that converts these into the OpenAPI subset Gemini expects:

  - exclusiveMinimum -> minimum
  - exclusiveMaximum -> maximum
  - const -> enum (single element)
  - anyOf [T, null] -> flattened to T (Optional pattern)
  - strips $schema, additionalProperties, title, default, examples

Fixes Intelligent-Internet#171
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant