Skip to content
Closed
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
3 changes: 2 additions & 1 deletion packages/genkit-openai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ For a server that isn't OpenAI, use `OpenAICompatible` below.

On Chat Completions, some reasoning models, such as `gpt-6-sol`, accept
function tools only with `reasoning_effort='none'` and do not default to it.
Set it when you pass tools:
Set it when you pass tools; without it, `OpenAI` fails before the request with
`INVALID_ARGUMENT` (an OpenAI-compatible host is not checked):

```python
res = await ai.generate(
Expand Down
34 changes: 34 additions & 0 deletions packages/genkit-openai/src/genkit_openai/_models/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""OpenAI Compatible Models for Genkit."""

import json
import re
from collections.abc import Callable
from typing import Any, cast

Expand Down Expand Up @@ -84,6 +85,22 @@ def _uses_max_completion_tokens(model: str | None) -> bool:
return model_id.startswith(reasoning_prefixes) or any(f'-{prefix}' in model_id for prefix in reasoning_prefixes)


# Chat Completions models that take function tools only with reasoning_effort='none'
# (a dated snapshot, -YYYY-MM-DD, counts as the same model).
_TOOLS_NEED_NO_REASONING = re.compile(
r'(gpt-5\.6-(sol|terra|luna)|gpt-6-(sol|luna)|gpt-6\.1-terra)(-\d{4}-\d{2}-\d{2})?'
)
_TOOLS_NEED_NO_REASONING_MESSAGE = (
"{model} accepts function tools on Chat Completions only with reasoning_effort='none'. "
"Set config={{'reasoning_effort': 'none'}} when you pass tools."
)


def _tools_need_no_reasoning(model: str | None) -> bool:
"""Whether ``model`` rejects function tools unless ``reasoning_effort='none'``."""
return bool(model) and _TOOLS_NEED_NO_REASONING.fullmatch(_base_id(str(model).lower())) is not None


def _openai_create_kwargs(*, config: OpenAIConfig, model: str | None = None) -> dict[str, Any]:
"""Kwargs for chat.completions.create().

Expand Down Expand Up @@ -404,6 +421,7 @@ def __init__(
*,
supports: ModelSupports | None = None,
mistral: bool | None = None,
openai: bool = False,
) -> None:
"""Initializes the OpenAIModel instance with the specified model and OpenAI client parameters.

Expand All @@ -416,11 +434,14 @@ 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.
openai: The endpoint is OpenAI's own, whose model rules apply. Other
OpenAI-compatible hosts may serve the same ids under different rules.
"""
self._model = model
self._openai_client = client
self._supports = supports
self._mistral = is_mistral(client) if mistral is None else mistral
self._openai = openai and not self._mistral

@property
def name(self) -> str:
Expand Down Expand Up @@ -654,7 +675,20 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict:
if config.version:
openai_config['model'] = config.version
effective_model = config.model or config.version or self._model
if request.tools and self._openai and _tools_need_no_reasoning(effective_model):
# extra goes out as extra_body, which replaces the top-level field.
effort = (config.extra or {}).get('reasoning_effort', config.reasoning_effort)
if str(getattr(effort, 'value', effort)) != 'none':
raise GenkitError(
status='INVALID_ARGUMENT',
message=_TOOLS_NEED_NO_REASONING_MESSAGE.format(model=effective_model),
)
openai_config.update(_openai_create_kwargs(config=config, model=effective_model))
elif request.tools and self._openai and _tools_need_no_reasoning(self._model):
raise GenkitError(
status='INVALID_ARGUMENT',
message=_TOOLS_NEED_NO_REASONING_MESSAGE.format(model=self._model),
)
if self._mistral:
openai_config = mistral_chat_body(openai_config, top_k=top_k)
return openai_config
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit-openai/src/genkit_openai/_openai_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ 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), openai=True)
)
return await openai_model.generate(request, ctx)

Expand Down
138 changes: 138 additions & 0 deletions packages/genkit-openai/tests/openai_tools_reasoning_effort_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# 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


"""Function tools on Chat Completions reasoning models that accept them only with reasoning_effort='none'."""

import json
from typing import Any

import httpx
import pytest
from genkit_openai import OpenAI, OpenAICompatible

from genkit import FinishReason, Genkit

_ANSWER = {
'id': 'chatcmpl-1',
'object': 'chat.completion',
'created': 0,
'model': 'x',
'choices': [{'index': 0, 'finish_reason': 'stop', 'message': {'role': 'assistant', 'content': 'Sunny.'}}],
'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2},
}


def _genkit(bodies: list[dict[str, Any]], *, compatible: bool = False) -> Genkit:
def handler(request: httpx.Request) -> httpx.Response:
bodies.append(json.loads(request.content))
return httpx.Response(200, json=_ANSWER)

options = {'http_client': httpx.AsyncClient(transport=httpx.MockTransport(handler)), 'max_retries': 0}
plugin = (
OpenAICompatible(name='gw', base_url='https://gw.example.com/v1', api_key='k', client_options=options)
if compatible
else OpenAI(api_key='sk-plugin', client_options=options)
)
ai = Genkit(plugins=[plugin])

@ai.tool(name='get_weather')
async def get_weather(city: str) -> str:
return f'{city}: sunny'

return ai


@pytest.mark.asyncio
@pytest.mark.parametrize('model', ['gpt-5.6-sol', 'gpt-5.6-luna', 'gpt-6-sol', 'gpt-6.1-terra', 'gpt-6-sol-2026-03-01'])
@pytest.mark.parametrize('config', [None, {'reasoning_effort': 'low'}, {'extra': {'reasoning_effort': 'high'}}])
async def test_tools_without_none_effort_fail_locally(model: str, config: dict[str, Any] | None) -> None:
"""Tools without reasoning_effort='none' fail with INVALID_ARGUMENT before any request goes out."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies)

response = await ai.generate(
model=f'openai/{model}', prompt='Weather in Paris?', tools=['get_weather'], config=config
)

assert response.finish_reason == FinishReason.FAILED
assert response.error.status == 'INVALID_ARGUMENT'
assert "reasoning_effort='none'" in str(response.finish_message)
assert bodies == []


@pytest.mark.asyncio
@pytest.mark.parametrize('config', [{'reasoning_effort': 'none'}, {'extra': {'reasoning_effort': 'none'}}])
async def test_tools_with_none_effort_are_sent(config: dict[str, Any]) -> None:
"""reasoning_effort='none' in config or extra lets the request through."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies)

await ai.generate(model='openai/gpt-6-sol', prompt='Weather in Paris?', tools=['get_weather'], config=config)

assert [t['function']['name'] for t in bodies[0]['tools']] == ['get_weather']
assert bodies[0]['reasoning_effort'] == 'none'


@pytest.mark.asyncio
async def test_extra_overrides_config_effort() -> None:
"""extra replaces the top-level field on the wire, so extra decides."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies)

response = await ai.generate(
model='openai/gpt-6-sol',
prompt='Weather in Paris?',
tools=['get_weather'],
config={'reasoning_effort': 'none', 'extra': {'reasoning_effort': 'high'}},
)

assert response.finish_reason == FinishReason.FAILED
assert bodies == []


@pytest.mark.asyncio
async def test_no_tools_no_check() -> None:
"""Without tools the request goes out untouched."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies)

await ai.generate(model='openai/gpt-6-sol', prompt='Hi')

assert 'tools' not in bodies[0]
assert 'reasoning_effort' not in bodies[0]


@pytest.mark.asyncio
async def test_other_models_are_not_checked() -> None:
"""A model outside the list keeps sending tools as before."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies)

await ai.generate(model='openai/gpt-4o', prompt='Weather in Paris?', tools=['get_weather'])

assert bodies[0]['tools']


@pytest.mark.asyncio
async def test_compatible_hosts_are_not_checked() -> None:
"""An OpenAI-compatible host may serve the same id under its own rules."""
bodies: list[dict[str, Any]] = []
ai = _genkit(bodies, compatible=True)

await ai.generate(model='gw/gpt-6-sol', prompt='Weather in Paris?', tools=['get_weather'])

assert bodies[0]['tools']