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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 135 additions & 7 deletions packages/genkit-openai/src/genkit_openai/_models/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,109 @@ 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'
# 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'}``).

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:
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))


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 _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]


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."""

Expand Down Expand Up @@ -304,6 +407,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):
# Function parameters must be an object; a scalar tool input
# (``async def tool(city: str)``) rides under one field.
parameters = _wrap_tool_schema(parameters)
if parameters:
parameters = _ensure_strict_json_schema(parameters, path=(), root=parameters)

Expand Down Expand Up @@ -445,7 +552,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.
Expand Down Expand Up @@ -513,7 +621,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')
Expand Down Expand Up @@ -552,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] = {}
Expand Down Expand Up @@ -606,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))
Expand All @@ -620,10 +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 = MessageConverter.to_genkit(
DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL})
message = _unwrap_tool_inputs(
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
MessageConverter.to_genkit(DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL})),
wrapped,
)
accumulated_content.extend(message.content)

Expand Down
124 changes: 124 additions & 0 deletions packages/genkit-openai/tests/tool_calling_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -155,3 +156,126 @@ 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.model import ToolDefinition, ToolRequest

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'


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'
9 changes: 8 additions & 1 deletion packages/genkit/src/genkit/_ai/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
ActionKind,
ModelContext,
get_func_description,
with_request_annotation,
)
from genkit._core._config_check import (
check_config_values,
Expand Down Expand Up @@ -490,10 +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,
fn=fn,
# An unannotated request parameter would get the raw JSON dict from
# 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,
Expand Down
5 changes: 5 additions & 0 deletions packages/genkit/src/genkit/_core/_dap.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from typing import Any

from genkit._core._action import (
GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR,
Action,
ActionKind,
create_action_key,
Expand Down Expand Up @@ -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)
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
self._dap_fn = dap_fn
self._cache: tuple[DapValue, float] | None = None
self._fetch_tasks: dict[asyncio.AbstractEventLoop, asyncio.Task[DapValue]] = {}
Expand Down
9 changes: 9 additions & 0 deletions packages/genkit/src/genkit/_core/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] # pyrefly: ignore[bad-override]
"""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.
Expand Down
Loading
Loading