Skip to content

Gemini: strip JSON-Schema fields the API rejects + bump default to 3.5-flash - #153

Merged
FMXExpress merged 2 commits into
mainfrom
claude/gemini-schema-strip-and-default
Jun 6, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/gemini-schema-strip-and-default

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

TL;DR

Two fixes — both visible the second you point an LLM loop at Gemini.

1. Schema sanitisation (the 400 you hit)

Gemini's function-calling API accepts only an OpenAPI 3.0 subset of JSON Schema. MCP servers and external skill manifests frequently emit additionalProperties: false on their tool parameter schemas (it's the JSON Schema "strict mode" convention). Anthropic and OpenAI ignore the extra field silently; Gemini 400s with:

Unknown name "additionalProperties" at
'tools[0].function_declarations[16].parameters.properties[2].value':
Cannot find field

— exactly what you saw. The Gemini docs say "only a subset of OpenAPI schema is supported" but don't enumerate which fields are rejected; turns out it's a fair number.

New PasClaw.Providers.Gemini.SanitizeSchemaForGemini parses each tool's schema, recursively strips the offending fields, and re-emits. Walks properties / items / anyOf / oneOf children so nested schemas get the same treatment.

Fields stripped (only when sending to Gemini — Anthropic and OpenAI still see the original schemas unchanged):

additionalProperties   # the actual blocker
$schema, $id, $ref     # meta — Gemini doesn't model
definitions, $defs     # JSON Schema 2019-09+ — Gemini takes OpenAPI 3.0
patternProperties      # not in OpenAPI 3.0
unevaluatedProperties  # JSON Schema 2019-09+
propertyNames          # JSON Schema 2019-09+

On parse failure, the helper returns the input verbatim so a genuinely-malformed schema still surfaces Gemini's own 400 with the actual pointer, instead of getting silently dropped.

2. Default Gemini model: gemini-1.5-flash → gemini-3.5-flash

1.5-flash is the 18-months-stale free-tier default the catalog scaffold ships with. 3.5-flash is the current GA model — function calling, structured outputs, code execution, search grounding. Operators who'd already picked a model in config.json are unaffected; the catalog default only applies when Cfg.Providers[i].Model is empty.

Supporting change

PasClaw.JSON.TJsonObject.Remove(Key) — needed for the recursive walker; existed as an internal RemoveKey helper, now exposed. FPC + Delphi backends both implemented.

Verified

  • make and make smoke clean on Linux + FPC
  • SanitizeSchemaForGemini round-trip on a schema matching the shape in your 400 — additionalProperties removed, rest preserved
  • Live exercise: configure gemini provider, run pasclaw agent -m "list files in pwd" with MCP tools enabled. The 400 should be gone.

What's NOT in this PR

Your other question — "how can it list the models available when I got to select a model in the onboarding?" — Gemini does have GET /v1beta/models that returns the full available list with just an API key, and the same pattern works for OpenAI (GET /v1/models) and Anthropic (GET /v1/models). Wiring that into onboarding's "choose a model" prompt is the right answer but a separate concern from this 400 fix. Want me to open a follow-up PR for that?

On the docs

"what is the big deal: https://ai.google.dev/gemini-api/docs#rest"

Honest answer: the docs don't tell you additionalProperties is rejected. They say "only a subset of the OpenAPI schema is supported" with no exhaustive list and no concrete invalid example. You only find out which fields are unsupported by hitting the 400. So the discoverability is genuinely bad; the fix on the client side is mechanical once you know what the API rejects.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…5-flash

Two fixes in one PR — both visible the moment you point an LLM
loop at Gemini.

