-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathopenai.py
More file actions
2888 lines (2504 loc) · 133 KB
/
openai.py
File metadata and controls
2888 lines (2504 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations as _annotations
import base64
import itertools
import json
import warnings
from collections.abc import AsyncIterable, AsyncIterator, Callable, Iterable, Sequence
from contextlib import asynccontextmanager
from dataclasses import dataclass, field, replace
from datetime import datetime
from functools import cached_property
from typing import Any, Literal, cast, overload
from pydantic import BaseModel, ValidationError
from pydantic_core import to_json
from typing_extensions import Never, assert_never, deprecated
from .. import ModelAPIError, ModelHTTPError, UnexpectedModelBehavior, _utils, usage
from .._output import DEFAULT_OUTPUT_TOOL_NAME, OutputObjectDefinition
from .._run_context import RunContext
from .._thinking_part import split_content_into_text_and_thinking
from .._utils import guard_tool_call_id as _guard_tool_call_id, now_utc as _now_utc, number_to_datetime
from ..builtin_tools import (
AbstractBuiltinTool,
CodeExecutionTool,
FileSearchTool,
ImageAspectRatio,
ImageGenerationTool,
MCPServerTool,
WebSearchTool,
)
from ..exceptions import UserError
from ..messages import (
AudioUrl,
BinaryContent,
BinaryImage,
BuiltinToolCallPart,
BuiltinToolReturnPart,
CachePoint,
DocumentUrl,
FilePart,
FinishReason,
ImageUrl,
ModelMessage,
ModelRequest,
ModelResponse,
ModelResponsePart,
ModelResponseStreamEvent,
PartStartEvent,
RetryPromptPart,
SystemPromptPart,
TextPart,
ThinkingPart,
ToolCallPart,
ToolReturnPart,
UserPromptPart,
VideoUrl,
)
from ..profiles import ModelProfile, ModelProfileSpec
from ..profiles.openai import OpenAIModelProfile, OpenAISystemPromptRole
from ..providers import Provider, infer_provider
from ..settings import ModelSettings
from ..tools import ToolDefinition
from . import (
Model,
ModelRequestParameters,
OpenAIChatCompatibleProvider,
OpenAIResponsesCompatibleProvider,
StreamedResponse,
check_allow_model_requests,
download_item,
get_user_agent,
)
try:
from openai import NOT_GIVEN, APIConnectionError, APIStatusError, AsyncOpenAI, AsyncStream, Omit, omit
from openai.types import AllModels, chat, responses
from openai.types.chat import (
ChatCompletionChunk,
ChatCompletionContentPartImageParam,
ChatCompletionContentPartInputAudioParam,
ChatCompletionContentPartParam,
ChatCompletionContentPartTextParam,
chat_completion,
chat_completion_chunk,
chat_completion_token_logprob,
)
from openai.types.chat.chat_completion_content_part_image_param import ImageURL
from openai.types.chat.chat_completion_content_part_input_audio_param import InputAudio
from openai.types.chat.chat_completion_content_part_param import File, FileFile
from openai.types.chat.chat_completion_message_custom_tool_call import ChatCompletionMessageCustomToolCall
from openai.types.chat.chat_completion_message_function_tool_call import ChatCompletionMessageFunctionToolCall
from openai.types.chat.chat_completion_message_function_tool_call_param import (
ChatCompletionMessageFunctionToolCallParam,
)
from openai.types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam
from openai.types.chat.completion_create_params import (
WebSearchOptions,
WebSearchOptionsUserLocation,
WebSearchOptionsUserLocationApproximate,
)
from openai.types.responses import ComputerToolParam, FileSearchToolParam, WebSearchToolParam
from openai.types.responses.response_input_param import FunctionCallOutput, Message
from openai.types.responses.response_reasoning_item_param import (
Content as ReasoningContent,
Summary as ReasoningSummary,
)
from openai.types.responses.response_status import ResponseStatus
from openai.types.shared import ReasoningEffort
from openai.types.shared_params import Reasoning
OMIT = omit
except ImportError as _import_error:
raise ImportError(
'Please install `openai` to use the OpenAI model, '
'you can use the `openai` optional group — `pip install "pydantic-ai-slim[openai]"`'
) from _import_error
__all__ = (
'OpenAIModel',
'OpenAIChatModel',
'OpenAIResponsesModel',
'OpenAIModelSettings',
'OpenAIChatModelSettings',
'OpenAIResponsesModelSettings',
'OpenAIModelName',
)
OpenAIModelName = str | AllModels
"""
Possible OpenAI model names.
Since OpenAI supports a variety of date-stamped models, we explicitly list the latest models but
allow any name in the type hints.
See [the OpenAI docs](https://platform.openai.com/docs/models) for a full list.
Using this more broad type for the model name instead of the ChatModel definition
allows this model to be used more easily with other model types (ie, Ollama, Deepseek).
"""
MCP_SERVER_TOOL_CONNECTOR_URI_SCHEME: Literal['x-openai-connector'] = 'x-openai-connector'
"""
Prefix for OpenAI connector IDs. OpenAI supports either a URL or a connector ID when passing MCP configuration to a model,
by using that prefix like `x-openai-connector:<connector-id>` in a URL, you can pass a connector ID to a model.
"""
_CHAT_FINISH_REASON_MAP: dict[
Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call'], FinishReason
] = {
'stop': 'stop',
'length': 'length',
'tool_calls': 'tool_call',
'content_filter': 'content_filter',
'function_call': 'tool_call',
}
_RESPONSES_FINISH_REASON_MAP: dict[Literal['max_output_tokens', 'content_filter'] | ResponseStatus, FinishReason] = {
'max_output_tokens': 'length',
'content_filter': 'content_filter',
'completed': 'stop',
'cancelled': 'error',
'failed': 'error',
}
_OPENAI_ASPECT_RATIO_TO_SIZE: dict[ImageAspectRatio, Literal['1024x1024', '1024x1536', '1536x1024']] = {
'1:1': '1024x1024',
'2:3': '1024x1536',
'3:2': '1536x1024',
}
_OPENAI_IMAGE_SIZE = Literal['auto', '1024x1024', '1024x1536', '1536x1024']
_OPENAI_IMAGE_SIZES: tuple[_OPENAI_IMAGE_SIZE, ...] = _utils.get_args(_OPENAI_IMAGE_SIZE)
class _AzureContentFilterResultDetail(BaseModel):
filtered: bool
severity: str | None = None
detected: bool | None = None
class _AzureContentFilterResult(BaseModel):
hate: _AzureContentFilterResultDetail | None = None
self_harm: _AzureContentFilterResultDetail | None = None
sexual: _AzureContentFilterResultDetail | None = None
violence: _AzureContentFilterResultDetail | None = None
jailbreak: _AzureContentFilterResultDetail | None = None
profanity: _AzureContentFilterResultDetail | None = None
class _AzureInnerError(BaseModel):
code: str
content_filter_result: _AzureContentFilterResult
class _AzureError(BaseModel):
code: str
message: str
innererror: _AzureInnerError | None = None
class _AzureErrorResponse(BaseModel):
error: _AzureError
def _resolve_openai_image_generation_size(
tool: ImageGenerationTool,
) -> _OPENAI_IMAGE_SIZE:
"""Map `ImageGenerationTool.aspect_ratio` to an OpenAI size string when provided."""
aspect_ratio = tool.aspect_ratio
if aspect_ratio is None:
if tool.size is None:
return 'auto' # default
if tool.size not in _OPENAI_IMAGE_SIZES:
raise UserError(
f'OpenAI image generation only supports `size` values: {_OPENAI_IMAGE_SIZES}. '
f'Got: {tool.size}. Omit `size` to use the default (auto).'
)
return tool.size
mapped_size = _OPENAI_ASPECT_RATIO_TO_SIZE.get(aspect_ratio)
if mapped_size is None:
supported = ', '.join(_OPENAI_ASPECT_RATIO_TO_SIZE)
raise UserError(
f'OpenAI image generation only supports `aspect_ratio` values: {supported}. Specify one of those values or omit `aspect_ratio`.'
)
# When aspect_ratio is set, size must be None, 'auto', or match the mapped size
if tool.size not in (None, 'auto', mapped_size):
raise UserError(
'`ImageGenerationTool` cannot combine `aspect_ratio` with a conflicting `size` when using OpenAI.'
)
return mapped_size
def _check_azure_content_filter(e: APIStatusError, system: str, model_name: str) -> ModelResponse | None:
"""Check if the error is an Azure content filter error."""
# Assign to Any to avoid 'dict[Unknown, Unknown]' inference in strict mode
body_any: Any = e.body
if system == 'azure' and e.status_code == 400 and isinstance(body_any, dict):
try:
error_data = _AzureErrorResponse.model_validate(body_any)
if error_data.error.code == 'content_filter':
provider_details: dict[str, Any] = {'finish_reason': 'content_filter'}
if error_data.error.innererror:
provider_details['content_filter_result'] = (
error_data.error.innererror.content_filter_result.model_dump(exclude_none=True)
)
return ModelResponse(
parts=[], # Empty parts to trigger content filter error in agent graph
model_name=model_name,
timestamp=_utils.now_utc(),
provider_name=system,
finish_reason='content_filter',
provider_details=provider_details,
)
except ValidationError:
pass
return None
class OpenAIChatModelSettings(ModelSettings, total=False):
"""Settings used for an OpenAI model request."""
# ALL FIELDS MUST BE `openai_` PREFIXED SO YOU CAN MERGE THEM WITH OTHER MODELS.
openai_reasoning_effort: ReasoningEffort
"""Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning).
Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can
result in faster responses and fewer tokens used on reasoning in a response.
"""
openai_logprobs: bool
"""Include log probabilities in the response.
For Chat models, these will be included in `ModelResponse.provider_details['logprobs']`.
For Responses models, these will be included in the response output parts `TextPart.provider_details['logprobs']`.
"""
openai_top_logprobs: int
"""Include log probabilities of the top n tokens in the response."""
openai_user: str
"""A unique identifier representing the end-user, which can help OpenAI monitor and detect abuse.
See [OpenAI's safety best practices](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids) for more details.
"""
openai_service_tier: Literal['auto', 'default', 'flex', 'priority']
"""The service tier to use for the model request.
Currently supported values are `auto`, `default`, `flex`, and `priority`.
For more information, see [OpenAI's service tiers documentation](https://platform.openai.com/docs/api-reference/chat/object#chat/object-service_tier).
"""
openai_prediction: ChatCompletionPredictionContentParam
"""Enables [predictive outputs](https://platform.openai.com/docs/guides/predicted-outputs).
This feature is currently only supported for some OpenAI models.
"""
openai_prompt_cache_key: str
"""Used by OpenAI to cache responses for similar requests to optimize your cache hit rates.
See the [OpenAI Prompt Caching documentation](https://platform.openai.com/docs/guides/prompt-caching#how-it-works) for more information.
"""
openai_prompt_cache_retention: Literal['in-memory', '24h']
"""The retention policy for the prompt cache. Set to 24h to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours.
See the [OpenAI Prompt Caching documentation](https://platform.openai.com/docs/guides/prompt-caching#how-it-works) for more information.
"""
@deprecated('Use `OpenAIChatModelSettings` instead.')
class OpenAIModelSettings(OpenAIChatModelSettings, total=False):
"""Deprecated alias for `OpenAIChatModelSettings`."""
class OpenAIResponsesModelSettings(OpenAIChatModelSettings, total=False):
"""Settings used for an OpenAI Responses model request.
ALL FIELDS MUST BE `openai_` PREFIXED SO YOU CAN MERGE THEM WITH OTHER MODELS.
"""
openai_builtin_tools: Sequence[FileSearchToolParam | WebSearchToolParam | ComputerToolParam]
"""The provided OpenAI built-in tools to use.
See [OpenAI's built-in tools](https://platform.openai.com/docs/guides/tools?api-mode=responses) for more details.
"""
openai_reasoning_generate_summary: Literal['detailed', 'concise']
"""Deprecated alias for `openai_reasoning_summary`."""
openai_reasoning_summary: Literal['detailed', 'concise', 'auto']
"""A summary of the reasoning performed by the model.
This can be useful for debugging and understanding the model's reasoning process.
One of `concise`, `detailed`, or `auto`.
Check the [OpenAI Reasoning documentation](https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries)
for more details.
"""
openai_send_reasoning_ids: bool
"""Whether to send the unique IDs of reasoning, text, and function call parts from the message history to the model. Enabled by default for reasoning models.
This can result in errors like `"Item 'rs_123' of type 'reasoning' was provided without its required following item."`
if the message history you're sending does not match exactly what was received from the Responses API in a previous response,
for example if you're using a [history processor](../../message-history.md#processing-message-history).
In that case, you'll want to disable this.
"""
openai_truncation: Literal['disabled', 'auto']
"""The truncation strategy to use for the model response.
It can be either:
- `disabled` (default): If a model response will exceed the context window size for a model, the
request will fail with a 400 error.
- `auto`: If the context of this response and previous ones exceeds the model's context window size,
the model will truncate the response to fit the context window by dropping input items in the
middle of the conversation.
"""
openai_text_verbosity: Literal['low', 'medium', 'high']
"""Constrains the verbosity of the model's text response.
Lower values will result in more concise responses, while higher values will
result in more verbose responses. Currently supported values are `low`,
`medium`, and `high`.
"""
openai_previous_response_id: Literal['auto'] | str
"""The ID of a previous response from the model to use as the starting point for a continued conversation.
When set to `'auto'`, the request automatically uses the most recent
`provider_response_id` from the message history and omits earlier messages.
This enables the model to use server-side conversation state and faithfully reference previous reasoning.
See the [OpenAI Responses API documentation](https://platform.openai.com/docs/guides/reasoning#keeping-reasoning-items-in-context)
for more information.
"""
openai_include_code_execution_outputs: bool
"""Whether to include the code execution results in the response.
Corresponds to the `code_interpreter_call.outputs` value of the `include` parameter in the Responses API.
"""
openai_include_web_search_sources: bool
"""Whether to include the web search results in the response.
Corresponds to the `web_search_call.action.sources` value of the `include` parameter in the Responses API.
"""
openai_include_file_search_results: bool
"""Whether to include the file search results in the response.
Corresponds to the `file_search_call.results` value of the `include` parameter in the Responses API.
"""
@dataclass(init=False)
class OpenAIChatModel(Model):
"""A model that uses the OpenAI API.
Internally, this uses the [OpenAI Python client](https://github.com/openai/openai-python) to interact with the API.
Apart from `__init__`, all methods are private or match those of the base class.
"""
client: AsyncOpenAI = field(repr=False)
_model_name: OpenAIModelName = field(repr=False)
_provider: Provider[AsyncOpenAI] = field(repr=False)
@overload
def __init__(
self,
model_name: OpenAIModelName,
*,
provider: OpenAIChatCompatibleProvider
| Literal[
'openai',
'openai-chat',
'gateway',
]
| Provider[AsyncOpenAI] = 'openai',
profile: ModelProfileSpec | None = None,
settings: ModelSettings | None = None,
) -> None: ...
@deprecated('Set the `system_prompt_role` in the `OpenAIModelProfile` instead.')
@overload
def __init__(
self,
model_name: OpenAIModelName,
*,
provider: OpenAIChatCompatibleProvider
| Literal[
'openai',
'openai-chat',
'gateway',
]
| Provider[AsyncOpenAI] = 'openai',
profile: ModelProfileSpec | None = None,
system_prompt_role: OpenAISystemPromptRole | None = None,
settings: ModelSettings | None = None,
) -> None: ...
def __init__(
self,
model_name: OpenAIModelName,
*,
provider: OpenAIChatCompatibleProvider
| Literal[
'openai',
'openai-chat',
'gateway',
]
| Provider[AsyncOpenAI] = 'openai',
profile: ModelProfileSpec | None = None,
system_prompt_role: OpenAISystemPromptRole | None = None,
settings: ModelSettings | None = None,
):
"""Initialize an OpenAI model.
Args:
model_name: The name of the OpenAI model to use. List of model names available
[here](https://github.com/openai/openai-python/blob/v1.54.3/src/openai/types/chat_model.py#L7)
(Unfortunately, despite being ask to do so, OpenAI do not provide `.inv` files for their API).
provider: The provider to use. Defaults to `'openai'`.
profile: The model profile to use. Defaults to a profile picked by the provider based on the model name.
system_prompt_role: The role to use for the system prompt message. If not provided, defaults to `'system'`.
In the future, this may be inferred from the model name.
settings: Default model settings for this model instance.
"""
self._model_name = model_name
if isinstance(provider, str):
provider = infer_provider('gateway/openai' if provider == 'gateway' else provider)
self._provider = provider
self.client = provider.client
super().__init__(settings=settings, profile=profile or provider.model_profile)
if system_prompt_role is not None:
self.profile = OpenAIModelProfile(openai_system_prompt_role=system_prompt_role).update(self.profile)
@property
def base_url(self) -> str:
return str(self.client.base_url)
@property
def model_name(self) -> OpenAIModelName:
"""The model name."""
return self._model_name
@property
def system(self) -> str:
"""The model provider."""
return self._provider.name
@classmethod
def supported_builtin_tools(cls) -> frozenset[type[AbstractBuiltinTool]]:
"""Return the set of builtin tool types this model can handle."""
return frozenset({WebSearchTool})
@cached_property
def profile(self) -> ModelProfile:
"""The model profile.
WebSearchTool is only supported if openai_chat_supports_web_search is True.
"""
_profile = super().profile
openai_profile = OpenAIModelProfile.from_profile(_profile)
if not openai_profile.openai_chat_supports_web_search:
new_tools = _profile.supported_builtin_tools - {WebSearchTool}
_profile = replace(_profile, supported_builtin_tools=new_tools)
return _profile
@property
@deprecated('Set the `system_prompt_role` in the `OpenAIModelProfile` instead.')
def system_prompt_role(self) -> OpenAISystemPromptRole | None:
return OpenAIModelProfile.from_profile(self.profile).openai_system_prompt_role
def prepare_request(
self,
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
) -> tuple[ModelSettings | None, ModelRequestParameters]:
# Check for WebSearchTool before base validation to provide a helpful error message
if (
any(isinstance(tool, WebSearchTool) for tool in model_request_parameters.builtin_tools)
and not OpenAIModelProfile.from_profile(self.profile).openai_chat_supports_web_search
):
raise UserError(
f'WebSearchTool is not supported with `OpenAIChatModel` and model {self.model_name!r}. '
f'Please use `OpenAIResponsesModel` instead.'
)
return super().prepare_request(model_settings, model_request_parameters)
async def request(
self,
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
) -> ModelResponse:
check_allow_model_requests()
model_settings, model_request_parameters = self.prepare_request(
model_settings,
model_request_parameters,
)
response = await self._completions_create(
messages, False, cast(OpenAIChatModelSettings, model_settings or {}), model_request_parameters
)
# Handle ModelResponse returned directly (for content filters)
if isinstance(response, ModelResponse):
return response
model_response = self._process_response(response)
return model_response
@asynccontextmanager
async def request_stream(
self,
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
run_context: RunContext[Any] | None = None,
) -> AsyncIterator[StreamedResponse]:
check_allow_model_requests()
model_settings, model_request_parameters = self.prepare_request(
model_settings,
model_request_parameters,
)
response = await self._completions_create(
messages, True, cast(OpenAIChatModelSettings, model_settings or {}), model_request_parameters
)
async with response:
yield await self._process_streamed_response(response, model_request_parameters)
@overload
async def _completions_create(
self,
messages: list[ModelMessage],
stream: Literal[True],
model_settings: OpenAIChatModelSettings,
model_request_parameters: ModelRequestParameters,
) -> AsyncStream[ChatCompletionChunk]: ...
@overload
async def _completions_create(
self,
messages: list[ModelMessage],
stream: Literal[False],
model_settings: OpenAIChatModelSettings,
model_request_parameters: ModelRequestParameters,
) -> chat.ChatCompletion | ModelResponse: ...
async def _completions_create(
self,
messages: list[ModelMessage],
stream: bool,
model_settings: OpenAIChatModelSettings,
model_request_parameters: ModelRequestParameters,
) -> chat.ChatCompletion | AsyncStream[ChatCompletionChunk] | ModelResponse:
tools = self._get_tools(model_request_parameters)
web_search_options = self._get_web_search_options(model_request_parameters)
if not tools:
tool_choice: Literal['none', 'required', 'auto'] | None = None
elif (
not model_request_parameters.allow_text_output
and OpenAIModelProfile.from_profile(self.profile).openai_supports_tool_choice_required
):
tool_choice = 'required'
else:
tool_choice = 'auto'
openai_messages = await self._map_messages(messages, model_request_parameters)
response_format: chat.completion_create_params.ResponseFormat | None = None
if model_request_parameters.output_mode == 'native':
output_object = model_request_parameters.output_object
assert output_object is not None
response_format = self._map_json_schema(output_object)
elif (
model_request_parameters.output_mode == 'prompted' and self.profile.supports_json_object_output
): # pragma: no branch
response_format = {'type': 'json_object'}
unsupported_model_settings = OpenAIModelProfile.from_profile(self.profile).openai_unsupported_model_settings
for setting in unsupported_model_settings:
model_settings.pop(setting, None)
try:
extra_headers = model_settings.get('extra_headers', {})
extra_headers.setdefault('User-Agent', get_user_agent())
return await self.client.chat.completions.create(
model=self.model_name,
messages=openai_messages,
parallel_tool_calls=model_settings.get('parallel_tool_calls', OMIT),
tools=tools or OMIT,
tool_choice=tool_choice or OMIT,
stream=stream,
stream_options={'include_usage': True} if stream else OMIT,
stop=model_settings.get('stop_sequences', OMIT),
max_completion_tokens=model_settings.get('max_tokens', OMIT),
timeout=model_settings.get('timeout', NOT_GIVEN),
response_format=response_format or OMIT,
seed=model_settings.get('seed', OMIT),
reasoning_effort=model_settings.get('openai_reasoning_effort', OMIT),
user=model_settings.get('openai_user', OMIT),
web_search_options=web_search_options or OMIT,
service_tier=model_settings.get('openai_service_tier', OMIT),
prediction=model_settings.get('openai_prediction', OMIT),
temperature=model_settings.get('temperature', OMIT),
top_p=model_settings.get('top_p', OMIT),
presence_penalty=model_settings.get('presence_penalty', OMIT),
frequency_penalty=model_settings.get('frequency_penalty', OMIT),
logit_bias=model_settings.get('logit_bias', OMIT),
logprobs=model_settings.get('openai_logprobs', OMIT),
top_logprobs=model_settings.get('openai_top_logprobs', OMIT),
prompt_cache_key=model_settings.get('openai_prompt_cache_key', OMIT),
prompt_cache_retention=model_settings.get('openai_prompt_cache_retention', OMIT),
extra_headers=extra_headers,
extra_body=model_settings.get('extra_body'),
)
except APIStatusError as e:
if model_response := _check_azure_content_filter(e, self.system, self.model_name):
return model_response
if (status_code := e.status_code) >= 400:
raise ModelHTTPError(status_code=status_code, model_name=self.model_name, body=e.body) from e
raise # pragma: lax no cover
except APIConnectionError as e:
raise ModelAPIError(model_name=self.model_name, message=e.message) from e
def _validate_completion(self, response: chat.ChatCompletion) -> chat.ChatCompletion:
"""Hook that validates chat completions before processing.
This method may be overridden by subclasses of `OpenAIChatModel` to apply custom completion validations.
"""
return chat.ChatCompletion.model_validate(response.model_dump())
def _process_provider_details(self, response: chat.ChatCompletion) -> dict[str, Any] | None:
"""Hook that response content to provider details.
This method may be overridden by subclasses of `OpenAIChatModel` to apply custom mappings.
"""
return _map_provider_details(response.choices[0])
def _process_response(self, response: chat.ChatCompletion | str) -> ModelResponse:
"""Process a non-streamed response, and prepare a message to return."""
# Although the OpenAI SDK claims to return a Pydantic model (`ChatCompletion`) from the chat completions function:
# * it hasn't actually performed validation (presumably they're creating the model with `model_construct` or something?!)
# * if the endpoint returns plain text, the return type is a string
# Thus we validate it fully here.
if not isinstance(response, chat.ChatCompletion):
raise UnexpectedModelBehavior(
f'Invalid response from {self.system} chat completions endpoint, expected JSON data'
)
timestamp = _now_utc()
if not response.created:
response.created = int(timestamp.timestamp())
# Workaround for local Ollama which sometimes returns a `None` finish reason.
if response.choices and (choice := response.choices[0]) and choice.finish_reason is None: # pyright: ignore[reportUnnecessaryComparison]
choice.finish_reason = 'stop'
try:
response = self._validate_completion(response)
except ValidationError as e:
raise UnexpectedModelBehavior(f'Invalid response from {self.system} chat completions endpoint: {e}') from e
choice = response.choices[0]
items: list[ModelResponsePart] = []
if thinking_parts := self._process_thinking(choice.message):
items.extend(thinking_parts)
if choice.message.content:
items.extend(
(replace(part, id='content', provider_name=self.system) if isinstance(part, ThinkingPart) else part)
for part in split_content_into_text_and_thinking(choice.message.content, self.profile.thinking_tags)
)
if choice.message.tool_calls is not None:
for c in choice.message.tool_calls:
if isinstance(c, ChatCompletionMessageFunctionToolCall):
part = ToolCallPart(c.function.name, c.function.arguments, tool_call_id=c.id)
elif isinstance(c, ChatCompletionMessageCustomToolCall): # pragma: no cover
# NOTE: Custom tool calls are not supported.
# See <https://github.com/pydantic/pydantic-ai/issues/2513> for more details.
raise RuntimeError('Custom tool calls are not supported')
else:
assert_never(c)
part.tool_call_id = _guard_tool_call_id(part)
items.append(part)
provider_details = self._process_provider_details(response)
if response.created: # pragma: no branch
if provider_details is None:
provider_details = {}
provider_details['timestamp'] = number_to_datetime(response.created)
return ModelResponse(
parts=items,
usage=self._map_usage(response),
model_name=response.model,
timestamp=timestamp,
provider_details=provider_details or None,
provider_response_id=response.id,
provider_name=self._provider.name,
provider_url=self._provider.base_url,
finish_reason=self._map_finish_reason(choice.finish_reason),
)
def _process_thinking(self, message: chat.ChatCompletionMessage) -> list[ThinkingPart] | None:
"""Hook that maps reasoning tokens to thinking parts.
This method may be overridden by subclasses of `OpenAIChatModel` to apply custom mappings.
"""
profile = OpenAIModelProfile.from_profile(self.profile)
custom_field = profile.openai_chat_thinking_field
items: list[ThinkingPart] = []
# Prefer the configured custom reasoning field, if present in profile.
# Fall back to built-in fields if no custom field result was found.
# The `reasoning_content` field is typically present in DeepSeek and Moonshot models.
# https://api-docs.deepseek.com/guides/reasoning_model
# The `reasoning` field is typically present in gpt-oss via Ollama and OpenRouter.
# - https://cookbook.openai.com/articles/gpt-oss/handle-raw-cot#chat-completions-api
# - https://openrouter.ai/docs/use-cases/reasoning-tokens#basic-usage-with-reasoning-tokens
for field_name in (custom_field, 'reasoning', 'reasoning_content'):
if not field_name:
continue
reasoning: str | None = getattr(message, field_name, None)
if reasoning: # pragma: no branch
items.append(ThinkingPart(id=field_name, content=reasoning, provider_name=self.system))
return items
return items or None
async def _process_streamed_response(
self, response: AsyncStream[ChatCompletionChunk], model_request_parameters: ModelRequestParameters
) -> OpenAIStreamedResponse:
"""Process a streamed response, and prepare a streaming response to return."""
peekable_response = _utils.PeekableAsyncStream(response)
first_chunk = await peekable_response.peek()
if isinstance(first_chunk, _utils.Unset):
raise UnexpectedModelBehavior( # pragma: no cover
'Streamed response ended without content or tool calls'
)
# When using Azure OpenAI and a content filter is enabled, the first chunk will contain a `''` model name,
# so we set it from a later chunk in `OpenAIChatStreamedResponse`.
model_name = first_chunk.model or self.model_name
return self._streamed_response_cls(
model_request_parameters=model_request_parameters,
_model_name=model_name,
_model_profile=self.profile,
_response=peekable_response,
_provider_name=self._provider.name,
_provider_url=self._provider.base_url,
_provider_timestamp=number_to_datetime(first_chunk.created) if first_chunk.created else None,
)
@property
def _streamed_response_cls(self) -> type[OpenAIStreamedResponse]:
"""Returns the `StreamedResponse` type that will be used for streamed responses.
This method may be overridden by subclasses of `OpenAIChatModel` to provide their own `StreamedResponse` type.
"""
return OpenAIStreamedResponse
def _map_usage(self, response: chat.ChatCompletion) -> usage.RequestUsage:
return _map_usage(response, self._provider.name, self._provider.base_url, self.model_name)
def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[chat.ChatCompletionToolParam]:
return [self._map_tool_definition(r) for r in model_request_parameters.tool_defs.values()]
def _get_web_search_options(self, model_request_parameters: ModelRequestParameters) -> WebSearchOptions | None:
for tool in model_request_parameters.builtin_tools:
if isinstance(tool, WebSearchTool): # pragma: no branch
if tool.user_location:
return WebSearchOptions(
search_context_size=tool.search_context_size,
user_location=WebSearchOptionsUserLocation(
type='approximate',
approximate=WebSearchOptionsUserLocationApproximate(**tool.user_location),
),
)
return WebSearchOptions(search_context_size=tool.search_context_size)
return None
@dataclass
class _MapModelResponseContext:
"""Context object for mapping a `ModelResponse` to OpenAI chat completion parameters.
This class is designed to be subclassed to add new fields for custom logic,
collecting various parts of the model response (like text and tool calls)
to form a single assistant message.
"""
_model: OpenAIChatModel
texts: list[str] = field(default_factory=list)
thinkings: list[str] = field(default_factory=list)
tool_calls: list[ChatCompletionMessageFunctionToolCallParam] = field(default_factory=list)
def map_assistant_message(self, message: ModelResponse) -> chat.ChatCompletionAssistantMessageParam:
for item in message.parts:
if isinstance(item, TextPart):
self._map_response_text_part(item)
elif isinstance(item, ThinkingPart):
self._map_response_thinking_part(item)
elif isinstance(item, ToolCallPart):
self._map_response_tool_call_part(item)
elif isinstance(item, BuiltinToolCallPart | BuiltinToolReturnPart): # pragma: no cover
self._map_response_builtin_part(item)
elif isinstance(item, FilePart): # pragma: no cover
self._map_response_file_part(item)
else:
assert_never(item)
return self._into_message_param()
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam:
"""Converts the collected texts and tool calls into a single OpenAI `ChatCompletionAssistantMessageParam`.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for how collected parts are transformed into the final message parameter.
Returns:
An OpenAI `ChatCompletionAssistantMessageParam` object representing the assistant's response.
"""
profile = OpenAIModelProfile.from_profile(self._model.profile)
message_param = chat.ChatCompletionAssistantMessageParam(role='assistant')
# Note: model responses from this model should only have one text item, so the following
# shouldn't merge multiple texts into one unless you switch models between runs:
if profile.openai_chat_send_back_thinking_parts == 'field' and self.thinkings:
field = profile.openai_chat_thinking_field
if field: # pragma: no branch (handled by profile validation)
message_param[field] = '\n\n'.join(self.thinkings)
if self.texts:
message_param['content'] = '\n\n'.join(self.texts)
else:
message_param['content'] = None
if self.tool_calls:
message_param['tool_calls'] = self.tool_calls
return message_param
def _map_response_text_part(self, item: TextPart) -> None:
"""Maps a `TextPart` to the response context.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for handling text parts.
"""
self.texts.append(item.content)
def _map_response_thinking_part(self, item: ThinkingPart) -> None:
"""Maps a `ThinkingPart` to the response context.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for handling thinking parts.
"""
profile = OpenAIModelProfile.from_profile(self._model.profile)
include_method = profile.openai_chat_send_back_thinking_parts
if include_method == 'tags':
start_tag, end_tag = self._model.profile.thinking_tags
self.texts.append('\n'.join([start_tag, item.content, end_tag]))
elif include_method == 'field':
self.thinkings.append(item.content)
def _map_response_tool_call_part(self, item: ToolCallPart) -> None:
"""Maps a `ToolCallPart` to the response context.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for handling tool call parts.
"""
self.tool_calls.append(self._model._map_tool_call(item))
def _map_response_builtin_part(self, item: BuiltinToolCallPart | BuiltinToolReturnPart) -> None:
"""Maps a built-in tool call or return part to the response context.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for handling built-in tool parts.
"""
# OpenAI doesn't return built-in tool calls
pass
def _map_response_file_part(self, item: FilePart) -> None:
"""Maps a `FilePart` to the response context.
This method serves as a hook that can be overridden by subclasses
to implement custom logic for handling file parts.
"""
# Files generated by models are not sent back to models that don't themselves generate files.
pass
def _map_model_response(self, message: ModelResponse) -> chat.ChatCompletionMessageParam:
"""Hook that determines how `ModelResponse` is mapped into `ChatCompletionMessageParam` objects before sending.
Subclasses of `OpenAIChatModel` may override this method to provide their own mapping logic.
"""
return self._MapModelResponseContext(self).map_assistant_message(message)
def _map_finish_reason(
self, key: Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call']
) -> FinishReason | None:
"""Hooks that maps a finish reason key to a [FinishReason][pydantic_ai.messages.FinishReason].
This method may be overridden by subclasses of `OpenAIChatModel` to accommodate custom keys.
"""
return _CHAT_FINISH_REASON_MAP.get(key)
async def _map_messages(
self, messages: Sequence[ModelMessage], model_request_parameters: ModelRequestParameters
) -> list[chat.ChatCompletionMessageParam]:
"""Just maps a `pydantic_ai.Message` to a `openai.types.ChatCompletionMessageParam`."""
openai_messages: list[chat.ChatCompletionMessageParam] = []
for message in messages:
if isinstance(message, ModelRequest):
async for item in self._map_user_message(message):
openai_messages.append(item)
elif isinstance(message, ModelResponse):
openai_messages.append(self._map_model_response(message))
else:
assert_never(message)
if instructions := self._get_instructions(messages, model_request_parameters):
system_prompt_count = sum(1 for m in openai_messages if m.get('role') == 'system')
openai_messages.insert(
system_prompt_count, chat.ChatCompletionSystemMessageParam(content=instructions, role='system')
)
return openai_messages
@staticmethod
def _map_tool_call(t: ToolCallPart) -> ChatCompletionMessageFunctionToolCallParam:
return ChatCompletionMessageFunctionToolCallParam(
id=_guard_tool_call_id(t=t),
type='function',
function={'name': t.tool_name, 'arguments': t.args_as_json_str()},
)
def _map_json_schema(self, o: OutputObjectDefinition) -> chat.completion_create_params.ResponseFormat:
response_format_param: chat.completion_create_params.ResponseFormatJSONSchema = { # pyright: ignore[reportPrivateImportUsage]
'type': 'json_schema',
'json_schema': {'name': o.name or DEFAULT_OUTPUT_TOOL_NAME, 'schema': o.json_schema},
}
if o.description: