Skip to content

Commit 376e3e1

Browse files
committed
Fix #980 Chat Completions: fails with function name for tool_choice parameter w/ streaming enabled
1 parent c5d5010 commit 376e3e1

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/agents/models/openai_chatcompletions.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
import time
55
from collections.abc import AsyncIterator
6-
from typing import TYPE_CHECKING, Any, Literal, cast, overload
6+
from typing import TYPE_CHECKING, Any, Literal, overload
77

88
from openai import NOT_GIVEN, AsyncOpenAI, AsyncStream
99
from openai.types import ChatModel
@@ -28,6 +28,7 @@
2828
from .chatcmpl_stream_handler import ChatCmplStreamHandler
2929
from .fake_id import FAKE_RESPONSES_ID
3030
from .interface import Model, ModelTracing
31+
from .openai_responses import Converter as OpenAIResponsesConverter
3132

3233
if TYPE_CHECKING:
3334
from ..model_settings import ModelSettings
@@ -296,15 +297,27 @@ async def _fetch_response(
296297
if isinstance(ret, ChatCompletion):
297298
return ret
298299

300+
responses_tool_choice = OpenAIResponsesConverter.convert_tool_choice(
301+
model_settings.tool_choice
302+
)
303+
if responses_tool_choice is None or responses_tool_choice == NOT_GIVEN:
304+
# For Responses API data compatibility with Chat Completions patterns,
305+
# we need to set "none" if tool_choice is absent.
306+
# Without this fix, you'll get the following error:
307+
# pydantic_core._pydantic_core.ValidationError: 4 validation errors for Response
308+
# tool_choice.literal['none','auto','required']
309+
# Input should be 'none', 'auto' or 'required'
310+
# [type=literal_error, input_value=NOT_GIVEN, input_type=NotGiven]
311+
# see also: https://github.com/openai/openai-agents-python/issues/980
312+
responses_tool_choice = "none"
313+
299314
response = Response(
300315
id=FAKE_RESPONSES_ID,
301316
created_at=time.time(),
302317
model=self.model,
303318
object="response",
304319
output=[],
305-
tool_choice=cast(Literal["auto", "required", "none"], tool_choice)
306-
if tool_choice != NOT_GIVEN
307-
else "auto",
320+
tool_choice=responses_tool_choice, # type: ignore[arg-type]
308321
top_p=model_settings.top_p,
309322
temperature=model_settings.temperature,
310323
tools=[],

0 commit comments

Comments
 (0)