From 1517ef2e70348d3d85bb0b67a1e308c7e9fc7969 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 24 Nov 2026 14:43:22 +0000 Subject: [PATCH 1/3] fix(py/openai): wrap non-object output schemas for OpenAI and unwrap the reply --- packages/genkit-openai/README.md | 7 + .../src/genkit_openai/_models/_handler.py | 2 +- .../src/genkit_openai/_models/_model.py | 89 +++- .../src/genkit_openai/_models/_output_root.py | 186 ++++++++ .../src/genkit_openai/_openai_plugin.py | 8 +- .../genkit-openai/tests/output_root_test.py | 416 ++++++++++++++++++ .../genkit-openai/tests/tool_calling_test.py | 10 +- 7 files changed, 699 insertions(+), 19 deletions(-) create mode 100644 packages/genkit-openai/src/genkit_openai/_models/_output_root.py create mode 100644 packages/genkit-openai/tests/output_root_test.py diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index d8793358..920eee11 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -85,6 +85,13 @@ alias. On `gpt-image-2` and older GPT Image models they fail before the request is sent. To send one anyway, pass it as `extra={'quality': 'xhigh'}`. +## Structured output + +OpenAI only accepts an object at the root of an output schema, so `OpenAI()` +sends any other schema (a list, enum or scalar, such as `output_schema=list[str]` +or a `str` Enum) as the `value` property of an object and unwraps the reply. +`response.output` and the streamed chunks hold the value itself. + ## Mistral `Mistral()` registers Mistral's models and embedders under `mistral/`, as the diff --git a/packages/genkit-openai/src/genkit_openai/_models/_handler.py b/packages/genkit-openai/src/genkit_openai/_models/_handler.py index d91e5a95..42af461e 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_handler.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_handler.py @@ -66,7 +66,7 @@ def get_model_handler( raise ValueError(f"Model '{model}' is not supported.") info = _SUPPORTED_MODELS[model] - openai_model = OpenAIModel(model, client, supports=info.supports) + openai_model = OpenAIModel(model, client, supports=info.supports, object_schema_root=True) return cls(openai_model).generate async def generate(self, request: ModelRequest, ctx: ModelContext) -> ModelResponse: diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index 10a51c1b..d6cb3ea8 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -21,6 +21,12 @@ from typing import Any, cast from genkit_openai._models._mistral import is_mistral, mistral_chat_body, refuse_non_image_media +from genkit_openai._models._output_root import ( + OUTPUT_VALUE_FIELD, + OutputStreamUnwrapper, + has_object_root, + unwrap_output_text, +) from genkit_openai._models._utils import ( OPENAI_CALL_ERRORS, DictMessageAdapter, @@ -269,9 +275,12 @@ def _root_ref_target(schema: dict[str, Any]) -> dict[str, Any] | None: return None -def _is_wrapped_tool_schema(schema: dict[str, Any] | None) -> bool: +def _is_non_object_schema(schema: dict[str, Any] | None) -> bool: """True for a non-empty schema that is not an object (``{'type': 'string'}``). + OpenAI takes only an object for a function's parameters and for a + ``json_schema`` response format, so such a schema is sent wrapped. + A root ``$ref`` is judged by its target: Pydantic emits one for an Enum input, which is a string, not an object. """ @@ -282,26 +291,26 @@ def _is_wrapped_tool_schema(schema: dict[str, Any] | None) -> bool: if '$ref' in schema: target = _root_ref_target(schema) # An unresolvable ref is sent as is rather than guessed at. - return target is not None and _is_wrapped_tool_schema(target) + return target is not None and _is_non_object_schema(target) # anyOf/oneOf roots: only an object schema is safe to send as-is. return 'properties' not in schema return schema_type != 'object' -def _wrap_tool_schema(schema: dict[str, Any]) -> dict[str, Any]: - """``schema`` under one ``input`` property, with any ``$defs`` kept at the root.""" +def _wrap_schema(schema: dict[str, Any], field: str) -> dict[str, Any]: + """``schema`` under the one property ``field``, with any ``$defs`` kept at the root.""" defs = {k: schema[k] for k in _DEFS_KEYS if k in schema} inner = {k: v for k, v in schema.items() if k not in defs} return { 'type': 'object', - 'properties': {_TOOL_INPUT_FIELD: inner}, - 'required': [_TOOL_INPUT_FIELD], + 'properties': {field: inner}, + 'required': [field], **defs, } def _wrapped_tool_names(tools: list[ToolDefinition] | None) -> frozenset[str]: - return frozenset(t.name for t in tools or [] if _is_wrapped_tool_schema(t.input_schema)) + return frozenset(t.name for t in tools or [] if _is_non_object_schema(t.input_schema)) def _map_tool_requests(message: Message, wrapped: frozenset[str], wrap: bool) -> Message: @@ -341,6 +350,24 @@ def _unwrapped_args_text(arguments: str) -> str: return arguments +def _unwrap_output(message: Message) -> Message: + """Replace a wrapped reply's text with the wrapped value. + + Text beside a tool call is a preamble, not the output, and is left alone. + """ + if any(part.tool_request is not None for part in message.content): + return message + changed = False + content: list[Part] = [] + for part in message.content: + if part.text is not None and (text := unwrap_output_text(part.text)) != part.text: + content.append(part.model_copy(update={'text': text})) + changed = True + else: + content.append(part) + return message.model_copy(update={'content': content}) if changed else message + + def _wrap_tool_inputs(messages: list[Message], wrapped: frozenset[str]) -> list[Message]: """Replay earlier calls to scalar-input tools in the wrapped wire shape.""" return [_map_tool_requests(m, wrapped, wrap=True) for m in messages] @@ -361,6 +388,7 @@ def __init__( *, supports: ModelSupports | None = None, mistral: bool | None = None, + object_schema_root: bool = False, ) -> None: """Initializes the OpenAIModel instance with the specified model and OpenAI client parameters. @@ -373,11 +401,16 @@ def __init__( ``json_object`` so a fine-tune keeps working. mistral: Send Mistral's field names (see ``_mistral.py``). ``None`` decides from the client's host. + object_schema_root: The host takes a ``json_schema`` response + format only with an object root (OpenAI). Any other output + schema is sent as the ``value`` property of an object, and + the reply is unwrapped. """ self._model = model self._openai_client = client self._supports = supports self._mistral = is_mistral(client) if mistral is None else mistral + self._object_schema_root = object_schema_root @property def name(self) -> str: @@ -423,10 +456,10 @@ async def _get_tools_definition(self, tools: list[ToolDefinition]) -> list[dict] result = [] for tool_definition in tools: parameters = tool_definition.input_schema or {} - if _is_wrapped_tool_schema(parameters): + if _is_non_object_schema(parameters): # Function parameters must be an object; a scalar tool input # (``async def tool(city: str)``) rides under one field. - parameters = _wrap_tool_schema(parameters) + parameters = _wrap_schema(parameters, _TOOL_INPUT_FIELD) if parameters: parameters = _ensure_strict_json_schema(parameters, path=(), root=parameters) @@ -461,6 +494,16 @@ def _needs_schema_in_prompt(self, request: ModelRequest) -> bool: # DeepSeek models use json_object mode — schema never reaches the API. return self._model.startswith('deepseek') + def _wraps_output(self, request: ModelRequest) -> bool: + """Whether the output schema goes out wrapped, so the reply must be unwrapped.""" + return ( + self._object_schema_root + and request.output_format == 'json' + and not self._model.startswith('deepseek') + and bool(request.output_schema) + and not has_object_root(request.output_schema) + ) + def _get_response_format(self, request: ModelRequest) -> dict | None: """Determines the response format configuration based on the output settings. @@ -481,13 +524,14 @@ def _get_response_format(self, request: ModelRequest) -> dict | None: if self._model.startswith('deepseek'): return {'type': 'json_object'} if request.output_schema: + schema = request.output_schema + if self._wraps_output(request): + schema = _wrap_schema(schema, OUTPUT_VALUE_FIELD) return { 'type': 'json_schema', 'json_schema': { 'name': request.output_schema.get('title', 'Response'), - 'schema': _ensure_strict_json_schema( - request.output_schema, path=(), root=request.output_schema - ), + 'schema': _ensure_strict_json_schema(schema, path=(), root=schema), 'strict': True, }, } @@ -650,6 +694,8 @@ async def _generate(self, request: ModelRequest) -> ModelResponse: ) genkit_message = _unwrap_tool_inputs(MessageConverter.to_genkit(message), _wrapped_tool_names(request.tools)) + if self._wraps_output(request): + genkit_message = _unwrap_output(genkit_message) # An empty message is the answer when the model was blocked or cut off; at a clean stop it is unreadable. if not genkit_message.content and finish_reason is FinishReason.STOP: raise ValueError('Unable to determine content part') @@ -694,6 +740,9 @@ async def _generate_stream( tool_calls: dict[int, Any] = {} wrapped = _wrapped_tool_names(request.tools) + # A wrapped reply streams as '{"value": ...}'; text is unwrapped as it + # arrives, so chunks and the final message read as the caller's value. + unwrapper = OutputStreamUnwrapper() if self._wraps_output(request) else None # As a full reply is read (MessageConverter.to_genkit): reasoning from # its own field (DeepSeek's reasoning_content) first, then the # content's reasoning and text in the order they arrived (Mistral's @@ -735,8 +784,19 @@ async def _generate_stream( field_reasoning.append(reasoning_part) parts.append(reasoning_part) + # Text before a tool call is a preamble, not the output: whatever + # was held back goes out as it streamed, and so does the rest. + if unwrapper is not None and delta.tool_calls and (held_text := unwrapper.pass_through()): + held_part = MessageConverter.text_part_to_genkit(held_text) + content_parts.append(held_part) + parts.append(held_part) + # Text content; Mistral's reasoning models stream reasoning in it too. for item in reply_content(delta.content): + if isinstance(item, str) and unwrapper is not None: + item = unwrapper.push(item) + if not item: + continue part = MessageConverter.text_part_to_genkit(item) if isinstance(item, str) else item content_parts.append(part) parts.append(part) @@ -761,6 +821,11 @@ async def _generate_stream( if parts: callback(ModelResponseChunk(role=Role.MODEL, content=parts)) + if unwrapper is not None and (rest := unwrapper.flush()): + rest_part = MessageConverter.text_part_to_genkit(rest) + content_parts.append(rest_part) + callback(ModelResponseChunk(role=Role.MODEL, content=[rest_part])) + if not saw_choice: raise GenkitError( status='INTERNAL', diff --git a/packages/genkit-openai/src/genkit_openai/_models/_output_root.py b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py new file mode 100644 index 00000000..c3690c15 --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py @@ -0,0 +1,186 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Unwrapping replies to an output schema that was sent wrapped in an object. + +OpenAI only accepts a ``json_schema`` response format whose root is +``type: "object"``. A schema with any other root (a list, enum or scalar) is +sent as the ``value`` property of an object, and the reply, which arrives as +``{"value": ...}``, is turned back into the caller's value here. +""" + +import json +import re +from typing import Any, cast + +# The property that holds the caller's value inside the wrapper object. +OUTPUT_VALUE_FIELD = 'value' + +# The wrapper's opening, as the tokens it is made of. Whitespace may sit +# before and between them. +_PREFIX_TOKENS = ('{', f'"{OUTPUT_VALUE_FIELD}"', ':') +_TRAILING = ' \t\r\n}' + +# Keywords a bare ``$ref`` may sit beside: at the root, and in a definition. +_ROOT_REF_KEYS = frozenset({'$ref', '$schema', '$defs', 'definitions'}) +_REF_KEYS = frozenset({'$ref'}) +_DEF_REF = re.compile(r'#/(\$defs|definitions)/([^/~]+)') + + +def has_object_root(schema: dict[str, Any]) -> bool: + """Whether the schema's root is explicitly an object. + + Either directly, or through a bare root ``$ref`` to a top-level definition + (as Pydantic emits for a recursive model), which OpenAI accepts unwrapped. + Anything else, including ``properties`` without a ``type`` (which also + allows non-object values), is wrapped. + + OpenAI rejects a ``$ref`` with sibling keywords (``description``, + ``title``, ...) and does not resolve escaped names (``~0``, ``~1``) at the + root, while non-strict requests accept both once wrapped, so those roots + are wrapped. + """ + seen: set[str] = set() + node: object = schema + allowed = _ROOT_REF_KEYS + while isinstance(node, dict): + node = cast(dict[str, Any], node) + if 'type' in node: + return node['type'] == 'object' + ref = node.get('$ref') + if not isinstance(ref, str) or ref in seen or not set(node) <= allowed: + return False + seen.add(ref) + match = _DEF_REF.fullmatch(ref) + if match is None: + return False + defs = schema.get(match[1]) + node = cast(dict[str, Any], defs).get(match[2]) if isinstance(defs, dict) else None + allowed = _REF_KEYS + return False + + +def unwrap_output_text(text: str) -> str: + """JSON text of the wrapped value in ``text``, or ``text`` unchanged. + + The value's text is kept as sent, so it reads the same as when streamed. + Text that is not exactly ``{"value": ...}`` is returned as is: a host that + ignored the schema may reply with the bare value. + """ + try: + parsed = json.loads(text) + except ValueError: + return text + if not isinstance(parsed, dict) or set(cast(dict[str, Any], parsed)) != {OUTPUT_VALUE_FIELD}: + return text + # The shape is known, so stripping the opening and closing brace leaves + # exactly the value. + unwrapper = OutputStreamUnwrapper() + return unwrapper.push(text) + unwrapper.flush() + + +def _match_prefix(text: str) -> int | None: + """Match the start of ``text`` against the wrapper's opening. + + Returns the opening's length when it is all there, 0 when ``text`` could + still become it, and None when it cannot. + """ + i = 0 + for token in _PREFIX_TOKENS: + while i < len(text) and text[i].isspace(): + i += 1 + rest = text[i : i + len(token)] + if rest != token: + return 0 if token.startswith(rest) and i + len(rest) == len(text) else None + i += len(token) + return i + + +class OutputStreamUnwrapper: + """Strips the ``{"value":`` opening and the closing ``}`` from streamed text. + + Chunks then read as the caller's value (``[{...},`` for a list), which is + what the output format's chunk parser expects. + + Text is held back for as long as it could still be the start of the + wrapper, so the result does not depend on how the stream is split. + Trailing whitespace and braces are then held until more text arrives, + because the last ``}`` belongs to the wrapper only if nothing follows it; + ``flush`` drops it. A reply that is not a wrapper passes through unchanged. + """ + + def __init__(self) -> None: + """Start before any text has arrived.""" + self._started = False + self._wrapped = False + self._value_started = False + self._passing = False + self._head = '' + self._held = '' + + def push(self, delta: str) -> str: + """Take a streamed delta and return the text to emit for it, possibly empty.""" + if self._passing: + return delta + if self._started: + return self._release(delta) + self._head += delta + match = _match_prefix(self._head) + if match == 0: + return '' + self._started = True + out, self._head = self._head, '' + if match is not None: + self._wrapped = True + out = out[match:] + return self._release(out) + + def _release(self, text: str) -> str: + text = self._held + text + # Whitespace after the colon belongs to the wrapper too, however much + # of it arrives after the opening matched. + if self._wrapped and not self._value_started: + text = text.lstrip() + self._value_started = bool(text) + kept = text.rstrip(_TRAILING) + self._held = text[len(kept) :] + return kept + + def pass_through(self) -> str: + """Stop unwrapping and return the text held back so far. + + For a reply that turns out not to be the output: text before a tool + call is a preamble. + """ + out = self._head + self._held + self._started = self._passing = True + self._head = self._held = '' + return out + + def flush(self) -> str: + """Return what is left at the end of the stream, minus the wrapper's closing brace.""" + if self._passing: + return '' + if not self._started: + out, self._head = self._head, '' + return out + text, self._held = self._held, '' + if not self._wrapped: + return text + brace = text.rfind('}') + if brace >= 0: + text = text[:brace] + return text.rstrip() diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 141010d6..a9682a7c 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -673,7 +673,13 @@ def _create_model_action(self, name: str) -> Action: async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> ModelResponse: client = self._client_for_call(request, ctx) openai_model = OpenAIModelHandler( - OpenAIModel(name, client, supports=info.supports, mistral=self._uses_mistral_names(client)) + OpenAIModel( + name, + client, + supports=info.supports, + mistral=self._uses_mistral_names(client), + object_schema_root=True, + ) ) return await openai_model.generate(request, ctx) diff --git a/packages/genkit-openai/tests/output_root_test.py b/packages/genkit-openai/tests/output_root_test.py new file mode 100644 index 00000000..141a8e88 --- /dev/null +++ b/packages/genkit-openai/tests/output_root_test.py @@ -0,0 +1,416 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for wrapping non-object output schemas for OpenAI and unwrapping the reply.""" + +import json +from enum import Enum +from typing import Any +from unittest.mock import MagicMock + +import httpx +import pytest +from genkit_openai import OpenAI +from genkit_openai._models._model import OpenAIModel, _unwrap_output +from genkit_openai._models._output_root import OutputStreamUnwrapper, has_object_root, unwrap_output_text + +from genkit import Genkit, Message, Part, Role +from genkit.model import ModelRequest, OutputConfig, ToolRequest + +ARRAY_SCHEMA: dict[str, Any] = { + 'type': 'array', + 'items': {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']}, +} + + +class Color(str, Enum): + """A colour, which Pydantic emits as a string enum schema.""" + + RED = 'red' + BLUE = 'blue' + + +def _run(deltas: list[str]) -> str: + unwrapper = OutputStreamUnwrapper() + return ''.join(unwrapper.push(d) for d in deltas) + unwrapper.flush() + + +def _json_request(schema: dict[str, Any]) -> ModelRequest: + return ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('Hi')])], + output=OutputConfig(format='json', json_schema=schema), + ) + + +def _sent_schema(model: OpenAIModel, request: ModelRequest) -> dict[str, Any]: + response_format = model._get_response_format(request) + assert response_format is not None + return response_format['json_schema']['schema'] + + +# Unwrapping text + + +@pytest.mark.parametrize( + ('text', 'expected'), + [ + ('{"value":[{"name":"a"}]}', '[{"name":"a"}]'), + ('{"value":42}', '42'), + ('{"value":"red"}', '"red"'), + ('{"value":0}', '0'), + ('{"value":false}', 'false'), + ('{"value":""}', '""'), + ('{"value":null}', 'null'), + ('{ "value" : [1, 2] }\n', '[1, 2]'), + ('{"value":{"a":"}"}}', '{"a":"}"}'), + ], +) +def test_unwrap_output_text_returns_the_value_as_sent(text: str, expected: str) -> None: + """The wrapped value comes back as the text it was sent as, falsy values included.""" + assert unwrap_output_text(text) == expected + + +@pytest.mark.parametrize('text', ['[1,2]', '{"other":1}', '{"value":1,"extra":2}', 'not json', '']) +def test_unwrap_output_text_passes_through_anything_else(text: str) -> None: + """Only exactly {"value": ...} is unwrapped; a bare value from a host that ignored the schema is kept.""" + assert unwrap_output_text(text) == text + + +def test_unwrap_output_keeps_reasoning_and_leaves_a_tool_call_preamble_alone() -> None: + """Text is unwrapped and other parts kept, unless the reply calls a tool.""" + answer = _unwrap_output( + Message(role=Role.MODEL, content=[Part.from_reasoning('thinking'), Part.from_text('{"value":[1]}')]) + ) + assert [p.reasoning for p in answer.content] == ['thinking', None] + assert answer.content[1].text == '[1]' + + preamble = Message( + role=Role.MODEL, + content=[Part.from_text('{"value":1}'), Part(tool_request=ToolRequest(name='lookup', input={}))], + ) + assert _unwrap_output(preamble) is preamble + + +# Streaming + + +FULL = '{"value":[{"name":"a"},{"name":"b"}]}' + + +def test_stream_unwrapper_gives_the_same_result_however_the_stream_is_split() -> None: + """Every two-way split, and one character at a time, yield the bare value.""" + assert _run([FULL]) == '[{"name":"a"},{"name":"b"}]' + assert _run(list(FULL)) == '[{"name":"a"},{"name":"b"}]' + for i in range(1, len(FULL)): + assert _run([FULL[:i], FULL[i:]]) == '[{"name":"a"},{"name":"b"}]', f'split at {i}' + + +def test_stream_unwrapper_handles_a_spaced_opening_split_anywhere() -> None: + """Whitespace around the opening's tokens is dropped wherever the stream splits.""" + spaced = '{ "value" : [1, 2] }\n' + for i in range(1, len(spaced)): + assert _run([spaced[:i], spaced[i:]]) == '[1, 2]', f'split at {i}' + assert _run(list(spaced)) == '[1, 2]' + + +def test_stream_unwrapper_never_emits_the_closing_brace_early() -> None: + """A trailing brace is held until it is known to belong to the value.""" + unwrapper = OutputStreamUnwrapper() + assert unwrapper.push('{"value":{"a":1}') == '{"a":1' + assert unwrapper.push('}') == '' + assert unwrapper.flush() == '}' + + +@pytest.mark.parametrize('text', ['[1,2]', '{"valuable":1}', '{"other":1}', '42']) +def test_stream_unwrapper_passes_through_output_that_is_not_a_wrapper(text: str) -> None: + """A reply that never matches the opening streams unchanged.""" + assert _run(list(text)) == text + + +def test_stream_unwrapper_pass_through_returns_held_text_and_stops_unwrapping() -> None: + """Once a tool call arrives, held text is released and the rest streams as is.""" + unwrapper = OutputStreamUnwrapper() + assert unwrapper.push('{"val') == '' + assert unwrapper.pass_through() == '{"val' + assert unwrapper.push('ue":1}') == 'ue":1}' + assert unwrapper.flush() == '' + + +# The response format + + +def test_response_format_wraps_a_non_object_root_for_an_object_only_host() -> None: + """The schema goes out under a required value property, closed for strict mode.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + schema = _sent_schema(model, _json_request(ARRAY_SCHEMA)) + assert schema['type'] == 'object' + assert schema['required'] == ['value'] + assert schema['additionalProperties'] is False + assert schema['properties']['value']['type'] == 'array' + assert schema['properties']['value']['items']['additionalProperties'] is False + + +def test_response_format_keeps_defs_at_the_wrapper_root() -> None: + """References into $defs still resolve once the schema is wrapped.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + node = { + 'type': 'object', + 'properties': {'children': {'type': 'array', 'items': {'$ref': '#/$defs/Node'}}}, + 'required': ['children'], + } + schema = _sent_schema( + model, _json_request({'type': 'array', 'items': {'$ref': '#/$defs/Node'}, '$defs': {'Node': node}}) + ) + assert schema['properties']['value'] == {'type': 'array', 'items': {'$ref': '#/$defs/Node'}} + assert schema['$defs']['Node']['properties']['children']['items'] == {'$ref': '#/$defs/Node'} + + +@pytest.mark.parametrize( + 'schema', + [ + {'type': 'object', 'properties': {'a': {'type': 'string'}}, 'required': ['a']}, + # A root $ref to an object, as Pydantic emits for a recursive model. + {'$ref': '#/$defs/Node', '$defs': {'Node': {'type': 'object', 'properties': {}}}}, + ], +) +def test_response_format_sends_an_object_root_unwrapped(schema: dict[str, Any]) -> None: + """An object root, directly or through a root $ref, is not wrapped.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + request = _json_request(schema) + assert not model._wraps_output(request) + assert 'value' not in _sent_schema(model, request).get('properties', {}) + + +_OBJ: dict[str, Any] = {'type': 'object'} + + +@pytest.mark.parametrize( + ('schema', 'expected'), + [ + ({'type': 'object', 'properties': {}}, True), + ({'properties': {'a': {'type': 'string'}}}, False), + (ARRAY_SCHEMA, False), + ({'type': 'string', 'enum': ['a', 'b']}, False), + ({'anyOf': [_OBJ, {'type': 'string'}]}, False), + ({'type': ['object', 'null']}, False), + ({'$ref': '#/definitions/Foo', 'definitions': {'Foo': _OBJ}}, True), + ({'$ref': '#/$defs/Foo', '$defs': {'Foo': _OBJ}}, True), + ({'$schema': 'http://json-schema.org/draft-07/schema#', '$ref': '#/$defs/Foo', '$defs': {'Foo': _OBJ}}, True), + ({'$ref': '#/$defs/A', '$defs': {'A': {'$ref': '#/$defs/B'}, 'B': _OBJ}}, True), + # OpenAI does not resolve escaped names or allow keywords beside $ref. + ({'$ref': '#/$defs/a~1b', '$defs': {'a/b': _OBJ}}, False), + ({'$ref': '#/$defs/Foo', 'description': 'd', '$defs': {'Foo': _OBJ}}, False), + ({'$ref': '#/$defs/A', '$defs': {'A': {'$ref': '#/$defs/B', 'title': 'A'}, 'B': _OBJ}}, False), + ({'$ref': '#/$defs/Foo', '$defs': {'Foo': {'type': 'array'}}}, False), + ({'$ref': '#/$defs/Missing', '$defs': {}}, False), + ({'$ref': '#/$defs/A', '$defs': {'A': {'$ref': '#/$defs/A'}}}, False), + ({'$ref': '#/$defs/Foo/properties/a', '$defs': {'Foo': _OBJ}}, False), + ], +) +def test_has_object_root(schema: dict[str, Any], expected: bool) -> None: + """Only an object, directly or through bare root refs to definitions, counts.""" + assert has_object_root(schema) is expected + + +def test_response_format_wraps_a_root_ref_with_sibling_keywords() -> None: + """OpenAI rejects keywords beside a root $ref, so such a root is wrapped.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + schema = {'$ref': '#/$defs/Foo', 'description': 'A person', '$defs': {'Foo': {'type': 'object', 'properties': {}}}} + request = _json_request(schema) + assert model._wraps_output(request) + # The SDK's strict pass inlines a $ref that has siblings. + value = _sent_schema(model, request)['properties']['value'] + assert value['type'] == 'object' + assert value['description'] == 'A person' + + +def test_response_format_wraps_a_root_ref_to_an_enum() -> None: + """A root $ref is judged by its target, so an enum behind one is wrapped.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + schema = {'$ref': '#/$defs/Color', '$defs': {'Color': {'type': 'string', 'enum': ['red', 'blue']}}} + sent = _sent_schema(model, _json_request(schema)) + assert sent['properties']['value'] == {'$ref': '#/$defs/Color'} + assert sent['$defs'] == schema['$defs'] + + +def test_response_format_is_unchanged_without_the_setting() -> None: + """Other users of OpenAIModel (Model Garden) send the schema as before.""" + model = OpenAIModel(model='meta/llama', client=MagicMock()) + request = _json_request(ARRAY_SCHEMA) + assert not model._wraps_output(request) + assert _sent_schema(model, request)['type'] == 'array' + + +def test_deepseek_is_not_wrapped() -> None: + """DeepSeek takes json_object with the schema in the prompt, so there is nothing to wrap.""" + model = OpenAIModel(model='deepseek-chat', client=MagicMock(), object_schema_root=True) + request = _json_request(ARRAY_SCHEMA) + assert not model._wraps_output(request) + assert model._get_response_format(request) == {'type': 'json_object'} + + +# Through the plugin + + +def _completion(content: str) -> dict[str, Any]: + return { + 'id': 'chatcmpl-1', + 'object': 'chat.completion', + 'created': 0, + 'model': 'gpt-4o', + 'choices': [{'index': 0, 'finish_reason': 'stop', 'message': {'role': 'assistant', 'content': content}}], + 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}, + } + + +def _delta(delta: dict[str, Any], finish_reason: str | None = None) -> str: + return json.dumps({ + 'id': 'chatcmpl-1', + 'object': 'chat.completion.chunk', + 'created': 0, + 'model': 'gpt-4o', + 'choices': [{'index': 0, 'delta': delta, 'finish_reason': finish_reason}], + }) + + +class _Server: + """A fake OpenAI endpoint that answers every request the same way and records each body.""" + + def __init__(self, content: str = '', frames: list[str] | None = None) -> None: + self._content = content + self._frames = frames + self.bodies: list[dict[str, Any]] = [] + + def handler(self, request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + self.bodies.append(body) + if body.get('stream'): + frames = self._frames or [_delta({'content': self._content}, 'stop')] + sse = ''.join(f'data: {f}\n\n' for f in frames) + 'data: [DONE]\n\n' + return httpx.Response(200, text=sse, headers={'content-type': 'text/event-stream'}) + return httpx.Response(200, json=_completion(self._content)) + + def sent_schema(self) -> dict[str, Any]: + return self.bodies[-1]['response_format']['json_schema']['schema'] + + +def _genkit(server: _Server, **options: Any) -> Genkit: # noqa: ANN401 + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return Genkit( + plugins=[OpenAI(api_key='sk-test', client_options={'http_client': http_client, 'max_retries': 0, **options})] + ) + + +@pytest.mark.asyncio +async def test_plugin_sends_a_wrapped_list_and_returns_the_bare_value() -> None: + """A list schema goes out wrapped and the caller gets the list, with its text as sent.""" + server = _Server('{"value":[{"name":"a"},{"name":"b"}]}') + response = await _genkit(server).generate(model='openai/gpt-4o', prompt='Two people.', output_schema=ARRAY_SCHEMA) + + assert server.sent_schema()['required'] == ['value'] + assert response.text == '[{"name":"a"},{"name":"b"}]' + assert response.output == [{'name': 'a'}, {'name': 'b'}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(('schema', 'reply', 'expected'), [(int, '{"value":0}', 0), (bool, '{"value":false}', False)]) +async def test_plugin_returns_a_falsy_scalar(schema: type, reply: str, expected: object) -> None: + """0 and false come back as values, not as missing output.""" + response = await _genkit(_Server(reply)).generate(model='openai/gpt-4o', prompt='?', output_schema=schema) + assert response.output == expected + + +@pytest.mark.asyncio +async def test_plugin_wraps_a_pydantic_enum() -> None: + """An Enum output type is a string schema, so it is wrapped too.""" + server = _Server('{"value":"blue"}') + response = await _genkit(server).generate(model='openai/gpt-4o', prompt='Sky?', output_schema=Color) + + assert server.sent_schema()['properties']['value']['enum'] == ['red', 'blue'] + assert response.output == Color.BLUE + + +@pytest.mark.asyncio +async def test_plugin_streams_unwrapped_chunks_and_an_unwrapped_message() -> None: + """Chunks read as the caller's value and the final message matches them.""" + frames = [_delta({'content': FULL[i : i + 5]}) for i in range(0, len(FULL), 5)] + frames.append(_delta({}, 'stop')) + server = _Server(frames=frames) + + stream = _genkit(server).generate_stream(model='openai/gpt-4o', prompt='Two people.', output_schema=ARRAY_SCHEMA) + streamed = ''.join([chunk.text async for chunk in stream.stream]) + response = await stream.response + + assert server.sent_schema()['required'] == ['value'] + assert streamed == '[{"name":"a"},{"name":"b"}]' + assert response.text == '[{"name":"a"},{"name":"b"}]' + assert response.output == [{'name': 'a'}, {'name': 'b'}] + + +@pytest.mark.asyncio +async def test_plugin_streams_a_tool_call_preamble_unchanged() -> None: + """Text before a tool call is not the output, so it streams and stays as sent.""" + tool_call = { + 'index': 0, + 'id': 'call_1', + 'type': 'function', + 'function': {'name': 'lookup', 'arguments': '{"dish":"pho"}'}, + } + server = _Server( + frames=[_delta({'content': '{"val'}), _delta({'tool_calls': [tool_call]}), _delta({}, 'tool_calls')] + ) + ai = _genkit(server) + + @ai.tool(name='lookup') + async def lookup(dish: str) -> str: + return dish + + stream = ai.generate_stream( + model='openai/gpt-4o', + prompt='Two people.', + output_schema=ARRAY_SCHEMA, + tools=['lookup'], + return_tool_requests=True, + ) + streamed = ''.join([chunk.text async for chunk in stream.stream]) + response = await stream.response + + assert streamed == '{"val' + assert response.message is not None + assert response.message.content[0].text == '{"val' + assert [p.tool_request.name for p in response.tool_requests if p.tool_request] == ['lookup'] + + +@pytest.mark.asyncio +async def test_plugin_sends_an_object_root_unchanged() -> None: + """Object schemas send the same request as before.""" + schema = {'type': 'object', 'properties': {'a': {'type': 'string'}}, 'required': ['a']} + server = _Server('{"a":"x"}') + response = await _genkit(server).generate(model='openai/gpt-4o', prompt='An object.', output_schema=schema) + + assert 'value' not in server.sent_schema()['properties'] + assert response.output == {'a': 'x'} + + +@pytest.mark.asyncio +async def test_plugin_pointed_at_another_host_still_wraps() -> None: + """Gateways in front of OpenAI reject the same roots, so base_url doesn't turn wrapping off.""" + server = _Server('{"value":[{"name":"a"}]}') + ai = _genkit(server, base_url='https://gateway.example.com/v1') + response = await ai.generate(model='openai/gpt-4o', prompt='One person.', output_schema=ARRAY_SCHEMA) + + assert server.sent_schema()['required'] == ['value'] + assert response.output == [{'name': 'a'}] diff --git a/packages/genkit-openai/tests/tool_calling_test.py b/packages/genkit-openai/tests/tool_calling_test.py index 1d454b7f..dcff0261 100644 --- a/packages/genkit-openai/tests/tool_calling_test.py +++ b/packages/genkit-openai/tests/tool_calling_test.py @@ -214,7 +214,7 @@ async def test_scalar_tool_schema_is_wrapped_and_round_trips(make_completion: Ca def test_enum_and_defs_tool_schemas_wrap_with_defs_at_root() -> None: """A $ref root to an Enum is wrapped; $defs stay at the root so refs still resolve.""" - from genkit_openai._models._model import _is_wrapped_tool_schema, _wrap_tool_schema + from genkit_openai._models._model import _TOOL_INPUT_FIELD, _is_non_object_schema, _wrap_schema spice = {'enum': ['mild', 'hot'], 'type': 'string'} enum_root = {'$defs': {'SpiceLevel': spice}, '$ref': '#/$defs/SpiceLevel'} @@ -224,10 +224,10 @@ def test_enum_and_defs_tool_schemas_wrap_with_defs_at_root() -> None: } dangling = {'$ref': '#/$defs/Missing'} - assert _is_wrapped_tool_schema(enum_root) is True - assert _is_wrapped_tool_schema(order) is False - assert _is_wrapped_tool_schema(dangling) is False - assert _wrap_tool_schema(enum_root) == { + assert _is_non_object_schema(enum_root) is True + assert _is_non_object_schema(order) is False + assert _is_non_object_schema(dangling) is False + assert _wrap_schema(enum_root, _TOOL_INPUT_FIELD) == { 'type': 'object', 'properties': {'input': {'$ref': '#/$defs/SpiceLevel'}}, 'required': ['input'], From db97918990415faa8c3719859d38e1aab350e197 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 24 Nov 2026 17:24:30 +0000 Subject: [PATCH 2/3] fix(py/openai): unwrap the value beside other keys, as JS, Go and Dart do --- .../src/genkit_openai/_models/_output_root.py | 10 +++++++--- packages/genkit-openai/tests/output_root_test.py | 9 +++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_output_root.py b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py index c3690c15..2276b2b4 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_output_root.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py @@ -77,15 +77,19 @@ def unwrap_output_text(text: str) -> str: """JSON text of the wrapped value in ``text``, or ``text`` unchanged. The value's text is kept as sent, so it reads the same as when streamed. - Text that is not exactly ``{"value": ...}`` is returned as is: a host that - ignored the schema may reply with the bare value. + Text that is not an object with a ``value`` key is returned as is: a host + that ignored the schema may reply with the bare value. """ try: parsed = json.loads(text) except ValueError: return text - if not isinstance(parsed, dict) or set(cast(dict[str, Any], parsed)) != {OUTPUT_VALUE_FIELD}: + if not isinstance(parsed, dict) or OUTPUT_VALUE_FIELD not in parsed: return text + parsed = cast(dict[str, Any], parsed) + if len(parsed) > 1: + # Keys beside the value (a non-strict host) rule out slicing. + return json.dumps(parsed[OUTPUT_VALUE_FIELD]) # The shape is known, so stripping the opening and closing brace leaves # exactly the value. unwrapper = OutputStreamUnwrapper() diff --git a/packages/genkit-openai/tests/output_root_test.py b/packages/genkit-openai/tests/output_root_test.py index 141a8e88..9ff67296 100644 --- a/packages/genkit-openai/tests/output_root_test.py +++ b/packages/genkit-openai/tests/output_root_test.py @@ -83,9 +83,14 @@ def test_unwrap_output_text_returns_the_value_as_sent(text: str, expected: str) assert unwrap_output_text(text) == expected -@pytest.mark.parametrize('text', ['[1,2]', '{"other":1}', '{"value":1,"extra":2}', 'not json', '']) +def test_unwrap_output_text_takes_the_value_beside_other_keys() -> None: + """A non-strict host may add keys; the value is still taken, as in JS, Go and Dart.""" + assert json.loads(unwrap_output_text('{"value":[1, 2],"extra":2}')) == [1, 2] + + +@pytest.mark.parametrize('text', ['[1,2]', '{"other":1}', 'not json', '']) def test_unwrap_output_text_passes_through_anything_else(text: str) -> None: - """Only exactly {"value": ...} is unwrapped; a bare value from a host that ignored the schema is kept.""" + """Only an object with a value key is unwrapped; a bare value from a host that ignored the schema is kept.""" assert unwrap_output_text(text) == text From efc4bf08d9d99fc96585e800070403604e3a38e2 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Thu, 26 Nov 2026 12:24:05 +0000 Subject: [PATCH 3/3] fix(py/openai): hoist local refs, unwrap only a lone value key, skip Mistral - The output wrapper moves '#' and '#/...' references into $defs and keeps $schema at the root, as JS and Go do. - A reply is unwrapped only when value is its one key, as in Dart. - The final streamed message is built from the raw text and unwrapped as a full reply is. - Mistral requests are no longer wrapped. - Restore the tool-schema helper names. --- packages/genkit-openai/README.md | 8 +- .../src/genkit_openai/_models/_model.py | 78 ++++---- .../src/genkit_openai/_models/_output_root.py | 183 +++++++++++++++++- .../src/genkit_openai/_openai_plugin.py | 3 +- .../genkit-openai/tests/output_root_test.py | 141 +++++++++++++- .../genkit-openai/tests/tool_calling_test.py | 10 +- 6 files changed, 363 insertions(+), 60 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 920eee11..cf9e9070 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -88,9 +88,11 @@ sent. To send one anyway, pass it as `extra={'quality': 'xhigh'}`. ## Structured output OpenAI only accepts an object at the root of an output schema, so `OpenAI()` -sends any other schema (a list, enum or scalar, such as `output_schema=list[str]` -or a `str` Enum) as the `value` property of an object and unwraps the reply. -`response.output` and the streamed chunks hold the value itself. +sends any other schema (a list, enum or scalar, such as `output_schema=int`, +a `str` Enum or `{'type': 'array', 'items': {'type': 'string'}}`) as the +`value` property of an object and unwraps the reply. `response.output` and +the streamed chunks hold the value itself. Requests to Mistral are sent +unwrapped. ## Mistral diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index d6cb3ea8..19c6c1cc 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -22,10 +22,10 @@ from genkit_openai._models._mistral import is_mistral, mistral_chat_body, refuse_non_image_media from genkit_openai._models._output_root import ( - OUTPUT_VALUE_FIELD, OutputStreamUnwrapper, has_object_root, unwrap_output_text, + wrap_schema_root, ) from genkit_openai._models._utils import ( OPENAI_CALL_ERRORS, @@ -275,11 +275,11 @@ def _root_ref_target(schema: dict[str, Any]) -> dict[str, Any] | None: return None -def _is_non_object_schema(schema: dict[str, Any] | None) -> bool: +def _is_wrapped_tool_schema(schema: dict[str, Any] | None) -> bool: """True for a non-empty schema that is not an object (``{'type': 'string'}``). - OpenAI takes only an object for a function's parameters and for a - ``json_schema`` response format, so such a schema is sent wrapped. + OpenAI takes only an object for a function's parameters, so such a + schema is sent wrapped. A root ``$ref`` is judged by its target: Pydantic emits one for an Enum input, which is a string, not an object. @@ -291,26 +291,26 @@ def _is_non_object_schema(schema: dict[str, Any] | None) -> bool: if '$ref' in schema: target = _root_ref_target(schema) # An unresolvable ref is sent as is rather than guessed at. - return target is not None and _is_non_object_schema(target) + return target is not None and _is_wrapped_tool_schema(target) # anyOf/oneOf roots: only an object schema is safe to send as-is. return 'properties' not in schema return schema_type != 'object' -def _wrap_schema(schema: dict[str, Any], field: str) -> dict[str, Any]: - """``schema`` under the one property ``field``, with any ``$defs`` kept at the root.""" +def _wrap_tool_schema(schema: dict[str, Any]) -> dict[str, Any]: + """``schema`` under one ``input`` property, with any ``$defs`` kept at the root.""" defs = {k: schema[k] for k in _DEFS_KEYS if k in schema} inner = {k: v for k, v in schema.items() if k not in defs} return { 'type': 'object', - 'properties': {field: inner}, - 'required': [field], + 'properties': {_TOOL_INPUT_FIELD: inner}, + 'required': [_TOOL_INPUT_FIELD], **defs, } def _wrapped_tool_names(tools: list[ToolDefinition] | None) -> frozenset[str]: - return frozenset(t.name for t in tools or [] if _is_non_object_schema(t.input_schema)) + return frozenset(t.name for t in tools or [] if _is_wrapped_tool_schema(t.input_schema)) def _map_tool_requests(message: Message, wrapped: frozenset[str], wrap: bool) -> Message: @@ -353,19 +353,25 @@ def _unwrapped_args_text(arguments: str) -> str: def _unwrap_output(message: Message) -> Message: """Replace a wrapped reply's text with the wrapped value. - Text beside a tool call is a preamble, not the output, and is left alone. + The text parts are read as one text, as a streamed reply arrives in many + of them, and the value goes in the first. Text beside a tool call is a + preamble, not the output, and is left alone. """ if any(part.tool_request is not None for part in message.content): return message - changed = False - content: list[Part] = [] - for part in message.content: - if part.text is not None and (text := unwrap_output_text(part.text)) != part.text: - content.append(part.model_copy(update={'text': text})) - changed = True - else: - content.append(part) - return message.model_copy(update={'content': content}) if changed else message + texts = [i for i, part in enumerate(message.content) if part.text is not None] + if not texts: + return message + text = ''.join(message.content[i].text or '' for i in texts) + value = unwrap_output_text(text) + if value == text: + return message + content = [ + part.model_copy(update={'text': value}) if i == texts[0] else part + for i, part in enumerate(message.content) + if i == texts[0] or i not in texts + ] + return message.model_copy(update={'content': content}) def _wrap_tool_inputs(messages: list[Message], wrapped: frozenset[str]) -> list[Message]: @@ -456,10 +462,10 @@ async def _get_tools_definition(self, tools: list[ToolDefinition]) -> list[dict] result = [] for tool_definition in tools: parameters = tool_definition.input_schema or {} - if _is_non_object_schema(parameters): + if _is_wrapped_tool_schema(parameters): # Function parameters must be an object; a scalar tool input # (``async def tool(city: str)``) rides under one field. - parameters = _wrap_schema(parameters, _TOOL_INPUT_FIELD) + parameters = _wrap_tool_schema(parameters) if parameters: parameters = _ensure_strict_json_schema(parameters, path=(), root=parameters) @@ -526,7 +532,7 @@ def _get_response_format(self, request: ModelRequest) -> dict | None: if request.output_schema: schema = request.output_schema if self._wraps_output(request): - schema = _wrap_schema(schema, OUTPUT_VALUE_FIELD) + schema = wrap_schema_root(schema) return { 'type': 'json_schema', 'json_schema': { @@ -740,8 +746,9 @@ async def _generate_stream( tool_calls: dict[int, Any] = {} wrapped = _wrapped_tool_names(request.tools) - # A wrapped reply streams as '{"value": ...}'; text is unwrapped as it - # arrives, so chunks and the final message read as the caller's value. + # A wrapped reply streams as '{"value": ...}'; chunks are unwrapped as + # they arrive. The final message is built from the raw text and + # unwrapped as a full reply is, so the two paths can't disagree. unwrapper = OutputStreamUnwrapper() if self._wraps_output(request) else None # As a full reply is read (MessageConverter.to_genkit): reasoning from # its own field (DeepSeek's reasoning_content) first, then the @@ -787,18 +794,16 @@ async def _generate_stream( # Text before a tool call is a preamble, not the output: whatever # was held back goes out as it streamed, and so does the rest. if unwrapper is not None and delta.tool_calls and (held_text := unwrapper.pass_through()): - held_part = MessageConverter.text_part_to_genkit(held_text) - content_parts.append(held_part) - parts.append(held_part) + parts.append(MessageConverter.text_part_to_genkit(held_text)) # Text content; Mistral's reasoning models stream reasoning in it too. for item in reply_content(delta.content): - if isinstance(item, str) and unwrapper is not None: - item = unwrapper.push(item) - if not item: - continue part = MessageConverter.text_part_to_genkit(item) if isinstance(item, str) else item content_parts.append(part) + if isinstance(item, str) and unwrapper is not None: + if chunk_text := unwrapper.push(item): + parts.append(MessageConverter.text_part_to_genkit(chunk_text)) + continue parts.append(part) # Tool calls (partial function calls) @@ -822,9 +827,7 @@ async def _generate_stream( callback(ModelResponseChunk(role=Role.MODEL, content=parts)) if unwrapper is not None and (rest := unwrapper.flush()): - rest_part = MessageConverter.text_part_to_genkit(rest) - content_parts.append(rest_part) - callback(ModelResponseChunk(role=Role.MODEL, content=[rest_part])) + callback(ModelResponseChunk(role=Role.MODEL, content=[MessageConverter.text_part_to_genkit(rest)])) if not saw_choice: raise GenkitError( @@ -863,9 +866,12 @@ async def _generate_stream( failure_message=failure_message, ) + final_message = Message(role=Role.MODEL, content=accumulated_content) + if unwrapper is not None: + final_message = _unwrap_output(final_message) result = ModelResponse( request=request, - message=Message(role=Role.MODEL, content=accumulated_content), + message=final_message, finish_reason=finish_reason, finish_message=finish_message, usage=_usage_from_completion(usage), diff --git a/packages/genkit-openai/src/genkit_openai/_models/_output_root.py b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py index 2276b2b4..a56301bc 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_output_root.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_output_root.py @@ -73,12 +73,183 @@ def has_object_root(schema: dict[str, Any]) -> bool: return False +def wrap_schema_root(schema: dict[str, Any]) -> dict[str, Any]: + """``schema`` as the one required ``value`` property of an object schema. + + ``$schema``, ``$defs`` and ``definitions`` stay at the root, so references + to the definitions still resolve. + + Any other local reference (``#``, ``#/items/...``) pointed into the + caller's schema, which is no longer the root. Strict mode accepts + references only to top-level definitions, so each referenced subschema + moves into ``$defs``, and both its old place and every reference to it + point there instead. + """ + hoister = _RefHoister(schema) + wrapped: dict[str, Any] = { + 'type': 'object', + 'required': [OUTPUT_VALUE_FIELD], + 'additionalProperties': False, + } + inner: dict[str, Any] = {} + for key, value in schema.items(): + if key == '$schema': + wrapped[key] = value + elif key == 'definitions': + wrapped[key] = hoister.walk(value, '#/definitions', names=True) + elif key == '$defs': + if isinstance(value, dict): + for name, definition in cast(dict[str, Any], value).items(): + hoister.defs[name] = hoister.walk(definition, f'#/$defs/{_escape(name)}') + else: + wrapped[key] = value + else: + inner[key] = value + wrapped['properties'] = {OUTPUT_VALUE_FIELD: hoister.walk(inner, '#')} + if hoister.defs: + wrapped['$defs'] = hoister.defs + return wrapped + + +# Keywords that hold data rather than subschemas: a ``$ref`` inside them is +# not a reference. +_DATA_KEYWORDS = frozenset({'const', 'enum', 'default', 'examples'}) +# Keywords whose values map names to subschemas. Keys there are names, so a +# property called ``default`` or ``$ref`` is a schema like any other. +_NAME_MAPS = frozenset({'properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'}) +_DEFS_PREFIXES = ('#/$defs/', '#/definitions/') + + +class _RefHoister: + """Moves the subschemas that local references point at into ``$defs`` as it copies a schema.""" + + def __init__(self, schema: dict[str, Any]) -> None: + self.defs: dict[str, Any] = {} + defs = schema.get('$defs') + taken = set(cast(dict[str, Any], defs)) if isinstance(defs, dict) else set() + refs: set[str] = set() + _collect_refs(schema, refs, names=False) + # Each referenced JSON pointer, and the name it moves to in defs. + self.targets: dict[str, str] = {} + for ref in sorted(r for r in refs if _hoistable(r) and _resolves(schema, r)): + self.targets[ref] = _unique_def_name(ref, taken) + + def walk(self, node: object, pointer: str, *, names: bool = False) -> object: + """Copy ``node``, found at ``pointer`` in the caller's schema. + + A node that a reference points at goes into defs, and a reference to it + is left in its place. ``names`` says ``node`` maps names to subschemas. + """ + if (name := self.targets.get(pointer)) is not None: + self.defs[name] = self._copy(node, pointer, names=names) + return {'$ref': f'#/$defs/{name}'} + return self._copy(node, pointer, names=names) + + def _copy(self, node: object, pointer: str, *, names: bool) -> object: + if isinstance(node, list): + return [self.walk(v, f'{pointer}/{i}') for i, v in enumerate(cast(list[Any], node))] + if not isinstance(node, dict): + return node + out: dict[str, Any] = {} + for key, value in cast(dict[str, Any], node).items(): + at = f'{pointer}/{_escape(key)}' + if names: + out[key] = self.walk(value, at) + elif key == '$ref' and isinstance(value, str): + name = self.targets.get(value) + out[key] = f'#/$defs/{name}' if name is not None else value + elif key in _DATA_KEYWORDS: + out[key] = value + else: + out[key] = self.walk(value, at, names=key in _NAME_MAPS) + return out + + +def _collect_refs(node: object, found: set[str], *, names: bool) -> None: + """Add every ``$ref`` in ``node`` to ``found``.""" + if isinstance(node, list): + for value in cast(list[Any], node): + _collect_refs(value, found, names=False) + elif isinstance(node, dict): + for key, value in cast(dict[str, Any], node).items(): + if names: + _collect_refs(value, found, names=False) + elif key == '$ref' and isinstance(value, str): + found.add(value) + elif key not in _DATA_KEYWORDS: + _collect_refs(value, found, names=key in _NAME_MAPS) + + +def _defs_path(ref: str) -> str | None: + """What follows ``#/$defs/`` or ``#/definitions/`` in ``ref``, or None.""" + for prefix in _DEFS_PREFIXES: + if ref.startswith(prefix): + return ref[len(prefix) :] + return None + + +def _hoistable(ref: str) -> bool: + """Whether ``ref`` is a local reference strict mode can't follow once the schema is wrapped. + + A reference to a whole top-level definition is fine; one into the middle + of a definition or anywhere else in the schema is not. + """ + if ref != '#' and not ref.startswith('#/'): + return False + if (rest := _defs_path(ref)) is not None: + return '/' in rest + return ref not in ('#/$defs', '#/definitions') + + +def _resolves(schema: dict[str, Any], ref: str) -> bool: + """Whether the JSON pointer ``ref`` names a schema inside ``schema``.""" + node: object = schema + for segment in ref.removeprefix('#').split('/')[1:]: + segment = segment.replace('~1', '/').replace('~0', '~') + if isinstance(node, dict): + node = cast(dict[str, Any], node) + if segment not in node: + return False + node = node[segment] + elif isinstance(node, list): + items = cast(list[Any], node) + if not segment.isdigit() or int(segment) >= len(items): + return False + node = items[int(segment)] + else: + return False + return isinstance(node, dict) + + +def _escape(key: str) -> str: + return key.replace('~', '~0').replace('/', '~1') + + +def _unique_def_name(ref: str, taken: set[str]) -> str: + """Name the definition a referenced pointer moves to, avoiding the names already taken. + + A pointer into a definition is named after its path there + (``Person_properties_name``), and any other after its path under the + wrapper (``value_items``). + """ + path = _defs_path(ref) + if path is None: + path = OUTPUT_VALUE_FIELD + ref.removeprefix('#') + base = re.sub(r'[^\w-]', '_', path) + name, i = base, 2 + while name in taken: + name, i = f'{base}_{i}', i + 1 + taken.add(name) + return name + + def unwrap_output_text(text: str) -> str: """JSON text of the wrapped value in ``text``, or ``text`` unchanged. The value's text is kept as sent, so it reads the same as when streamed. - Text that is not an object with a ``value`` key is returned as is: a host - that ignored the schema may reply with the bare value. + Text that is not an object whose only key is ``value`` is returned as is: + a host that ignored the schema may reply with the bare value, or with an + object that has a ``value`` property of its own. """ try: parsed = json.loads(text) @@ -86,10 +257,10 @@ def unwrap_output_text(text: str) -> str: return text if not isinstance(parsed, dict) or OUTPUT_VALUE_FIELD not in parsed: return text - parsed = cast(dict[str, Any], parsed) - if len(parsed) > 1: - # Keys beside the value (a non-strict host) rule out slicing. - return json.dumps(parsed[OUTPUT_VALUE_FIELD]) + if len(cast(dict[str, Any], parsed)) > 1: + # Keys beside the value: a host that ignored the wrapper and replied + # with an object of its own, which is left as sent. + return text # The shape is known, so stripping the opening and closing brace leaves # exactly the value. unwrapper = OutputStreamUnwrapper() diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index a9682a7c..56e87d66 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -678,7 +678,8 @@ async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> M client, supports=info.supports, mistral=self._uses_mistral_names(client), - object_schema_root=True, + # Only OpenAI requires an object root; Mistral requests go as before. + object_schema_root=not self._uses_mistral_names(client), ) ) return await openai_model.generate(request, ctx) diff --git a/packages/genkit-openai/tests/output_root_test.py b/packages/genkit-openai/tests/output_root_test.py index 9ff67296..eb599ee8 100644 --- a/packages/genkit-openai/tests/output_root_test.py +++ b/packages/genkit-openai/tests/output_root_test.py @@ -23,9 +23,14 @@ import httpx import pytest -from genkit_openai import OpenAI +from genkit_openai import Mistral, OpenAI from genkit_openai._models._model import OpenAIModel, _unwrap_output -from genkit_openai._models._output_root import OutputStreamUnwrapper, has_object_root, unwrap_output_text +from genkit_openai._models._output_root import ( + OutputStreamUnwrapper, + has_object_root, + unwrap_output_text, + wrap_schema_root, +) from genkit import Genkit, Message, Part, Role from genkit.model import ModelRequest, OutputConfig, ToolRequest @@ -83,17 +88,25 @@ def test_unwrap_output_text_returns_the_value_as_sent(text: str, expected: str) assert unwrap_output_text(text) == expected -def test_unwrap_output_text_takes_the_value_beside_other_keys() -> None: - """A non-strict host may add keys; the value is still taken, as in JS, Go and Dart.""" - assert json.loads(unwrap_output_text('{"value":[1, 2],"extra":2}')) == [1, 2] - - -@pytest.mark.parametrize('text', ['[1,2]', '{"other":1}', 'not json', '']) +@pytest.mark.parametrize( + 'text', ['[1,2]', '{"other":1}', '{"value":[1,2],"extra":2}', '{"extra":2,"value":[1,2]}', 'not json', ''] +) def test_unwrap_output_text_passes_through_anything_else(text: str) -> None: - """Only an object with a value key is unwrapped; a bare value from a host that ignored the schema is kept.""" + """Only an object whose one key is value is unwrapped; a host that ignored the schema keeps its reply.""" assert unwrap_output_text(text) == text +def test_unwrap_output_reads_streamed_text_parts_as_one() -> None: + """A streamed reply's text parts are unwrapped together, and the value goes in the first.""" + answer = _unwrap_output( + Message( + role=Role.MODEL, + content=[Part.from_text('{"val'), Part.from_reasoning('hmm'), Part.from_text('ue":[1]}')], + ) + ) + assert [(p.text, p.reasoning) for p in answer.content] == [('[1]', None), (None, 'hmm')] + + def test_unwrap_output_keeps_reasoning_and_leaves_a_tool_call_preamble_alone() -> None: """Text is unwrapped and other parts kept, unless the reply calls a tool.""" answer = _unwrap_output( @@ -251,6 +264,55 @@ def test_response_format_wraps_a_root_ref_to_an_enum() -> None: assert sent['$defs'] == schema['$defs'] +def test_wrap_schema_root_hoists_a_root_reference() -> None: + """'#' pointed at the caller's schema; once wrapped it moves to $defs, and $schema stays at the root.""" + schema = { + '$schema': 'http://json-schema.org/draft-07/schema#', + 'type': 'array', + 'items': {'anyOf': [{'type': 'string'}, {'$ref': '#'}]}, + } + wrapped = wrap_schema_root(schema) + assert wrapped['$schema'] == schema['$schema'] + assert wrapped['properties'] == {'value': {'$ref': '#/$defs/value'}} + assert wrapped['$defs'] == { + 'value': {'type': 'array', 'items': {'anyOf': [{'type': 'string'}, {'$ref': '#/$defs/value'}]}} + } + + +def test_wrap_schema_root_hoists_a_pointer_into_the_schema() -> None: + """A '#/items/...' reference moves to $defs, which the SDK's strict pass can then resolve.""" + model = OpenAIModel(model='gpt-4o', client=MagicMock(), object_schema_root=True) + schema = { + 'type': 'array', + 'items': { + 'type': 'object', + 'properties': {'a': {'type': 'string'}, 'b': {'$ref': '#/items/properties/a', 'description': 'd'}}, + 'required': ['a', 'b'], + }, + } + sent = _sent_schema(model, _json_request(schema)) + item = sent['properties']['value']['items'] + assert item['properties']['a'] == {'$ref': '#/$defs/value_items_properties_a'} + assert item['properties']['b'] == {'type': 'string', 'description': 'd'} + assert sent['$defs'] == {'value_items_properties_a': {'type': 'string'}} + + +def test_wrap_schema_root_leaves_references_to_whole_definitions() -> None: + """References to a top-level definition still resolve, and data keywords are not read as references.""" + schema = { + 'type': 'array', + 'items': {'$ref': '#/$defs/Node', 'default': {'$ref': '#'}}, + '$defs': {'Node': {'type': 'object', 'properties': {'name': {'$ref': '#/$defs/Node/properties/x'}, 'x': {}}}}, + } + wrapped = wrap_schema_root(schema) + assert wrapped['properties']['value']['items'] == {'$ref': '#/$defs/Node', 'default': {'$ref': '#'}} + assert wrapped['$defs']['Node']['properties'] == { + 'name': {'$ref': '#/$defs/Node_properties_x'}, + 'x': {'$ref': '#/$defs/Node_properties_x'}, + } + assert wrapped['$defs']['Node_properties_x'] == {} + + def test_response_format_is_unchanged_without_the_setting() -> None: """Other users of OpenAIModel (Model Garden) send the schema as before.""" model = OpenAIModel(model='meta/llama', client=MagicMock()) @@ -419,3 +481,64 @@ async def test_plugin_pointed_at_another_host_still_wraps() -> None: assert server.sent_schema()['required'] == ['value'] assert response.output == [{'name': 'a'}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('reply', ['{"value":[1,2],"extra":2}', '{"extra":2,"value":[1,2]}']) +async def test_plugin_leaves_a_reply_with_other_keys_alone(reply: str) -> None: + """A host that ignored the wrapper keeps its reply, streamed or not.""" + schema = {'type': 'array', 'items': {'type': 'integer'}} + response = await _genkit(_Server(reply)).generate(model='openai/gpt-4o', prompt='?', output_schema=schema) + assert response.text == reply + + frames = [_delta({'content': reply[i : i + 4]}) for i in range(0, len(reply), 4)] + frames.append(_delta({}, 'stop')) + stream = _genkit(_Server(frames=frames)).generate_stream(model='openai/gpt-4o', prompt='?', output_schema=schema) + [_ async for _ in stream.stream] + assert (await stream.response).text == reply + + +@pytest.mark.asyncio +async def test_plugin_streams_the_same_message_as_a_full_reply_when_a_tool_call_follows() -> None: + """A whole wrapper before a tool call is a preamble, kept as sent, as in a full reply.""" + tool_call = { + 'index': 0, + 'id': 'call_1', + 'type': 'function', + 'function': {'name': 'lookup', 'arguments': '{"dish":"pho"}'}, + } + server = _Server( + frames=[_delta({'content': '{"value":[1,2]}'}), _delta({'tool_calls': [tool_call]}), _delta({}, 'tool_calls')] + ) + ai = _genkit(server) + + @ai.tool(name='lookup') + async def lookup(dish: str) -> str: + return dish + + stream = ai.generate_stream( + model='openai/gpt-4o', + prompt='?', + output_schema={'type': 'array', 'items': {'type': 'integer'}}, + tools=['lookup'], + return_tool_requests=True, + ) + [_ async for _ in stream.stream] + response = await stream.response + + assert response.message is not None + assert response.message.content[0].text == '{"value":[1,2]}' + assert [p.tool_request.name for p in response.tool_requests if p.tool_request] == ['lookup'] + + +@pytest.mark.asyncio +async def test_mistral_sends_a_non_object_root_unwrapped() -> None: + """Only OpenAI needs an object root, so Mistral gets the schema as before.""" + server = _Server('[1,2]') + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + ai = Genkit(plugins=[Mistral(api_key='test', client_options={'http_client': http_client, 'max_retries': 0})]) + schema = {'type': 'array', 'items': {'type': 'integer'}} + response = await ai.generate(model='mistral/mistral-small-latest', prompt='?', output_schema=schema) + + assert server.sent_schema()['type'] == 'array' + assert response.output == [1, 2] diff --git a/packages/genkit-openai/tests/tool_calling_test.py b/packages/genkit-openai/tests/tool_calling_test.py index dcff0261..1d454b7f 100644 --- a/packages/genkit-openai/tests/tool_calling_test.py +++ b/packages/genkit-openai/tests/tool_calling_test.py @@ -214,7 +214,7 @@ async def test_scalar_tool_schema_is_wrapped_and_round_trips(make_completion: Ca def test_enum_and_defs_tool_schemas_wrap_with_defs_at_root() -> None: """A $ref root to an Enum is wrapped; $defs stay at the root so refs still resolve.""" - from genkit_openai._models._model import _TOOL_INPUT_FIELD, _is_non_object_schema, _wrap_schema + from genkit_openai._models._model import _is_wrapped_tool_schema, _wrap_tool_schema spice = {'enum': ['mild', 'hot'], 'type': 'string'} enum_root = {'$defs': {'SpiceLevel': spice}, '$ref': '#/$defs/SpiceLevel'} @@ -224,10 +224,10 @@ def test_enum_and_defs_tool_schemas_wrap_with_defs_at_root() -> None: } dangling = {'$ref': '#/$defs/Missing'} - assert _is_non_object_schema(enum_root) is True - assert _is_non_object_schema(order) is False - assert _is_non_object_schema(dangling) is False - assert _wrap_schema(enum_root, _TOOL_INPUT_FIELD) == { + assert _is_wrapped_tool_schema(enum_root) is True + assert _is_wrapped_tool_schema(order) is False + assert _is_wrapped_tool_schema(dangling) is False + assert _wrap_tool_schema(enum_root) == { 'type': 'object', 'properties': {'input': {'$ref': '#/$defs/SpiceLevel'}}, 'required': ['input'],