From 4a09b8820cfb99bee6e457927ed3e152bc22e936 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:16:46 -0600 Subject: [PATCH 1/5] fix(py): add read-only OutputConfig.schema property (D4a) --- packages/genkit/src/genkit/_core/_model.py | 9 +++++++++ .../tests/genkit/core/output_config_test.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 4a2c2cc9f..660227129 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -1352,6 +1352,15 @@ class OutputConfig(GenkitModel): constrained: bool | None = None content_type: str | None = None + @property + def schema(self) -> dict[str, Any] | None: # pyright: ignore[reportIncompatibleMethodOverride] + """Read-only alias for ``json_schema``, matching the wire key and JS. + + Shadows Pydantic's deprecated ``BaseModel.schema()`` classmethod so + ``request.output.schema`` returns the schema dict, or ``None``. + """ + return self.json_schema + class ModelRequest(GenkitModel, Generic[ModelRequestConfigT]): """Hand-written model request with veneer types and flat output accessors. diff --git a/packages/genkit/tests/genkit/core/output_config_test.py b/packages/genkit/tests/genkit/core/output_config_test.py index 8f6db55c7..3d8e53989 100644 --- a/packages/genkit/tests/genkit/core/output_config_test.py +++ b/packages/genkit/tests/genkit/core/output_config_test.py @@ -70,3 +70,18 @@ def test_as_output_config_unwraps_output_config_data() -> None: assert isinstance(cfg, OutputConfigData) is False assert cfg.json_schema == _SAMPLE assert cfg.model_dump() == {'schema': _SAMPLE} + + +def test_schema_property_reads_json_schema() -> None: + """``request.output.schema`` must not resolve to ``BaseModel.schema``.""" + assert OutputConfig().schema is None + assert OutputConfig.model_validate({'schema': _SAMPLE}).schema == _SAMPLE + + +def test_request_output_schema_on_plain_text_request() -> None: + from genkit._core._model import ModelRequest + + plain = ModelRequest.model_validate({'messages': []}) + assert plain.output.schema is None + structured = ModelRequest.model_validate({'messages': [], 'output': {'format': 'json', 'schema': _SAMPLE}}) + assert structured.output.schema == _SAMPLE From 14e3c14bde1f31826287bf94ef328f5cd58df1fd Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:17:42 -0600 Subject: [PATCH 2/5] fix(py): prefix plugin-advertised action keys with the plugin name Registry.list_actions() advertised /model/org/name for a plugin returning an unprefixed slash id, which 404s on /api/runAction. Apply the same prefix rule as init(). --- packages/genkit/src/genkit/_core/_registry.py | 7 +++-- .../genkit/ai/plugin_resolve_name_test.py | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 908899655..94c009354 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -427,8 +427,11 @@ async def list_actions( raise ValueError(f'Invalid ActionMetadata from {plugin_name}: name required') if not meta.action_type: raise ValueError(f'Invalid ActionMetadata from {plugin_name}: action_type required') - key = f'/{meta.action_type}/{meta.name}' - catalog[key] = meta.model_copy(update={'key': key}) + # Same prefix rule as ``register_action_instance`` in ``init()`` so + # the advertised key resolves through ``resolve_action``. + name = meta.name if meta.name.startswith(f'{plugin_name}/') else f'{plugin_name}/{meta.name}' + key = f'/{meta.action_type}/{name}' + catalog[key] = meta.model_copy(update={'key': key, 'name': name}) # 2. Concrete registered actions. A local tool is ``/tool/`` plus its # ``/tool.v2/`` envelope; the Dev UI shows the ``tool.v2`` row. diff --git a/packages/genkit/tests/genkit/ai/plugin_resolve_name_test.py b/packages/genkit/tests/genkit/ai/plugin_resolve_name_test.py index 1ca797317..62d909ccf 100644 --- a/packages/genkit/tests/genkit/ai/plugin_resolve_name_test.py +++ b/packages/genkit/tests/genkit/ai/plugin_resolve_name_test.py @@ -354,3 +354,31 @@ async def test_check_operation_saved_handle_checks_on_a_fresh_app() -> None: assert checked.id == 'job-1' assert checked.done is True assert checked.action == '/background-model/myplug/veo-x' + + +class AdvertisingPlugin(RecordingPlugin): + """Advertises models the way a vLLM-style plugin would: bare and prefixed ids.""" + + async def list_actions(self) -> list[Action]: + return [ + _answering_model('meta-llama/Llama-3.3-70B', 'listed'), + _answering_model('myplug/already-prefixed', 'listed'), + ] + + +@pytest.mark.asyncio +async def test_list_actions_prefixes_unprefixed_slash_ids() -> None: + """Advertised keys use the same plugin prefix as `init()`, so the Dev UI can run them.""" + plugin = AdvertisingPlugin(serves={'meta-llama/Llama-3.3-70B', 'already-prefixed'}) + ai = Genkit(plugins=[plugin]) + + catalog = await ai._registry.list_actions() + + assert '/model/myplug/meta-llama/Llama-3.3-70B' in catalog + assert '/model/meta-llama/Llama-3.3-70B' not in catalog + assert catalog['/model/myplug/meta-llama/Llama-3.3-70B'].name == 'myplug/meta-llama/Llama-3.3-70B' + assert '/model/myplug/already-prefixed' in catalog + assert '/model/myplug/myplug/already-prefixed' not in catalog + action = await ai._registry.resolve_action_by_key('/model/myplug/meta-llama/Llama-3.3-70B') + assert action is not None + assert action.name == 'myplug/meta-llama/Llama-3.3-70B' From 102478dab3bf9d7ca60e2037531ca659a41f6fb0 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 9 Nov 2026 06:24:23 -0600 Subject: [PATCH 3/5] fix(py): plugin ABI fixes for unannotated models, DAPs, scalar tool schemas - Model wraps an unannotated request parameter as ModelRequest, like Embedder, so Dev UI / CLI runs pass a ModelRequest, not a dict. - DynamicActionProvider stamps itself on its action, so one returned from Plugin.init() is recoverable from the registry. - genkit-openai wraps non-object tool input schemas under 'input' and unwraps tool requests, matching genkit-google-genai. --- .../src/genkit_openai/_models/_model.py | 69 ++++++++++++- .../genkit-openai/tests/tool_calling_test.py | 55 +++++++++++ packages/genkit/src/genkit/_ai/_model.py | 5 +- packages/genkit/src/genkit/_core/_dap.py | 5 + .../genkit/tests/genkit/ai/plugin_abi_test.py | 96 +++++++++++++++++++ 5 files changed, 225 insertions(+), 5 deletions(-) create mode 100644 packages/genkit/tests/genkit/ai/plugin_abi_test.py diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index 243486df6..ab4454420 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -244,6 +244,57 @@ def _finish_state( return finish_reason, failure_message +# The field a non-object tool input rides under on the wire, as in genkit-google-genai. +_TOOL_INPUT_FIELD = 'input' + + +def _is_wrapped_tool_schema(schema: dict[str, Any] | None) -> bool: + """True for a non-empty schema that is not an object (``{'type': 'string'}``).""" + if not schema: + return False + schema_type = schema.get('type') + if schema_type is None: + # anyOf/oneOf/$ref roots: only an object schema is safe to send as-is. + return not ('properties' in schema or '$ref' in schema) + return schema_type != 'object' + + +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)) + + +def _map_tool_requests(message: Message, wrapped: frozenset[str], wrap: bool) -> Message: + if not wrapped: + return message + changed = False + content: list[Part] = [] + for part in message.content: + req = part.tool_request + if req is not None and req.name in wrapped: + if wrap: + new_input: object = {_TOOL_INPUT_FIELD: req.input} + elif isinstance(req.input, dict) and set(req.input) == {_TOOL_INPUT_FIELD}: + new_input = cast(dict[str, Any], req.input)[_TOOL_INPUT_FIELD] + else: + content.append(part) + continue + content.append(Part(tool_request=req.model_copy(update={'input': new_input}), metadata=part.metadata)) + 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] + + +def _unwrap_tool_inputs(message: Message, wrapped: frozenset[str]) -> Message: + """Hand scalar-input tools their bare value, not ``{'input': value}``.""" + return _map_tool_requests(message, wrapped, wrap=False) + + class OpenAIModel: """Handles OpenAI API interactions for the Genkit plugin.""" @@ -304,6 +355,14 @@ 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): + # Function parameters must be an object; a scalar tool input + # (``async def tool(city: str)``) rides under one field. + parameters = { + 'type': 'object', + 'properties': {_TOOL_INPUT_FIELD: parameters}, + 'required': [_TOOL_INPUT_FIELD], + } if parameters: parameters = _ensure_strict_json_schema(parameters, path=(), root=parameters) @@ -445,7 +504,8 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict: Returns: A dictionary representing the OpenAI request configuration. """ - messages = self._get_messages(request.messages) + wrapped = _wrapped_tool_names(request.tools) + messages = self._get_messages(_wrap_tool_inputs(request.messages, wrapped) if wrapped else request.messages) # For models that only support json_object mode, inject the schema # into the messages so the model knows the expected output structure. @@ -513,7 +573,7 @@ async def _generate(self, request: ModelRequest) -> ModelResponse: failure_message=_failure_message(choice.model_extra), ) - genkit_message = MessageConverter.to_genkit(message) + genkit_message = _unwrap_tool_inputs(MessageConverter.to_genkit(message), _wrapped_tool_names(request.tools)) # 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') @@ -622,8 +682,9 @@ async def _generate_stream( accumulated_content: list[Part] = [*reasoning_parts, *text_parts] if tool_calls: - message = MessageConverter.to_genkit( - DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL}) + message = _unwrap_tool_inputs( + MessageConverter.to_genkit(DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL})), + _wrapped_tool_names(request.tools), ) accumulated_content.extend(message.content) diff --git a/packages/genkit-openai/tests/tool_calling_test.py b/packages/genkit-openai/tests/tool_calling_test.py index 9ff98f41d..5c5c3ee7a 100644 --- a/packages/genkit-openai/tests/tool_calling_test.py +++ b/packages/genkit-openai/tests/tool_calling_test.py @@ -155,3 +155,58 @@ def callback(chunk: ModelResponseChunk) -> None: accumulated_output = reduce(lambda res, tool_call: res + tool_call.tool_request.input, collected_chunks, '') assert json.loads(accumulated_output) == {'a': 1} + + +@pytest.mark.asyncio +async def test_scalar_tool_schema_is_wrapped_and_round_trips(make_completion: Callable[..., ChatCompletion]) -> None: + """`async def tool(city: str)` sends an object schema and gets the bare string back.""" + from genkit import Message, Part, Role + from genkit._core._typing import ToolRequest + from genkit.model import ToolDefinition + + completion = make_completion( + choice={ + 'finish_reason': 'tool_calls', + 'message': { + 'role': 'assistant', + 'content': None, + 'tool_calls': [ + { + 'id': 'call1', + 'type': 'function', + 'function': {'name': 'current_weather', 'arguments': '{"input": "Paris"}'}, + } + ], + }, + } + ) + mock_client = MagicMock() + mock_client.chat.completions.create = AsyncMock(return_value=completion) + model = OpenAIModel(model='gpt-4', client=mock_client) + request = ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part.from_text('weather?')]), + Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(ref='call0', name='current_weather', input='Oslo'))], + ), + ], + tools=[ + ToolDefinition( + name='current_weather', description='Weather', input_schema={'type': 'string'}, output_schema=None + ) + ], + ) + + response = await model._generate(request) + + sent = mock_client.chat.completions.create.call_args.kwargs + params = sent['tools'][0]['function']['parameters'] + assert params['type'] == 'object' + assert params['properties']['input'] == {'type': 'string'} + assert params['required'] == ['input'] + replayed = sent['messages'][1]['tool_calls'][0]['function']['arguments'] + assert json.loads(replayed) == {'input': 'Oslo'} + assert response.message is not None + assert response.message.content[0].tool_request is not None + assert response.message.content[0].tool_request.input == 'Paris' diff --git a/packages/genkit/src/genkit/_ai/_model.py b/packages/genkit/src/genkit/_ai/_model.py index 69f1cf6c4..bf3d3444f 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -31,6 +31,7 @@ ActionKind, ModelContext, get_func_description, + with_request_annotation, ) from genkit._core._config_check import ( check_config_values, @@ -493,7 +494,9 @@ def __init__( super().__init__( kind=ActionKind.MODEL, name=name, - fn=fn, + # An unannotated request parameter would get the raw JSON dict from + # a Dev UI or CLI run; give it ModelRequest, like Embedder does. + fn=with_request_annotation(fn, ModelRequest, kind=ActionKind.MODEL), metadata=model_meta, description=get_func_description(fn, description), config_schema=config_schema, diff --git a/packages/genkit/src/genkit/_core/_dap.py b/packages/genkit/src/genkit/_core/_dap.py index 496a8225f..3ad06d655 100644 --- a/packages/genkit/src/genkit/_core/_dap.py +++ b/packages/genkit/src/genkit/_core/_dap.py @@ -23,6 +23,7 @@ from typing import Any from genkit._core._action import ( + GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, Action, ActionKind, create_action_key, @@ -59,6 +60,10 @@ def __init__( cache_ttl_millis: int | None = None, ) -> None: self.action = action + # Stamp the provider on its action so a ``dap.action`` returned from + # ``Plugin.init()`` expands in ``list_actions`` and DAP-qualified lookups, + # not only one registered through ``define_dynamic_action_provider``. + setattr(action, GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, self) self._dap_fn = dap_fn self._cache: tuple[DapValue, float] | None = None self._fetch_tasks: dict[asyncio.AbstractEventLoop, asyncio.Task[DapValue]] = {} diff --git a/packages/genkit/tests/genkit/ai/plugin_abi_test.py b/packages/genkit/tests/genkit/ai/plugin_abi_test.py new file mode 100644 index 000000000..bc8e0b6f6 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/plugin_abi_test.py @@ -0,0 +1,96 @@ +# 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 + +"""Plugin-author surface: unannotated models and DAPs returned from ``init()``.""" + +from typing import Any + +import pytest + +from genkit import Genkit, Message, ModelResponse, Part, Role +from genkit._core._action import GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR # noqa: TID251 +from genkit.model import Model, ModelContext, ModelRequest +from genkit.plugin_api import Action, ActionKind, DynamicActionProvider, Plugin + + +@pytest.mark.asyncio +async def test_unannotated_model_gets_model_request_from_raw_json() -> None: + """A Dev UI / CLI run passes JSON; an unannotated handler still sees ModelRequest.""" + seen: list[object] = [] + + async def fn(request, ctx: ModelContext) -> ModelResponse: # noqa: ANN001 # pyright: ignore[reportMissingParameterType] + seen.append(request) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(request.messages[0].text)])) + + model = Model('echo', fn) + out = await model.run({'messages': [{'role': 'user', 'content': [{'text': 'hi'}]}]}) + + assert isinstance(seen[0], ModelRequest) + assert out.response.text == 'hi' + + +class _DapPlugin(Plugin): + name = 'catalog' + + def __init__(self) -> None: + async def tool_fn(city: str) -> str: + return f'sunny in {city}' + + self._tool = Action(kind=ActionKind.TOOL, name='weather', fn=tool_fn) + + async def provide() -> dict[str, list[Action[Any, Any]]]: + return {'tool': [self._tool]} + + async def dap_fn(input: dict[str, Any]) -> dict[str, Any]: + return input + + self.dap = DynamicActionProvider( + Action(kind=ActionKind.DYNAMIC_ACTION_PROVIDER, name='live', fn=dap_fn), + provide, + ) + + async def init(self) -> list[Action]: + return [self.dap.action] + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + return None + + async def list_actions(self) -> list[Action]: + return [] + + +def test_dynamic_action_provider_stamps_its_action() -> None: + """A directly constructed provider is recoverable from its action.""" + plugin = _DapPlugin() + + assert getattr(plugin.dap.action, GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR) is plugin.dap + + +@pytest.mark.asyncio +async def test_dap_returned_from_plugin_init_is_listed_as_provider() -> None: + """``init()`` registers it under the plugin namespace and the catalog finds the provider. + + Children stay out of the catalog: ``catalog/live:tool/weather`` has a slash in + the provider segment, which neither the Python nor the JS key grammar accepts. + """ + plugin = _DapPlugin() + ai = Genkit(plugins=[plugin]) + + catalog = await ai._registry.list_actions() + + assert '/dynamic-action-provider/catalog/live' in catalog + action = await ai._registry.resolve_action(ActionKind.DYNAMIC_ACTION_PROVIDER, 'catalog/live') + assert getattr(action, GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR) is plugin.dap From f07e4b6a05fbf16105f86730c0b7220c68795cb5 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 16:44:19 -0600 Subject: [PATCH 4/5] test(py/openai): import ToolRequest from genkit.model --- packages/genkit-openai/tests/tool_calling_test.py | 3 +-- packages/genkit/src/genkit/_core/_model.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/genkit-openai/tests/tool_calling_test.py b/packages/genkit-openai/tests/tool_calling_test.py index 5c5c3ee7a..8445a5b72 100644 --- a/packages/genkit-openai/tests/tool_calling_test.py +++ b/packages/genkit-openai/tests/tool_calling_test.py @@ -161,8 +161,7 @@ def callback(chunk: ModelResponseChunk) -> None: async def test_scalar_tool_schema_is_wrapped_and_round_trips(make_completion: Callable[..., ChatCompletion]) -> None: """`async def tool(city: str)` sends an object schema and gets the bare string back.""" from genkit import Message, Part, Role - from genkit._core._typing import ToolRequest - from genkit.model import ToolDefinition + from genkit.model import ToolDefinition, ToolRequest completion = make_completion( choice={ diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 660227129..16980f2b1 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -1353,7 +1353,7 @@ class OutputConfig(GenkitModel): content_type: str | None = None @property - def schema(self) -> dict[str, Any] | None: # pyright: ignore[reportIncompatibleMethodOverride] + def schema(self) -> dict[str, Any] | None: # pyright: ignore[reportIncompatibleMethodOverride] # pyrefly: ignore[bad-override] """Read-only alias for ``json_schema``, matching the wire key and JS. Shadows Pydantic's deprecated ``BaseModel.schema()`` classmethod so From 56b89372a56f61fcff4de00261ddaa84c63439c4 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 23:16:32 -0600 Subject: [PATCH 5/5] fix(py): wrap $ref/$defs tool schemas, unwrap streamed scalar tool input, type unannotated model config - genkit-openai: a root $ref is judged by its target, so an Enum input is wrapped; $defs stay at the wrapper root so refs still resolve (list[Enum], Optional[Enum]). - genkit-openai: stream chunks for a wrapped tool carry the bare value, matching response.message, instead of '{"input": ...}' fragments. - Model: an unannotated handler with a Pydantic config_schema gets ModelRequest[Config], so request.config is the config model. - Drop the now-dead setattr in define_dynamic_action_provider. --- .../src/genkit_openai/_models/_model.py | 91 ++++++++++++++++--- .../genkit-openai/tests/tool_calling_test.py | 70 ++++++++++++++ packages/genkit/src/genkit/_ai/_model.py | 8 +- packages/genkit/src/genkit/_core/_registry.py | 9 +- .../genkit/tests/genkit/ai/plugin_abi_test.py | 27 +++++- 5 files changed, 182 insertions(+), 23 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index ab4454420..ec00050c1 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -246,19 +246,56 @@ def _finish_state( # The field a non-object tool input rides under on the wire, as in genkit-google-genai. _TOOL_INPUT_FIELD = 'input' +# Definitions a root ``$ref`` points into. They stay at the root when the +# schema is wrapped so ``#/$defs/...`` still resolves. +_DEFS_KEYS = ('$defs', 'definitions') + + +def _root_ref_target(schema: dict[str, Any]) -> dict[str, Any] | None: + """The definition a root ``$ref`` points at (``#/$defs/SpiceLevel``), or None.""" + ref = schema.get('$ref') + if not isinstance(ref, str): + return None + for key in _DEFS_KEYS: + prefix = f'#/{key}/' + defs = schema.get(key) + if ref.startswith(prefix) and isinstance(defs, dict): + target = cast(dict[str, Any], defs).get(ref[len(prefix) :]) + return cast(dict[str, Any], target) if isinstance(target, dict) else None + return None def _is_wrapped_tool_schema(schema: dict[str, Any] | None) -> bool: - """True for a non-empty schema that is not an object (``{'type': 'string'}``).""" + """True for a non-empty schema that is not an object (``{'type': 'string'}``). + + A root ``$ref`` is judged by its target: Pydantic emits one for an Enum + input, which is a string, not an object. + """ if not schema: return False schema_type = schema.get('type') if schema_type is None: - # anyOf/oneOf/$ref roots: only an object schema is safe to send as-is. - return not ('properties' in schema or '$ref' in schema) + 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) + # 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.""" + 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], + **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)) @@ -285,6 +322,21 @@ def _map_tool_requests(message: Message, wrapped: frozenset[str], wrap: bool) -> return message.model_copy(update={'content': content}) if changed else message +def _unwrapped_args_text(arguments: str) -> str: + """JSON text of the bare value in a wrapped call's ``'{"input": ...}'`` arguments. + + Arguments that are not exactly that shape are returned unchanged, as + ``_unwrap_tool_inputs`` leaves them. + """ + try: + parsed = json.loads(arguments) + except ValueError: + return arguments + if isinstance(parsed, dict) and set(cast(dict[str, Any], parsed)) == {_TOOL_INPUT_FIELD}: + return json.dumps(parsed[_TOOL_INPUT_FIELD], ensure_ascii=False) + return arguments + + 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] @@ -358,11 +410,7 @@ async def _get_tools_definition(self, tools: list[ToolDefinition]) -> list[dict] 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 = { - 'type': 'object', - 'properties': {_TOOL_INPUT_FIELD: parameters}, - 'required': [_TOOL_INPUT_FIELD], - } + parameters = _wrap_tool_schema(parameters) if parameters: parameters = _ensure_strict_json_schema(parameters, path=(), root=parameters) @@ -612,6 +660,7 @@ async def _generate_stream( stream = await self._openai_client.chat.completions.create(**openai_config) tool_calls: dict[int, Any] = {} + wrapped = _wrapped_tool_names(request.tools) reasoning_parts: list[Part] = [] text_parts: list[Part] = [] metadata: dict[str, Any] = {} @@ -666,9 +715,11 @@ async def _generate_stream( existing = tool_calls[tool_call.index] if hasattr(existing, 'function') and existing.function and tool_call.function: existing.function.arguments = (existing.function.arguments or '') + fragment - parts.append( - MessageConverter.tool_call_to_genkit(tool_calls[tool_call.index], args_segment=fragment) - ) + call = tool_calls[tool_call.index] + if call.function and call.function.name in wrapped: + # Fragments are pieces of '{"input": ...}'; sent unwrapped once complete. + continue + parts.append(MessageConverter.tool_call_to_genkit(call, args_segment=fragment)) if parts: callback(ModelResponseChunk(role=Role.MODEL, content=parts)) @@ -680,11 +731,27 @@ async def _generate_stream( details={'usage': _usage_from_completion(usage).model_dump(exclude_none=True)}, ) + # A stream consumer joining tool_request.input fragments sees the bare + # value, same as response.message, not the '{"input": ...}' wire shape. + held = [c for c in tool_calls.values() if c.function and c.function.name in wrapped] + if held: + callback( + ModelResponseChunk( + role=Role.MODEL, + content=[ + MessageConverter.tool_call_to_genkit( + c, args_segment=_unwrapped_args_text(c.function.arguments or '') + ) + for c in held + ], + ) + ) + accumulated_content: list[Part] = [*reasoning_parts, *text_parts] if tool_calls: message = _unwrap_tool_inputs( MessageConverter.to_genkit(DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL})), - _wrapped_tool_names(request.tools), + wrapped, ) accumulated_content.extend(message.content) diff --git a/packages/genkit-openai/tests/tool_calling_test.py b/packages/genkit-openai/tests/tool_calling_test.py index 8445a5b72..1d454b7fa 100644 --- a/packages/genkit-openai/tests/tool_calling_test.py +++ b/packages/genkit-openai/tests/tool_calling_test.py @@ -19,6 +19,7 @@ import json from collections.abc import Callable from functools import reduce +from typing import cast from unittest.mock import AsyncMock, MagicMock import pytest @@ -209,3 +210,72 @@ async def test_scalar_tool_schema_is_wrapped_and_round_trips(make_completion: Ca assert response.message is not None assert response.message.content[0].tool_request is not None assert response.message.content[0].tool_request.input == 'Paris' + + +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 + + spice = {'enum': ['mild', 'hot'], 'type': 'string'} + enum_root = {'$defs': {'SpiceLevel': spice}, '$ref': '#/$defs/SpiceLevel'} + order = { + '$defs': {'Order': {'type': 'object', 'properties': {'dish': {'type': 'string'}}}}, + '$ref': '#/$defs/Order', + } + 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) == { + 'type': 'object', + 'properties': {'input': {'$ref': '#/$defs/SpiceLevel'}}, + 'required': ['input'], + '$defs': {'SpiceLevel': spice}, + } + + +@pytest.mark.asyncio +async def test_stream_of_scalar_tool_call_sends_unwrapped_input(sample_request: ModelRequest) -> None: + """Joined tool_request.input chunks match response.message: the bare value, not {"input": ...}.""" + from genkit.model import ToolDefinition + + def tool_chunk(args: str) -> object: + call = MagicMock(id='call1', index=0) + call.function.name = 'current_weather' + call.function.arguments = args + delta = MagicMock(content=None, role=None, tool_calls=[call], reasoning_content=None, refusal=None) + return MagicMock(choices=[MagicMock(delta=delta, finish_reason=None, model_extra={})], usage=None) + + class Stream: + def __init__(self) -> None: + self._chunks = iter([tool_chunk(''), tool_chunk('{"input": "Pa'), tool_chunk('ris"}')]) + + def __aiter__(self) -> 'Stream': + return self + + async def __anext__(self) -> object: + try: + return next(self._chunks) + except StopIteration: + raise StopAsyncIteration from None + + mock_client = MagicMock() + mock_client.chat.completions.create = AsyncMock(return_value=Stream()) + model = OpenAIModel(model='gpt-4', client=mock_client) + request = sample_request.model_copy( + update={ + 'tools': [ToolDefinition(name='current_weather', description='Weather', input_schema={'type': 'string'})] + } + ) + streamed: list[ModelResponseChunk] = [] + + response = await model._generate_stream(request, streamed.append) + + parts = [p for c in streamed for p in c.content if p.tool_request is not None] + joined = ''.join(cast(str, p.tool_request.input) for p in parts if p.tool_request is not None) + assert json.loads(joined) == 'Paris' + assert response.message is not None + final_request = response.message.content[-1].tool_request + assert final_request is not None + assert final_request.input == 'Paris' diff --git a/packages/genkit/src/genkit/_ai/_model.py b/packages/genkit/src/genkit/_ai/_model.py index bf3d3444f..1d12d8388 100644 --- a/packages/genkit/src/genkit/_ai/_model.py +++ b/packages/genkit/src/genkit/_ai/_model.py @@ -491,12 +491,16 @@ def __init__( model_options = _model_options(name=name, info=info, config_schema=config_schema, metadata=metadata) model_meta: dict[str, object] = metadata.copy() if metadata else {} model_meta['model'] = model_options + config_class = python_config_schema(config_schema) + # Built at runtime, so checkers can't read ``ModelRequest[config_class]`` as a type. + request_type = cast(Any, ModelRequest)[config_class] if config_class is not None else ModelRequest super().__init__( kind=ActionKind.MODEL, name=name, # An unannotated request parameter would get the raw JSON dict from - # a Dev UI or CLI run; give it ModelRequest, like Embedder does. - fn=with_request_annotation(fn, ModelRequest, kind=ActionKind.MODEL), + # a Dev UI or CLI run; give it ModelRequest (typed by config_schema + # when there is one), like Embedder does. + fn=with_request_annotation(fn, request_type, kind=ActionKind.MODEL), metadata=model_meta, description=get_func_description(fn, description), config_schema=config_schema, diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 94c009354..83c059a73 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -934,10 +934,5 @@ async def dap_action(input: DapMetadata) -> DapMetadata: metadata={**(metadata or {}), 'type': 'dynamic-action-provider'}, ) - dap = DynamicActionProvider(action, fn, cache_ttl_millis) - # Attach the provider to the registered Action so anyone holding the - # Action (e.g. ``Registry.resolve_action_by_key`` for a DAP-qualified key, - # or ``Registry.list_actions`` expanding children for reflection) can - # recover the cache and helpers via ``getattr(action, ATTR, None)``. - setattr(action, GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, dap) - return dap + # DynamicActionProvider stamps itself on ``action``. + return DynamicActionProvider(action, fn, cache_ttl_millis) diff --git a/packages/genkit/tests/genkit/ai/plugin_abi_test.py b/packages/genkit/tests/genkit/ai/plugin_abi_test.py index bc8e0b6f6..fdae8be1c 100644 --- a/packages/genkit/tests/genkit/ai/plugin_abi_test.py +++ b/packages/genkit/tests/genkit/ai/plugin_abi_test.py @@ -16,9 +16,10 @@ """Plugin-author surface: unannotated models and DAPs returned from ``init()``.""" -from typing import Any +from typing import Any, cast import pytest +from pydantic import BaseModel from genkit import Genkit, Message, ModelResponse, Part, Role from genkit._core._action import GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR # noqa: TID251 @@ -36,12 +37,34 @@ async def fn(request, ctx: ModelContext) -> ModelResponse: # noqa: ANN001 # py return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(request.messages[0].text)])) model = Model('echo', fn) - out = await model.run({'messages': [{'role': 'user', 'content': [{'text': 'hi'}]}]}) + # Raw JSON, as a Dev UI or CLI run sends it. + out = await model.run(cast(Any, {'messages': [{'role': 'user', 'content': [{'text': 'hi'}]}]})) assert isinstance(seen[0], ModelRequest) assert out.response.text == 'hi' +@pytest.mark.asyncio +async def test_unannotated_model_with_config_schema_gets_typed_config() -> None: + """With config_schema, an unannotated handler's request.config is the config model, not a dict.""" + + class KitchenConfig(BaseModel): + temperature: float = 0.5 + + seen: list[object] = [] + + async def fn(request, ctx: ModelContext) -> ModelResponse: # noqa: ANN001 # pyright: ignore[reportMissingParameterType] + seen.append(request.config) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) + + model = Model('chef', fn, config_schema=KitchenConfig) + await model.run( + cast(Any, {'messages': [{'role': 'user', 'content': [{'text': 'hi'}]}], 'config': {'temperature': 0.9}}) + ) + + assert seen == [KitchenConfig(temperature=0.9)] + + class _DapPlugin(Plugin): name = 'catalog'