Skip to content

fix(openai): send the user's types.Schema output_schema to Chat Completions - #8006

Open
Yasser-Ameur wants to merge 4 commits into
google:mainfrom
Yasser-Ameur:fix/openai-types-schema-output
Open

Yasser-Ameur wants to merge 4 commits into
google:mainfrom
Yasser-Ameur:fix/openai-types-schema-output

Conversation

@Yasser-Ameur

Copy link
Copy Markdown
Contributor

Please ensure you have read the contribution guide before creating a pull request.

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

  • Closes: none, no issue exists
  • Related: none

2. Or, if no issue exists, describe the change:

Problem:

  • Expected: an output_schema given as types.Schema reaches Chat Completions as that schema, in strict mode, like it does on OpenAIResponsesLlm and LiteLlm.
  • Actual: OpenAILlm sends the JSON schema of the types.Schema class itself (its 7 KB meta schema), named Schema. After the strict pass the request carries {"$ref": "#/$defs/Schema"}, so the user's schema is never enforced.
  • Cause: the response_format builder in integrations/openai/_openai_llm.py tests isinstance(schema, BaseModel) before any types.Schema check. types.Schema is a pydantic model, so it takes that branch and schema.__class__.model_json_schema() describes the class, not the value.
  • Reproduction: OpenAILlm with a mocked chat.completions.create capturing kwargs, response_schema=types.Schema(type=ARRAY, items=Schema(type=STRING)); inspect response_format.
  • Version: origin/main 946ca77, Python 3.14.7.

Solution: check for a types.Schema instance first and convert it with model_dump(by_alias=True, exclude_none=True, mode="json") plus lowercase_schema_types, the same conversion OpenAIResponsesLlm._schema_to_dict and LiteLlm use, then run the existing strict pass. The BaseModel and dict paths are unchanged.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change: test_response_schema_genai_schema_becomes_json_schema_format in test_openai_llm.py, parametrized over an array schema and an object schema; both cases fail on main.
  • All unit tests pass locally.

pytest tests/unittests/integrations/openai: 293 passed.

Manual End-to-End (E2E) Tests:

No live OpenAI call was made. A script with a mocked client was run on main and on this branch, capturing the sent response_format.
Before: name: Schema, schema: {"$ref": "#/$defs/Schema"}.
After: name: response, schema: {"items": {"type": "string"}, "type": "array"}.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end. (mocked client only, see above)
  • Any dependent changes have been merged and published in downstream modules.

Additional context

A list[...] output_schema still sends no response_format on this path; that is a separate gap, and LiteLlm has the same one.

…etions

OpenAILlm checked isinstance(schema, BaseModel) before anything else, and
types.Schema is a pydantic model, so a types.Schema response_schema was
turned into schema.__class__.model_json_schema(): the JSON schema of the
Schema class itself. After the strict pass the request carried
{"$ref": "#/$defs/Schema"} under the name "Schema" and the user's schema
was never enforced.

Convert a types.Schema with model_dump and lowercase its types before the
BaseModel branch, as OpenAIResponsesLlm._schema_to_dict and LiteLlm
already do.

@BlueRaddish BlueRaddish 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.

The new array-schema case still cannot be used as a strict Structured Output on the default OpenAI Chat Completions endpoint. It now sends the user's array instead of the types.Schema meta-schema, but the resulting root schema is {"type": "array", "items": {"type": "string"}} with strict: true. The official Structured Outputs contract requires an object root; arrays are supported as nested properties. A types.Schema(type=STRING) has the same remaining issue.

At head b51b5f3cef40ee0cb0021e9f31b29bb726467b16, I captured the actual OpenAI SDK's serialized request to https://api.openai.com/v1/chat/completions through a no-network httpx.MockTransport. The array input produces:

{"type":"json_schema","json_schema":{"name":"response","strict":true,"schema":{"items":{"type":"string"},"type":"array"}}}

Could this branch reject unsupported root shapes locally for the default OpenAI backend, or provide an explicit object-wrapper adaptation with matching response handling? The regression should distinguish a supported object containing an array from an unsupported top-level array, rather than treating a captured raw-array payload as a successful strict-mode request. An explicit OpenAI-compatible backend may have a different contract, so this need not impose the OpenAI restriction on every custom base_url.

I checked the exact complete base/head generate_content_async methods and schema helpers, with the unchanged _openai_common module, real supported google-genai==2.32.0, openai==2.33.0, and actual SDK serialization. Four object-root controls (including a nested array, BaseModel, and dict schema) produced object roots; a custom-host array control was kept separate. The PR base 946ca77224d5b3e1bf7c5a1dd0a39e9b17c3e655 already sends the wrong meta-schema, so this is an incomplete-fix/provider-contract finding, not a newly introduced working-to-failing regression.

Scope: model/request holders isolate unrelated ADK initialization, and response conversion is an identity boundary after real SDK parsing. No full ADK/Runner/owning suite or live provider/server request was run; remote rejection is inferred from the documented schema contract, not claimed as a measured API response.

schema_dict = {}

if isinstance(schema, type) and issubclass(schema, BaseModel):
if isinstance(schema, types.Schema):

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.

one more gap on the way to parity with OpenAIResponsesLlm: that model reads config.response_schema or config.response_json_schema, but this path only checks response_schema, so GenerateContentConfig(response_json_schema={...}) sends no response_format at all on Chat Completions. and a dict title like "Weather Report" goes out as the json_schema name unsanitized, which OpenAI rejects (^[a-zA-Z0-9_-]+$), while Responses already sanitizes it:

@@ -430,8 +431,14 @@ class OpenAILlm(BaseLlm):
     response_format = None
-    if llm_request.config and llm_request.config.response_schema:
-      schema = llm_request.config.response_schema
+    if llm_request.config and (
+        llm_request.config.response_schema
+        or llm_request.config.response_json_schema
+    ):
+      schema = (
+          llm_request.config.response_schema
+          or llm_request.config.response_json_schema
+      )
       schema_name = "response"
@@ -449,7 +456,11 @@ class OpenAILlm(BaseLlm):
         if "title" in schema_dict:
-          schema_name = str(schema_dict["title"])
+          # OpenAI requires the json_schema name to match ^[a-zA-Z0-9_-]+$.
+          schema_name = (
+              re.sub(r"[^a-zA-Z0-9_-]", "_", str(schema_dict["title"]))
+              or "response"
+          )

pushed the fix plus a test (and the re import) here, should cherry pick clean on your branch: its-amann@35faaa5

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both are real gaps: response_json_schema is not read on this path, and a dict title is sent as the schema name without sanitizing. I kept them out of this PR so it stays on the types.Schema fix, and they fit a follow-up once this one is in.

@Yasser-Ameur

Copy link
Copy Markdown
Contributor Author

@BlueRaddish you are right about the array root. The test now uses a types.Schema object with an array property (4749a16), so it checks a root that strict mode accepts. A top-level array is refused by OpenAI on the dict branch and in the Responses wrapper as well, and that was the case before this PR, so I left rejecting or wrapping it to the maintainers.

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.

4 participants