1. Schema sanitisation (the 400 the user hit)

   Gemini's function-calling API accepts only an OpenAPI 3.0 subset
   of JSON Schema. MCP servers and external skill manifests
   frequently emit `additionalProperties: false` on their tool
   parameter schemas (it's the JSON Schema "strict mode"
   convention); Anthropic and OpenAI ignore the field silently,
   Gemini 400s with:

     Unknown name "additionalProperties" at
     'tools[0].function_declarations[16].parameters.properties[2].value':
     Cannot find field

   New PasClaw.Providers.Gemini.SanitizeSchemaForGemini parses the
   schema, recursively strips the offending fields, and re-emits.
   Walks properties / items / anyOf / oneOf children so nested
   schemas get the same treatment. Stripped at the wire boundary
   only — Anthropic and OpenAI still see the original schemas
   unchanged.

   Fields stripped:
     additionalProperties   { the actual blocker }
     $schema, $id, $ref     { meta — Gemini doesn't model }
     definitions, $defs     { JSON Schema 2019-09+ }
     patternProperties      { not in OpenAPI 3.0 }
     unevaluatedProperties  { JSON Schema 2019-09+ }
     propertyNames          { JSON Schema 2019-09+ }

   On parse failure, SanitizeSchemaForGemini returns the input
   verbatim so a genuinely-malformed schema still surfaces Gemini's
   own 400 with the actual pointer, instead of getting silently
   dropped.

2. Default model bump

   Catalog default Gemini model: gemini-1.5-flash → gemini-3.5-flash.
   gemini-1.5-flash is the 18-months-stale free-tier default that
   ships with most catalog scaffolds; 3.5-flash is the current GA
   "real-world tasks at higher speed and lower cost" model with
   first-class function calling, structured outputs, and code
   execution. Operators who'd already picked their own model in
   config.json are unaffected — the catalog default only applies
   when Cfg.Providers[i].Model is empty.

3. Supporting JSON wrapper change

   PasClaw.JSON.TJsonObject.Remove(Key) — needed for the recursive
   walker; existed as an internal RemoveKey helper, now exposed.
   FPC and Delphi backends both implemented.

Verified:
  - make / make smoke clean (Linux+FPC)
  - SanitizeSchemaForGemini round-trip on the user's reported
    schema shape (additionalProperties at properties.X.value)
    confirms the field is removed and the rest of the schema is
    preserved

What's NOT in this PR:
  - Gemini model listing during onboarding (the user's second
    question). Gemini does have GET /v1beta/models that returns the
    full list with a key. Worth wiring into onboarding's "choose a
    model" prompt — separate concern, doesn't block the 400 fix.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 771815dbb9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ChildObj := Obj.ChildObject(Key);
if ChildObj <> nil then
try
StripUnsupportedSchemaFields(ChildObj);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve user parameters named like stripped keywords

When the walker recurses into the properties object, it treats that name-to-schema map as if it were a schema node and calls Obj.Remove('additionalProperties'), Obj.Remove('$ref'), etc. on it. For a tool schema with an actual argument named additionalProperties (or any of the other stripped names), the argument schema is deleted before being sent to Gemini, so the model no longer sees or validates that parameter even though the tool can require it. The sanitizer needs to distinguish schema-keyword objects from properties maps and only recurse into each property value there.

Useful? React with 👍 / 👎.

Codex P2: the original sanitiser's blind recursion treated the
JSON Schema \`properties\` map as a schema node, so a tool parameter
literally named "additionalProperties" (or any other stripped
keyword) would silently disappear from the wire body. Rare in
practice but legitimately broken — user-supplied property names
share a namespace with schema keywords.

Fix: rewrite the walker as schema-aware.

  StripUnsupportedSchemaFields strips keywords on the schema node
    it's called with, then recurses through specific schema-keyword
    fields that hold subschemas:
      properties       -> WalkPropertyMap  (name->subschema map)
      items            -> StripUnsupportedSchemaFields (single subschema)
                          or StripUnsupportedFromArray (tuple array)
      anyOf / oneOf / allOf
                       -> StripUnsupportedFromArray
      not              -> StripUnsupportedSchemaFields

  WalkPropertyMap iterates Map's values (each IS a schema, full
    strip pass) but never strips keywords on Map itself — Map's
    keys are user data.

  StripUnsupportedFromArray walks array entries, calling the strip
    pass on each (every element is a schema).

Effect:
  Schema node:  { additionalProperties: false, properties: {...} }
                -> additionalProperties STRIPPED (correct)

  Property map: { additionalProperties: { type: boolean } }
                (inside a parent's `properties` field)
                -> NOT stripped (correct — it's a user property name)

SanitizeSchemaForGemini exposed in the interface so the test
program can call it directly without going through BuildRequest.

New test: src/tests/gemini_schema_strip_tests.pas
  TestRejectedFieldsScrubbed
    - reproduces the original 400 shape (additionalProperties at
      two levels + $schema meta), asserts they're gone while real
      fields (url, options.timeout, required[]) survive.
  TestUserPropertyNamedAdditionalPropertiesSurvives
    - Codex P2 regression: a tool with properties named
      "additionalProperties", "\$schema", "\$ref" keeps all of them
      (proved via a sibling marker that only exists if the property
      schema was preserved), while the top-level schema keywords
      with those same names are stripped.
  TestEmptyAndMalformed
    - empty input round-trips empty; malformed JSON round-trips
      verbatim so Gemini's own 400 with field pointer surfaces
      instead of a silent drop.

  make test-gemini-schema-strip -> OK
  make smoke                    -> all 11 commands OK
@FMXExpress
FMXExpress merged commit 93bfac6 into main Jun 6, 2026
FMXExpress pushed a commit that referenced this pull request Jun 6, 2026
The 400 the user hit on gemini-3.5-flash after PR #153's schema scrub
landed:

  Function call is missing a thought_signature in functionCall parts.
  This is required for tools to work correctly, and missing
  thought_signature may lead to degraded model performance.
  Additional data, function call \`default_api:fs_list\`, position 2.

Gemini 3+ requires the client to echo back an opaque
\`thoughtSignature\` blob that the model returns on each functionCall
part. The signature encodes the model's internal reasoning state; if
we drop it, Gemini 3 rejects the next request with a 400. Gemini 2.x
doesn't require it. Ref:
  https://ai.google.dev/gemini-api/docs/thought-signatures

Wire shape (Gemini 3):

  // Assistant turn the model returned:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"
    }]
  }

  // Follow-up request must echo the signature verbatim:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"   <-- mandatory
    }]
  }

Implementation:

  TToolCall.ProviderSignature — new opaque string field on the
    shared TToolCall record (PasClaw.Providers.Types). Provider-
    specific blob; empty for everything except Gemini 3+. Survives
    history persistence through session save/load because it lives
    on the TToolCall the gateway already serialises.

  ParseResponse — reads the part-level \`thoughtSignature\` (sibling
    of functionCall, NOT inside it) and stashes it on the parsed
    TToolCall.

  BuildRequest — when emitting the assistant turn's part, if the
    TToolCall has a non-empty ProviderSignature, write it as a
    sibling of functionCall on the part. Empty signature stays
    silent — no empty "":"" field on the wire.

Tests added to gemini_schema_strip_tests:

  TestThoughtSignatureRoundTrip — assistant message carrying
    ProviderSignature = 'SIG_AAA_BBB_OPAQUE_BLOB' makes BuildRequest
    emit \`"thoughtSignature": "SIG_AAA_BBB_OPAQUE_BLOB"\` on the
    part, alongside the functionCall. Plus the function name and
    args survive.

  TestNoSignatureWhenEmpty — Gemini 2 path: empty ProviderSignature
    means no \`thoughtSignature\` key emitted at all. An empty
    string field would be invalid wire shape.

Verified:
  - make / make smoke clean
  - make test-gemini-schema-strip — all 5 tests OK
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
The 400 the user hit on gemini-3.5-flash after PR FMXExpress#153's schema scrub
landed:

  Function call is missing a thought_signature in functionCall parts.
  This is required for tools to work correctly, and missing
  thought_signature may lead to degraded model performance.
  Additional data, function call \`default_api:fs_list\`, position 2.

Gemini 3+ requires the client to echo back an opaque
\`thoughtSignature\` blob that the model returns on each functionCall
part. The signature encodes the model's internal reasoning state; if
we drop it, Gemini 3 rejects the next request with a 400. Gemini 2.x
doesn't require it. Ref:
  https://ai.google.dev/gemini-api/docs/thought-signatures

Wire shape (Gemini 3):

  // Assistant turn the model returned:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"
    }]
  }

  // Follow-up request must echo the signature verbatim:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"   <-- mandatory
    }]
  }

Implementation:

  TToolCall.ProviderSignature — new opaque string field on the
    shared TToolCall record (PasClaw.Providers.Types). Provider-
    specific blob; empty for everything except Gemini 3+. Survives
    history persistence through session save/load because it lives
    on the TToolCall the gateway already serialises.

  ParseResponse — reads the part-level \`thoughtSignature\` (sibling
    of functionCall, NOT inside it) and stashes it on the parsed
    TToolCall.

  BuildRequest — when emitting the assistant turn's part, if the
    TToolCall has a non-empty ProviderSignature, write it as a
    sibling of functionCall on the part. Empty signature stays
    silent — no empty "":"" field on the wire.

Tests added to gemini_schema_strip_tests:

  TestThoughtSignatureRoundTrip — assistant message carrying
    ProviderSignature = 'SIG_AAA_BBB_OPAQUE_BLOB' makes BuildRequest
    emit \`"thoughtSignature": "SIG_AAA_BBB_OPAQUE_BLOB"\` on the
    part, alongside the functionCall. Plus the function name and
    args survive.

  TestNoSignatureWhenEmpty — Gemini 2 path: empty ProviderSignature
    means no \`thoughtSignature\` key emitted at all. An empty
    string field would be invalid wire shape.

Verified:
  - make / make smoke clean
  - make test-gemini-schema-strip — all 5 tests OK
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.

2 participants