Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/google/adk/integrations/openai/_openai_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,12 @@ async def generate_content_async(
schema_name = "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.

schema_dict = schema.model_dump(
by_alias=True, exclude_none=True, mode="json"
)
lowercase_schema_types(schema_dict)
elif isinstance(schema, type) and issubclass(schema, BaseModel):
schema_dict = schema.model_json_schema()
schema_name = schema.__name__
elif isinstance(schema, BaseModel):
Expand Down
71 changes: 71 additions & 0 deletions tests/unittests/integrations/openai/test_openai_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1628,6 +1628,77 @@ async def test_response_schema_dict_becomes_json_schema_format():
assert "name" in response_format["json_schema"]["schema"]["properties"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
"response_schema, expected_schema",
[
(
types.Schema(
type=types.Type.OBJECT,
properties={
"tags": types.Schema(
type=types.Type.ARRAY,
items=types.Schema(type=types.Type.STRING),
),
},
),
{
"type": "object",
"properties": {
"tags": {"type": "array", "items": {"type": "string"}},
},
"additionalProperties": False,
"required": ["tags"],
},
),
(
types.Schema(
type=types.Type.OBJECT,
properties={
"name": types.Schema(type=types.Type.STRING),
"age": types.Schema(type=types.Type.INTEGER),
},
),
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"additionalProperties": False,
"required": ["age", "name"],
},
),
],
)
async def test_response_schema_genai_schema_becomes_json_schema_format(
response_schema, expected_schema
):
"""A types.Schema response_schema is sent as the user's own schema.

Previously the BaseModel branch caught the types.Schema instance and sent
the JSON schema of the types.Schema class itself.
"""
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hi")])],
config=types.GenerateContentConfig(response_schema=response_schema),
)

create_kwargs = await _capture_create_kwargs(openai_llm, llm_request)

assert create_kwargs["response_format"] == {
"type": "json_schema",
"json_schema": {
"name": "response",
"strict": True,
"schema": expected_schema,
},
}


@pytest.mark.asyncio
async def test_response_mime_type_json_becomes_json_object_format():
"""response_mime_type application/json maps to a json_object format."""
Expand Down