Skip to content

Commit f9cd68d

Browse files
authored
Raise error when WebSearchTool is used with OpenAIChatModel and unsupported model (#2824)
1 parent 29a1c4a commit f9cd68d

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

pydantic_ai_slim/pydantic_ai/models/openai.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,12 @@ def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[c
568568
def _get_web_search_options(self, model_request_parameters: ModelRequestParameters) -> WebSearchOptions | None:
569569
for tool in model_request_parameters.builtin_tools:
570570
if isinstance(tool, WebSearchTool): # pragma: no branch
571+
if not OpenAIModelProfile.from_profile(self.profile).openai_chat_supports_web_search:
572+
raise UserError(
573+
f'WebSearchTool is not supported with `OpenAIChatModel` and model {self.model_name!r}. '
574+
f'Please use `OpenAIResponsesModel` instead.'
575+
)
576+
571577
if tool.user_location:
572578
return WebSearchOptions(
573579
search_context_size=tool.search_context_size,
@@ -579,7 +585,7 @@ def _get_web_search_options(self, model_request_parameters: ModelRequestParamete
579585
return WebSearchOptions(search_context_size=tool.search_context_size)
580586
else:
581587
raise UserError(
582-
f'`{tool.__class__.__name__}` is not supported by `OpenAIModel`. If it should be, please file an issue.'
588+
f'`{tool.__class__.__name__}` is not supported by `OpenAIChatModel`. If it should be, please file an issue.'
583589
)
584590

585591
async def _map_messages(self, messages: list[ModelMessage]) -> list[chat.ChatCompletionMessageParam]:

pydantic_ai_slim/pydantic_ai/profiles/openai.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ class OpenAIModelProfile(ModelProfile):
3838
openai_system_prompt_role: OpenAISystemPromptRole | None = None
3939
"""The role to use for the system prompt message. If not provided, defaults to `'system'`."""
4040

41+
openai_chat_supports_web_search: bool = False
42+
"""Whether the model supports web search in Chat Completions API."""
43+
4144
def __post_init__(self): # pragma: no cover
4245
if not self.openai_supports_sampling_settings:
4346
warnings.warn(
@@ -50,6 +53,9 @@ def __post_init__(self): # pragma: no cover
5053
def openai_model_profile(model_name: str) -> ModelProfile:
5154
"""Get the model profile for an OpenAI model."""
5255
is_reasoning_model = model_name.startswith('o') or model_name.startswith('gpt-5')
56+
# Check if the model supports web search (only specific search-preview models)
57+
supports_web_search = '-search-preview' in model_name
58+
5359
# Structured Outputs (output mode 'native') is only supported with the gpt-4o-mini, gpt-4o-mini-2024-07-18, and gpt-4o-2024-08-06 model snapshots and later.
5460
# We leave it in here for all models because the `default_structured_output_mode` is `'tool'`, so `native` is only used
5561
# when the user specifically uses the `NativeOutput` marker, so an error from the API is acceptable.
@@ -77,6 +83,7 @@ def openai_model_profile(model_name: str) -> ModelProfile:
7783
supports_json_object_output=True,
7884
openai_unsupported_model_settings=openai_unsupported_model_settings,
7985
openai_system_prompt_role=openai_system_prompt_role,
86+
openai_chat_supports_web_search=supports_web_search,
8087
)
8188

8289

tests/models/test_openai.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from pydantic import AnyUrl, BaseModel, ConfigDict, Discriminator, Field, Tag
1414
from typing_extensions import NotRequired, TypedDict
1515

16-
from pydantic_ai import Agent, ModelHTTPError, ModelRetry, UnexpectedModelBehavior
16+
from pydantic_ai import Agent, ModelHTTPError, ModelRetry, UnexpectedModelBehavior, UserError
1717
from pydantic_ai.builtin_tools import WebSearchTool
1818
from pydantic_ai.messages import (
1919
AudioUrl,
@@ -2105,7 +2105,7 @@ async def test_openai_web_search_tool_model_not_supported(allow_model_requests:
21052105
m, instructions='You are a helpful assistant.', builtin_tools=[WebSearchTool(search_context_size='low')]
21062106
)
21072107

2108-
with pytest.raises(ModelHTTPError, match='.*Web search options not supported with this model.*'):
2108+
with pytest.raises(UserError, match=r'WebSearchTool is not supported with `OpenAIChatModel` and model.*'):
21092109
await agent.run('What day is today?')
21102110

21112111

0 commit comments

Comments
 (0)