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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/gen/PYPIDESCRIPTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,19 @@ You can install a subset of the extra libraries (without langchain support) by s

## Configuration, Usage

### OpenAI parameter compatibility

The native OpenAI proxy and its LangChain wrapper omit `temperature` for
GPT-5/6 reasoning models, including versioned and `-pro`/`-sol` variants, as
well as o-series and Cohere reasoning models. Temperature is preserved for
GPT chat variants, GPT-6 Astra, and newer GPT models when reasoning effort is
explicitly `none` (`reasoning_effort` in Chat Completions or `reasoning.effort`
in Responses). The original GPT-5, GPT-5 mini/nano, o-series, and Cohere
reasoning models remain filtered regardless of the requested effort.

The Responses API proxy always omits `n`, which is a Chat Completions-only
parameter. This applies to synchronous and asynchronous `create` and `parse`
calls, including requests routed to Responses by LangChain. Chat Completions
continues to forward `n` except for Cohere models.

Please refer to the official documentation hosted on [help.sap.com](https://help.sap.com/doc/generative-ai-hub-sdk/CLOUD/en-US/index.html) for details on how to configure and use the SAP Cloud SDK for AI (Python).
91 changes: 55 additions & 36 deletions packages/gen/gen_ai_hub/proxy/native/openai/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,43 @@
# Model name patterns
COHERE_MODEL_PATTERN = r"^cohere--"
O_SERIES_MODEL_PATTERN = r"^o\d+"
GPT_5_MODEL_PATTERN = r"^gpt-5(-mini|-nano)?$"
GPT_5_MODEL_PATTERN = r"^gpt-5(?:-mini|-nano)?(?:-\d{4}-\d{2}-\d{2})?$"
GPT_REASONING_MODEL_PATTERN = r"^gpt-(?:5|6)(?:[.-]|$)"
GPT_CHAT_MODEL_PATTERN = r"^gpt-(?:5|6)(?:\.\d+)?-chat(?:-|$)"
# Azure documents Astra as an exception to reasoning temperature restrictions.
# https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/reasoning
GPT_ASTRA_MODEL_PATTERN = r"^gpt-6-astra(?:-|$)"
COHERE_REASONING_MODEL_PATTERN = r"^cohere--command-.*-reasoning$"


def _supports_temperature(model_name: str, reasoning_effort: Optional[str] = None) -> bool:
"""Check temperature support, allowing explicit non-reasoning GPT requests.

GPT-5/6 reasoning variants are filtered by default. Chat variants, Astra,
and newer GPT models requested with reasoning effort ``none`` are preserved.
The original GPT-5, o-series and Cohere reasoning models remain filtered.
"""
if (re.search(O_SERIES_MODEL_PATTERN, model_name)
or re.search(GPT_5_MODEL_PATTERN, model_name)
or re.search(COHERE_REASONING_MODEL_PATTERN, model_name)):
return False
if (re.search(GPT_REASONING_MODEL_PATTERN, model_name)
and not re.search(GPT_CHAT_MODEL_PATTERN, model_name)
and not re.search(GPT_ASTRA_MODEL_PATTERN, model_name)):
return reasoning_effort == 'none'
return True


def _filter_temperature(model_name: str, kwargs: dict) -> None:
"""Handle both Chat Completions and Responses reasoning parameter formats."""
reasoning_effort = kwargs.get('reasoning_effort')
reasoning = kwargs.get('reasoning')
if isinstance(reasoning, dict):
reasoning_effort = reasoning.get('effort')
if not _supports_temperature(model_name, reasoning_effort):
kwargs.pop('temperature', None)


ResponseFormatT = TypeVar('ResponseFormatT')
_current_deployment = contextvars.ContextVar('current_deployment')

Expand Down Expand Up @@ -329,9 +363,7 @@ def _prepare_chat(self, config_id, config_name, deployment_id, kwargs, model, mo
)
deployment = proxy_client.select_deployment(**model_identification)
model_name = deployment.model_name or '???'
# Reasoning models do not support temperature
if not self.supports_temperature(model_name) and 'temperature' in kwargs:
kwargs.pop('temperature')
_filter_temperature(model_name, kwargs)
# Cohere models do not support the 'n' and 'max_completion_tokens' parameters
if model_name and re.search(COHERE_MODEL_PATTERN, model_name):
kwargs.pop('n', None)
Expand Down Expand Up @@ -416,17 +448,15 @@ def parse(self,
@staticmethod
def supports_temperature(model_name: str) -> bool:
"""Checks if the given model supports the `temperature` parameter.
Reasoning models do not support temperature e.g., o1[-mini], o3[-mini], 5[-mini, -nano],
cohere--command-a-reasoning
Reasoning models (o-series, GPT-5/6 and Cohere reasoning) are filtered
by default; GPT chat variants support temperature.

:param model_name: the name of the model to check.
:type model_name: str
:return: True if the model supports `temperature`, False otherwise
:rtype: bool
"""
return (not re.search(O_SERIES_MODEL_PATTERN, model_name)
and not re.search(GPT_5_MODEL_PATTERN, model_name)
and not re.search(COHERE_REASONING_MODEL_PATTERN, model_name))
return _supports_temperature(model_name)


class Responses(Responses_):
Expand Down Expand Up @@ -463,12 +493,10 @@ def _prepare_chat(self, config_id, config_name, deployment_id, kwargs, model, mo
)
deployment = proxy_client.select_deployment(**model_identification)
model_name = deployment.model_name or '???'
# Reasoning models do not support temperature
if not self.supports_temperature(model_name) and 'temperature' in kwargs:
kwargs.pop('temperature')
# Cohere models do not support the 'n' and 'max_completion_tokens' parameters
_filter_temperature(model_name, kwargs)
# The Responses API never supports the Chat Completions 'n' parameter.
kwargs.pop('n', None)
if model_name and re.search(COHERE_MODEL_PATTERN, model_name):
kwargs.pop('n', None)
kwargs.pop('max_completion_tokens', None)
return deployment, model_name

Expand Down Expand Up @@ -560,17 +588,15 @@ def parse(
@staticmethod
def supports_temperature(model_name: str) -> bool:
"""Checks if the given model supports the `temperature` parameter.
Reasoning models do not support temperature e.g., o1[-mini], o3[-mini], 5[-mini, -nano],
cohere--command-a-reasoning
Reasoning models (o-series, GPT-5/6 and Cohere reasoning) are filtered
by default; GPT chat variants support temperature.

:param model_name: the name of the model to check.
:type model_name: str
:return: True if the model supports `temperature`, False otherwise
:rtype: bool
"""
return (not re.search(O_SERIES_MODEL_PATTERN, model_name)
and not re.search(GPT_5_MODEL_PATTERN, model_name)
and not re.search(COHERE_REASONING_MODEL_PATTERN, model_name))
return _supports_temperature(model_name)


class AsyncChat(AsyncChat_):
Expand Down Expand Up @@ -606,9 +632,7 @@ def _prepare_chat(self, config_id, config_name, deployment_id, kwargs, model, mo
deployment = proxy_client.select_deployment(**model_identification)
model_name = deployment.model_name or '???'

# Reasoning models do not support temperature
if not self.supports_temperature(model_name) and 'temperature' in kwargs:
kwargs.pop('temperature')
_filter_temperature(model_name, kwargs)
# Cohere models do not support the 'n' and 'max_completion_tokens' parameters
if model_name and re.search(COHERE_MODEL_PATTERN, model_name):
kwargs.pop('n', None)
Expand Down Expand Up @@ -695,16 +719,15 @@ async def parse(self,
@staticmethod
def supports_temperature(model_name: str) -> bool:
"""Checks if the given model supports the `temperature` parameter.
Reasoning models do not support temperature e.g., o1[-mini], o3[-mini], cohere--command-a-reasoning
Reasoning models (o-series, GPT-5/6 and Cohere reasoning) are filtered
by default; GPT chat variants support temperature.

:param model_name: the name of the model to check.
:type model_name: str
:return: True if the model supports `temperature`, False otherwise
:rtype: bool
"""
return (not re.search(O_SERIES_MODEL_PATTERN, model_name)
and not re.search(GPT_5_MODEL_PATTERN, model_name)
and not re.search(COHERE_REASONING_MODEL_PATTERN, model_name))
return _supports_temperature(model_name)


class AsyncResponses(AsyncResponses_):
Expand Down Expand Up @@ -742,12 +765,10 @@ def _prepare_chat(self, config_id, config_name, deployment_id, kwargs, model, mo
)
deployment = proxy_client.select_deployment(**model_identification)
model_name = deployment.model_name or '???'
# Reasoning models do not support temperature
if not self.supports_temperature(model_name) and 'temperature' in kwargs:
kwargs.pop('temperature')
# Cohere models do not support the 'n' and 'max_completion_tokens' parameters
_filter_temperature(model_name, kwargs)
# The Responses API never supports the Chat Completions 'n' parameter.
kwargs.pop('n', None)
if model_name and re.search(COHERE_MODEL_PATTERN, model_name):
kwargs.pop('n', None)
kwargs.pop('max_completion_tokens', None)
return deployment, model_name

Expand Down Expand Up @@ -839,17 +860,15 @@ async def parse(
@staticmethod
def supports_temperature(model_name: str) -> bool:
"""Checks if the given model supports the `temperature` parameter.
Reasoning models do not support temperature e.g., o1[-mini], o3[-mini], 5[-mini, -nano],
cohere--command-a-reasoning
Reasoning models (o-series, GPT-5/6 and Cohere reasoning) are filtered
by default; GPT chat variants support temperature.

:param model_name: the name of the model to check.
:type model_name: str
:return: True if the model supports `temperature`, False otherwise
:rtype: bool
"""
return (not re.search(O_SERIES_MODEL_PATTERN, model_name)
and not re.search(GPT_5_MODEL_PATTERN, model_name)
and not re.search(COHERE_REASONING_MODEL_PATTERN, model_name))
return _supports_temperature(model_name)

class OpenAIWithRawResponse:
"""
Expand Down
189 changes: 189 additions & 0 deletions packages/gen/tests/proxy/native/test_openai_parameters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""Regression tests for parameter filtering at the OpenAI proxy boundary."""
import json
from datetime import datetime

import pytest
import respx
from httpx import Response
from pydantic import BaseModel

from gen_ai_hub.proxy.gen_ai_hub_proxy.client import Deployment
from gen_ai_hub.proxy.native.openai import AsyncOpenAI, OpenAI
from gen_ai_hub.proxy.native.openai.clients import (
AsyncChatCompletions,
AsyncResponses,
ChatCompletions,
Responses,
)
from gen_ai_hub.proxy.langchain.openai import ChatOpenAI
from tests.mock import (
OPENAI_RESPONSES_RESPONSE,
OPENAI_RESPONSES_RESPONSE_PARSE,
OPENAI_STRUCTRED_OUTPUTS_RESPONSE,
get_mocked_ai_core_client,
)


class PersonName(BaseModel):
first_name: str
last_name: str


@pytest.fixture
def proxy_client():
return get_mocked_ai_core_client(client_id='test-openai-parameters')


def add_deployment(proxy_client, model_name):
deployment = Deployment(
url=f'https://api.gen-ai.io/v2/inference/deployments/{model_name}',
deployment_id=f'{model_name}-deployment',
config_id=f'{model_name}-config',
config_name=f'{model_name}-config',
model_name=model_name,
model_version='latest',
created_at=datetime.now(),
)
proxy_client._deployments.append(deployment)
return deployment


@pytest.mark.parametrize('resource_class', [
ChatCompletions, AsyncChatCompletions, Responses, AsyncResponses,
])
@pytest.mark.parametrize('model_name,supported', [
('o1', False),
('o3-mini', False),
('gpt-5', False),
('gpt-5-mini', False),
('gpt-5-nano', False),
('gpt-5-2025-08-07', False),
('gpt-5.1', False),
('gpt-5.2-pro', False),
('gpt-5.6-sol', False),
('gpt-6', False),
('gpt-6-sol', False),
('gpt-6.1-sol', False),
('gpt-6-astra', True),
('gpt-6-astra-2026-09-24', True),
('cohere--command-a-reasoning', False),
('gpt-4o-mini', True),
('gpt-4.1', True),
('gpt-5-chat-latest', True),
('gpt-5.1-chat-latest', True),
('cohere--command-a', True),
('custom-model', True),
('gpt-50', True),
('gpt-60', True),
])
def test_supports_temperature(resource_class, model_name, supported):
assert resource_class.supports_temperature(model_name) is supported


@pytest.mark.parametrize('resource_name', ['responses', 'chat.completions'])
@pytest.mark.parametrize('method', ['create', 'parse'])
@pytest.mark.parametrize('model_name,reasoning_effort,supported', [
('gpt-6.1-sol', None, False),
('gpt-5.2', 'high', False),
('gpt-5.2', 'none', True),
('gpt-6-sol', 'none', True),
('gpt-6-astra', None, True),
('gpt-6-astra', 'high', True),
('gpt-5', 'none', False),
('o3', 'none', False),
('gpt-4o-mini', None, True),
('gpt-5-chat-latest', None, True),
('cohere--command-a-reasoning', None, False),
])
@pytest.mark.parametrize('is_async', [False, True])
@pytest.mark.asyncio
async def test_request_parameter_filtering(
proxy_client, resource_name, method, model_name, reasoning_effort, supported, is_async,
):
deployment = add_deployment(proxy_client, model_name)
client = (AsyncOpenAI if is_async else OpenAI)(proxy_client=proxy_client)
is_responses = resource_name == 'responses'
resource = client.responses if is_responses else client.chat.completions
kwargs = {'deployment_id': deployment.deployment_id, 'temperature': 0, 'n': 1}
if is_responses:
kwargs['input'] = 'Tell me about John Doe.'
kwargs['max_output_tokens'] = 128
if reasoning_effort is not None:
kwargs['reasoning'] = {'effort': reasoning_effort}
response_body = OPENAI_RESPONSES_RESPONSE_PARSE
if method == 'parse':
kwargs['text_format'] = PersonName
else:
kwargs['messages'] = [{'role': 'user', 'content': 'Tell me about John Doe.'}]
kwargs['max_completion_tokens'] = 128
if reasoning_effort is not None:
kwargs['reasoning_effort'] = reasoning_effort
response_body = OPENAI_STRUCTRED_OUTPUTS_RESPONSE
if method == 'parse':
kwargs['response_format'] = PersonName

with respx.mock:
route = respx.post(deployment.prediction_url).mock(
return_value=Response(200, json=response_body),
)
try:
result = getattr(resource, method)(**kwargs)
if is_async:
result = await result
assert result is not None
payload = json.loads(route.calls.last.request.content)
assert ('temperature' in payload) is supported
if supported:
assert payload['temperature'] == 0
assert ('n' in payload) is (not is_responses and not model_name.startswith('cohere--'))
token_parameter = 'max_output_tokens' if is_responses else 'max_completion_tokens'
assert (token_parameter in payload) is (is_responses or not model_name.startswith('cohere--'))
if reasoning_effort is not None:
if is_responses:
assert payload['reasoning']['effort'] == reasoning_effort
else:
assert payload['reasoning_effort'] == reasoning_effort
if method == 'parse':
parsed = result.output_parsed if is_responses else result.choices[0].message.parsed
assert isinstance(parsed, PersonName)
finally:
if is_async:
await client.close()
else:
client.close()


@pytest.mark.parametrize('is_async', [False, True])
@pytest.mark.asyncio
async def test_langchain_reasoning_model_with_tools(proxy_client, is_async):
model_name = 'gpt-6.1-sol'
deployment = add_deployment(proxy_client, model_name)
llm = ChatOpenAI(proxy_client=proxy_client, proxy_model_name=model_name, temperature=0)
tool = {
'type': 'function',
'function': {
'name': 'get_weather',
'description': 'Get the weather in a city.',
'parameters': {
'type': 'object',
'properties': {'city': {'type': 'string'}},
'required': ['city'],
},
},
}
with respx.mock:
route = respx.post(deployment.prediction_url).mock(
return_value=Response(200, json=OPENAI_RESPONSES_RESPONSE),
)
try:
bound = llm.bind_tools([tool])
result = await bound.ainvoke('hello') if is_async else bound.invoke('hello')
assert result.content
payload = json.loads(route.calls.last.request.content)
assert 'n' not in payload
assert 'temperature' not in payload
assert payload['tools'][0]['name'] == 'get_weather'
assert 'input' in payload
finally:
llm.root_client.close()
await llm.root_async_client.close()