openai-agents 0.0.10__py3-none-any.whl → 0.0.12__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of openai-agents might be problematic. Click here for more details.

@@ -3,71 +3,27 @@ from __future__ import annotations
3
3
  import dataclasses
4
4
  import json
5
5
  import time
6
- from collections.abc import AsyncIterator, Iterable
7
- from dataclasses import dataclass, field
6
+ from collections.abc import AsyncIterator
8
7
  from typing import TYPE_CHECKING, Any, Literal, cast, overload
9
8
 
10
- from openai import NOT_GIVEN, AsyncOpenAI, AsyncStream, NotGiven
9
+ from openai import NOT_GIVEN, AsyncOpenAI, AsyncStream
11
10
  from openai.types import ChatModel
12
- from openai.types.chat import (
13
- ChatCompletion,
14
- ChatCompletionAssistantMessageParam,
15
- ChatCompletionChunk,
16
- ChatCompletionContentPartImageParam,
17
- ChatCompletionContentPartParam,
18
- ChatCompletionContentPartTextParam,
19
- ChatCompletionDeveloperMessageParam,
20
- ChatCompletionMessage,
21
- ChatCompletionMessageParam,
22
- ChatCompletionMessageToolCallParam,
23
- ChatCompletionSystemMessageParam,
24
- ChatCompletionToolChoiceOptionParam,
25
- ChatCompletionToolMessageParam,
26
- ChatCompletionUserMessageParam,
27
- )
28
- from openai.types.chat.chat_completion_tool_param import ChatCompletionToolParam
29
- from openai.types.chat.completion_create_params import ResponseFormat
30
- from openai.types.completion_usage import CompletionUsage
31
- from openai.types.responses import (
32
- EasyInputMessageParam,
33
- Response,
34
- ResponseCompletedEvent,
35
- ResponseContentPartAddedEvent,
36
- ResponseContentPartDoneEvent,
37
- ResponseCreatedEvent,
38
- ResponseFileSearchToolCallParam,
39
- ResponseFunctionCallArgumentsDeltaEvent,
40
- ResponseFunctionToolCall,
41
- ResponseFunctionToolCallParam,
42
- ResponseInputContentParam,
43
- ResponseInputImageParam,
44
- ResponseInputTextParam,
45
- ResponseOutputItem,
46
- ResponseOutputItemAddedEvent,
47
- ResponseOutputItemDoneEvent,
48
- ResponseOutputMessage,
49
- ResponseOutputMessageParam,
50
- ResponseOutputRefusal,
51
- ResponseOutputText,
52
- ResponseRefusalDeltaEvent,
53
- ResponseTextDeltaEvent,
54
- ResponseUsage,
55
- )
56
- from openai.types.responses.response_input_param import FunctionCallOutput, ItemReference, Message
57
- from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails
11
+ from openai.types.chat import ChatCompletion, ChatCompletionChunk
12
+ from openai.types.responses import Response
58
13
 
59
14
  from .. import _debug
60
- from ..agent_output import AgentOutputSchema
61
- from ..exceptions import AgentsException, UserError
15
+ from ..agent_output import AgentOutputSchemaBase
62
16
  from ..handoffs import Handoff
63
- from ..items import ModelResponse, TResponseInputItem, TResponseOutputItem, TResponseStreamEvent
17
+ from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent
64
18
  from ..logger import logger
65
- from ..tool import FunctionTool, Tool
19
+ from ..tool import Tool
66
20
  from ..tracing import generation_span
67
21
  from ..tracing.span_data import GenerationSpanData
68
22
  from ..tracing.spans import Span
69
23
  from ..usage import Usage
70
- from ..version import __version__
24
+ from .chatcmpl_converter import Converter
25
+ from .chatcmpl_helpers import HEADERS, ChatCmplHelpers
26
+ from .chatcmpl_stream_handler import ChatCmplStreamHandler
71
27
  from .fake_id import FAKE_RESPONSES_ID
72
28
  from .interface import Model, ModelTracing
73
29
 
@@ -75,18 +31,6 @@ if TYPE_CHECKING:
75
31
  from ..model_settings import ModelSettings
76
32
 
77
33
 
78
- _USER_AGENT = f"Agents/Python {__version__}"
79
- _HEADERS = {"User-Agent": _USER_AGENT}
80
-
81
-
82
- @dataclass
83
- class _StreamingState:
84
- started: bool = False
85
- text_content_index_and_output: tuple[int, ResponseOutputText] | None = None
86
- refusal_content_index_and_output: tuple[int, ResponseOutputRefusal] | None = None
87
- function_calls: dict[int, ResponseFunctionToolCall] = field(default_factory=dict)
88
-
89
-
90
34
  class OpenAIChatCompletionsModel(Model):
91
35
  def __init__(
92
36
  self,
@@ -105,7 +49,7 @@ class OpenAIChatCompletionsModel(Model):
105
49
  input: str | list[TResponseInputItem],
106
50
  model_settings: ModelSettings,
107
51
  tools: list[Tool],
108
- output_schema: AgentOutputSchema | None,
52
+ output_schema: AgentOutputSchemaBase | None,
109
53
  handoffs: list[Handoff],
110
54
  tracing: ModelTracing,
111
55
  previous_response_id: str | None,
@@ -152,7 +96,7 @@ class OpenAIChatCompletionsModel(Model):
152
96
  "output_tokens": usage.output_tokens,
153
97
  }
154
98
 
155
- items = _Converter.message_to_output_items(response.choices[0].message)
99
+ items = Converter.message_to_output_items(response.choices[0].message)
156
100
 
157
101
  return ModelResponse(
158
102
  output=items,
@@ -166,7 +110,7 @@ class OpenAIChatCompletionsModel(Model):
166
110
  input: str | list[TResponseInputItem],
167
111
  model_settings: ModelSettings,
168
112
  tools: list[Tool],
169
- output_schema: AgentOutputSchema | None,
113
+ output_schema: AgentOutputSchemaBase | None,
170
114
  handoffs: list[Handoff],
171
115
  tracing: ModelTracing,
172
116
  *,
@@ -193,257 +137,20 @@ class OpenAIChatCompletionsModel(Model):
193
137
  stream=True,
194
138
  )
195
139
 
196
- usage: CompletionUsage | None = None
197
- state = _StreamingState()
198
-
199
- async for chunk in stream:
200
- if not state.started:
201
- state.started = True
202
- yield ResponseCreatedEvent(
203
- response=response,
204
- type="response.created",
205
- )
206
-
207
- # The usage is only available in the last chunk
208
- usage = chunk.usage
209
-
210
- if not chunk.choices or not chunk.choices[0].delta:
211
- continue
212
-
213
- delta = chunk.choices[0].delta
214
-
215
- # Handle text
216
- if delta.content:
217
- if not state.text_content_index_and_output:
218
- # Initialize a content tracker for streaming text
219
- state.text_content_index_and_output = (
220
- 0 if not state.refusal_content_index_and_output else 1,
221
- ResponseOutputText(
222
- text="",
223
- type="output_text",
224
- annotations=[],
225
- ),
226
- )
227
- # Start a new assistant message stream
228
- assistant_item = ResponseOutputMessage(
229
- id=FAKE_RESPONSES_ID,
230
- content=[],
231
- role="assistant",
232
- type="message",
233
- status="in_progress",
234
- )
235
- # Notify consumers of the start of a new output message + first content part
236
- yield ResponseOutputItemAddedEvent(
237
- item=assistant_item,
238
- output_index=0,
239
- type="response.output_item.added",
240
- )
241
- yield ResponseContentPartAddedEvent(
242
- content_index=state.text_content_index_and_output[0],
243
- item_id=FAKE_RESPONSES_ID,
244
- output_index=0,
245
- part=ResponseOutputText(
246
- text="",
247
- type="output_text",
248
- annotations=[],
249
- ),
250
- type="response.content_part.added",
251
- )
252
- # Emit the delta for this segment of content
253
- yield ResponseTextDeltaEvent(
254
- content_index=state.text_content_index_and_output[0],
255
- delta=delta.content,
256
- item_id=FAKE_RESPONSES_ID,
257
- output_index=0,
258
- type="response.output_text.delta",
259
- )
260
- # Accumulate the text into the response part
261
- state.text_content_index_and_output[1].text += delta.content
262
-
263
- # Handle refusals (model declines to answer)
264
- if delta.refusal:
265
- if not state.refusal_content_index_and_output:
266
- # Initialize a content tracker for streaming refusal text
267
- state.refusal_content_index_and_output = (
268
- 0 if not state.text_content_index_and_output else 1,
269
- ResponseOutputRefusal(refusal="", type="refusal"),
270
- )
271
- # Start a new assistant message if one doesn't exist yet (in-progress)
272
- assistant_item = ResponseOutputMessage(
273
- id=FAKE_RESPONSES_ID,
274
- content=[],
275
- role="assistant",
276
- type="message",
277
- status="in_progress",
278
- )
279
- # Notify downstream that assistant message + first content part are starting
280
- yield ResponseOutputItemAddedEvent(
281
- item=assistant_item,
282
- output_index=0,
283
- type="response.output_item.added",
284
- )
285
- yield ResponseContentPartAddedEvent(
286
- content_index=state.refusal_content_index_and_output[0],
287
- item_id=FAKE_RESPONSES_ID,
288
- output_index=0,
289
- part=ResponseOutputText(
290
- text="",
291
- type="output_text",
292
- annotations=[],
293
- ),
294
- type="response.content_part.added",
295
- )
296
- # Emit the delta for this segment of refusal
297
- yield ResponseRefusalDeltaEvent(
298
- content_index=state.refusal_content_index_and_output[0],
299
- delta=delta.refusal,
300
- item_id=FAKE_RESPONSES_ID,
301
- output_index=0,
302
- type="response.refusal.delta",
303
- )
304
- # Accumulate the refusal string in the output part
305
- state.refusal_content_index_and_output[1].refusal += delta.refusal
306
-
307
- # Handle tool calls
308
- # Because we don't know the name of the function until the end of the stream, we'll
309
- # save everything and yield events at the end
310
- if delta.tool_calls:
311
- for tc_delta in delta.tool_calls:
312
- if tc_delta.index not in state.function_calls:
313
- state.function_calls[tc_delta.index] = ResponseFunctionToolCall(
314
- id=FAKE_RESPONSES_ID,
315
- arguments="",
316
- name="",
317
- type="function_call",
318
- call_id="",
319
- )
320
- tc_function = tc_delta.function
321
-
322
- state.function_calls[tc_delta.index].arguments += (
323
- tc_function.arguments if tc_function else ""
324
- ) or ""
325
- state.function_calls[tc_delta.index].name += (
326
- tc_function.name if tc_function else ""
327
- ) or ""
328
- state.function_calls[tc_delta.index].call_id += tc_delta.id or ""
329
-
330
- function_call_starting_index = 0
331
- if state.text_content_index_and_output:
332
- function_call_starting_index += 1
333
- # Send end event for this content part
334
- yield ResponseContentPartDoneEvent(
335
- content_index=state.text_content_index_and_output[0],
336
- item_id=FAKE_RESPONSES_ID,
337
- output_index=0,
338
- part=state.text_content_index_and_output[1],
339
- type="response.content_part.done",
340
- )
341
-
342
- if state.refusal_content_index_and_output:
343
- function_call_starting_index += 1
344
- # Send end event for this content part
345
- yield ResponseContentPartDoneEvent(
346
- content_index=state.refusal_content_index_and_output[0],
347
- item_id=FAKE_RESPONSES_ID,
348
- output_index=0,
349
- part=state.refusal_content_index_and_output[1],
350
- type="response.content_part.done",
351
- )
352
-
353
- # Actually send events for the function calls
354
- for function_call in state.function_calls.values():
355
- # First, a ResponseOutputItemAdded for the function call
356
- yield ResponseOutputItemAddedEvent(
357
- item=ResponseFunctionToolCall(
358
- id=FAKE_RESPONSES_ID,
359
- call_id=function_call.call_id,
360
- arguments=function_call.arguments,
361
- name=function_call.name,
362
- type="function_call",
363
- ),
364
- output_index=function_call_starting_index,
365
- type="response.output_item.added",
366
- )
367
- # Then, yield the args
368
- yield ResponseFunctionCallArgumentsDeltaEvent(
369
- delta=function_call.arguments,
370
- item_id=FAKE_RESPONSES_ID,
371
- output_index=function_call_starting_index,
372
- type="response.function_call_arguments.delta",
373
- )
374
- # Finally, the ResponseOutputItemDone
375
- yield ResponseOutputItemDoneEvent(
376
- item=ResponseFunctionToolCall(
377
- id=FAKE_RESPONSES_ID,
378
- call_id=function_call.call_id,
379
- arguments=function_call.arguments,
380
- name=function_call.name,
381
- type="function_call",
382
- ),
383
- output_index=function_call_starting_index,
384
- type="response.output_item.done",
385
- )
140
+ final_response: Response | None = None
141
+ async for chunk in ChatCmplStreamHandler.handle_stream(response, stream):
142
+ yield chunk
386
143
 
387
- # Finally, send the Response completed event
388
- outputs: list[ResponseOutputItem] = []
389
- if state.text_content_index_and_output or state.refusal_content_index_and_output:
390
- assistant_msg = ResponseOutputMessage(
391
- id=FAKE_RESPONSES_ID,
392
- content=[],
393
- role="assistant",
394
- type="message",
395
- status="completed",
396
- )
397
- if state.text_content_index_and_output:
398
- assistant_msg.content.append(state.text_content_index_and_output[1])
399
- if state.refusal_content_index_and_output:
400
- assistant_msg.content.append(state.refusal_content_index_and_output[1])
401
- outputs.append(assistant_msg)
402
-
403
- # send a ResponseOutputItemDone for the assistant message
404
- yield ResponseOutputItemDoneEvent(
405
- item=assistant_msg,
406
- output_index=0,
407
- type="response.output_item.done",
408
- )
409
-
410
- for function_call in state.function_calls.values():
411
- outputs.append(function_call)
412
-
413
- final_response = response.model_copy()
414
- final_response.output = outputs
415
- final_response.usage = (
416
- ResponseUsage(
417
- input_tokens=usage.prompt_tokens,
418
- output_tokens=usage.completion_tokens,
419
- total_tokens=usage.total_tokens,
420
- output_tokens_details=OutputTokensDetails(
421
- reasoning_tokens=usage.completion_tokens_details.reasoning_tokens
422
- if usage.completion_tokens_details
423
- and usage.completion_tokens_details.reasoning_tokens
424
- else 0
425
- ),
426
- input_tokens_details=InputTokensDetails(
427
- cached_tokens=usage.prompt_tokens_details.cached_tokens
428
- if usage.prompt_tokens_details and usage.prompt_tokens_details.cached_tokens
429
- else 0
430
- ),
431
- )
432
- if usage
433
- else None
434
- )
144
+ if chunk.type == "response.completed":
145
+ final_response = chunk.response
435
146
 
436
- yield ResponseCompletedEvent(
437
- response=final_response,
438
- type="response.completed",
439
- )
440
- if tracing.include_data():
147
+ if tracing.include_data() and final_response:
441
148
  span_generation.span_data.output = [final_response.model_dump()]
442
149
 
443
- if usage:
150
+ if final_response and final_response.usage:
444
151
  span_generation.span_data.usage = {
445
- "input_tokens": usage.prompt_tokens,
446
- "output_tokens": usage.completion_tokens,
152
+ "input_tokens": final_response.usage.input_tokens,
153
+ "output_tokens": final_response.usage.output_tokens,
447
154
  }
448
155
 
449
156
  @overload
@@ -453,7 +160,7 @@ class OpenAIChatCompletionsModel(Model):
453
160
  input: str | list[TResponseInputItem],
454
161
  model_settings: ModelSettings,
455
162
  tools: list[Tool],
456
- output_schema: AgentOutputSchema | None,
163
+ output_schema: AgentOutputSchemaBase | None,
457
164
  handoffs: list[Handoff],
458
165
  span: Span[GenerationSpanData],
459
166
  tracing: ModelTracing,
@@ -467,7 +174,7 @@ class OpenAIChatCompletionsModel(Model):
467
174
  input: str | list[TResponseInputItem],
468
175
  model_settings: ModelSettings,
469
176
  tools: list[Tool],
470
- output_schema: AgentOutputSchema | None,
177
+ output_schema: AgentOutputSchemaBase | None,
471
178
  handoffs: list[Handoff],
472
179
  span: Span[GenerationSpanData],
473
180
  tracing: ModelTracing,
@@ -480,13 +187,13 @@ class OpenAIChatCompletionsModel(Model):
480
187
  input: str | list[TResponseInputItem],
481
188
  model_settings: ModelSettings,
482
189
  tools: list[Tool],
483
- output_schema: AgentOutputSchema | None,
190
+ output_schema: AgentOutputSchemaBase | None,
484
191
  handoffs: list[Handoff],
485
192
  span: Span[GenerationSpanData],
486
193
  tracing: ModelTracing,
487
194
  stream: bool = False,
488
195
  ) -> ChatCompletion | tuple[Response, AsyncStream[ChatCompletionChunk]]:
489
- converted_messages = _Converter.items_to_messages(input)
196
+ converted_messages = Converter.items_to_messages(input)
490
197
 
491
198
  if system_instructions:
492
199
  converted_messages.insert(
@@ -506,13 +213,13 @@ class OpenAIChatCompletionsModel(Model):
506
213
  if model_settings.parallel_tool_calls is False
507
214
  else NOT_GIVEN
508
215
  )
509
- tool_choice = _Converter.convert_tool_choice(model_settings.tool_choice)
510
- response_format = _Converter.convert_response_format(output_schema)
216
+ tool_choice = Converter.convert_tool_choice(model_settings.tool_choice)
217
+ response_format = Converter.convert_response_format(output_schema)
511
218
 
512
- converted_tools = [ToolConverter.to_openai(tool) for tool in tools] if tools else []
219
+ converted_tools = [Converter.tool_to_openai(tool) for tool in tools] if tools else []
513
220
 
514
221
  for handoff in handoffs:
515
- converted_tools.append(ToolConverter.convert_handoff_tool(handoff))
222
+ converted_tools.append(Converter.convert_handoff_tool(handoff))
516
223
 
517
224
  if _debug.DONT_LOG_MODEL_DATA:
518
225
  logger.debug("Calling LLM")
@@ -526,9 +233,11 @@ class OpenAIChatCompletionsModel(Model):
526
233
  )
527
234
 
528
235
  reasoning_effort = model_settings.reasoning.effort if model_settings.reasoning else None
529
- store = _Converter.get_store_param(self._get_client(), model_settings)
236
+ store = ChatCmplHelpers.get_store_param(self._get_client(), model_settings)
530
237
 
531
- stream_options = _Converter.get_stream_options_param(self._get_client(), model_settings)
238
+ stream_options = ChatCmplHelpers.get_stream_options_param(
239
+ self._get_client(), model_settings, stream=stream
240
+ )
532
241
 
533
242
  ret = await self._get_client().chat.completions.create(
534
243
  model=self.model,
@@ -546,7 +255,7 @@ class OpenAIChatCompletionsModel(Model):
546
255
  stream_options=self._non_null_or_not_given(stream_options),
547
256
  store=self._non_null_or_not_given(store),
548
257
  reasoning_effort=self._non_null_or_not_given(reasoning_effort),
549
- extra_headers=_HEADERS,
258
+ extra_headers=HEADERS,
550
259
  extra_query=model_settings.extra_query,
551
260
  extra_body=model_settings.extra_body,
552
261
  metadata=self._non_null_or_not_given(model_settings.metadata),
@@ -576,450 +285,3 @@ class OpenAIChatCompletionsModel(Model):
576
285
  if self._client is None:
577
286
  self._client = AsyncOpenAI()
578
287
  return self._client
579
-
580
-
581
- class _Converter:
582
- @classmethod
583
- def is_openai(cls, client: AsyncOpenAI):
584
- return str(client.base_url).startswith("https://api.openai.com")
585
-
586
- @classmethod
587
- def get_store_param(cls, client: AsyncOpenAI, model_settings: ModelSettings) -> bool | None:
588
- # Match the behavior of Responses where store is True when not given
589
- default_store = True if cls.is_openai(client) else None
590
- return model_settings.store if model_settings.store is not None else default_store
591
-
592
- @classmethod
593
- def get_stream_options_param(
594
- cls, client: AsyncOpenAI, model_settings: ModelSettings
595
- ) -> dict[str, bool] | None:
596
- default_include_usage = True if cls.is_openai(client) else None
597
- include_usage = (
598
- model_settings.include_usage
599
- if model_settings.include_usage is not None
600
- else default_include_usage
601
- )
602
- stream_options = {"include_usage": include_usage} if include_usage is not None else None
603
- return stream_options
604
-
605
- @classmethod
606
- def convert_tool_choice(
607
- cls, tool_choice: Literal["auto", "required", "none"] | str | None
608
- ) -> ChatCompletionToolChoiceOptionParam | NotGiven:
609
- if tool_choice is None:
610
- return NOT_GIVEN
611
- elif tool_choice == "auto":
612
- return "auto"
613
- elif tool_choice == "required":
614
- return "required"
615
- elif tool_choice == "none":
616
- return "none"
617
- else:
618
- return {
619
- "type": "function",
620
- "function": {
621
- "name": tool_choice,
622
- },
623
- }
624
-
625
- @classmethod
626
- def convert_response_format(
627
- cls, final_output_schema: AgentOutputSchema | None
628
- ) -> ResponseFormat | NotGiven:
629
- if not final_output_schema or final_output_schema.is_plain_text():
630
- return NOT_GIVEN
631
-
632
- return {
633
- "type": "json_schema",
634
- "json_schema": {
635
- "name": "final_output",
636
- "strict": final_output_schema.strict_json_schema,
637
- "schema": final_output_schema.json_schema(),
638
- },
639
- }
640
-
641
- @classmethod
642
- def message_to_output_items(cls, message: ChatCompletionMessage) -> list[TResponseOutputItem]:
643
- items: list[TResponseOutputItem] = []
644
-
645
- message_item = ResponseOutputMessage(
646
- id=FAKE_RESPONSES_ID,
647
- content=[],
648
- role="assistant",
649
- type="message",
650
- status="completed",
651
- )
652
- if message.content:
653
- message_item.content.append(
654
- ResponseOutputText(text=message.content, type="output_text", annotations=[])
655
- )
656
- if message.refusal:
657
- message_item.content.append(
658
- ResponseOutputRefusal(refusal=message.refusal, type="refusal")
659
- )
660
- if message.audio:
661
- raise AgentsException("Audio is not currently supported")
662
-
663
- if message_item.content:
664
- items.append(message_item)
665
-
666
- if message.tool_calls:
667
- for tool_call in message.tool_calls:
668
- items.append(
669
- ResponseFunctionToolCall(
670
- id=FAKE_RESPONSES_ID,
671
- call_id=tool_call.id,
672
- arguments=tool_call.function.arguments,
673
- name=tool_call.function.name,
674
- type="function_call",
675
- )
676
- )
677
-
678
- return items
679
-
680
- @classmethod
681
- def maybe_easy_input_message(cls, item: Any) -> EasyInputMessageParam | None:
682
- if not isinstance(item, dict):
683
- return None
684
-
685
- keys = item.keys()
686
- # EasyInputMessageParam only has these two keys
687
- if keys != {"content", "role"}:
688
- return None
689
-
690
- role = item.get("role", None)
691
- if role not in ("user", "assistant", "system", "developer"):
692
- return None
693
-
694
- if "content" not in item:
695
- return None
696
-
697
- return cast(EasyInputMessageParam, item)
698
-
699
- @classmethod
700
- def maybe_input_message(cls, item: Any) -> Message | None:
701
- if (
702
- isinstance(item, dict)
703
- and item.get("type") == "message"
704
- and item.get("role")
705
- in (
706
- "user",
707
- "system",
708
- "developer",
709
- )
710
- ):
711
- return cast(Message, item)
712
-
713
- return None
714
-
715
- @classmethod
716
- def maybe_file_search_call(cls, item: Any) -> ResponseFileSearchToolCallParam | None:
717
- if isinstance(item, dict) and item.get("type") == "file_search_call":
718
- return cast(ResponseFileSearchToolCallParam, item)
719
- return None
720
-
721
- @classmethod
722
- def maybe_function_tool_call(cls, item: Any) -> ResponseFunctionToolCallParam | None:
723
- if isinstance(item, dict) and item.get("type") == "function_call":
724
- return cast(ResponseFunctionToolCallParam, item)
725
- return None
726
-
727
- @classmethod
728
- def maybe_function_tool_call_output(
729
- cls,
730
- item: Any,
731
- ) -> FunctionCallOutput | None:
732
- if isinstance(item, dict) and item.get("type") == "function_call_output":
733
- return cast(FunctionCallOutput, item)
734
- return None
735
-
736
- @classmethod
737
- def maybe_item_reference(cls, item: Any) -> ItemReference | None:
738
- if isinstance(item, dict) and item.get("type") == "item_reference":
739
- return cast(ItemReference, item)
740
- return None
741
-
742
- @classmethod
743
- def maybe_response_output_message(cls, item: Any) -> ResponseOutputMessageParam | None:
744
- # ResponseOutputMessage is only used for messages with role assistant
745
- if (
746
- isinstance(item, dict)
747
- and item.get("type") == "message"
748
- and item.get("role") == "assistant"
749
- ):
750
- return cast(ResponseOutputMessageParam, item)
751
- return None
752
-
753
- @classmethod
754
- def extract_text_content(
755
- cls, content: str | Iterable[ResponseInputContentParam]
756
- ) -> str | list[ChatCompletionContentPartTextParam]:
757
- all_content = cls.extract_all_content(content)
758
- if isinstance(all_content, str):
759
- return all_content
760
- out: list[ChatCompletionContentPartTextParam] = []
761
- for c in all_content:
762
- if c.get("type") == "text":
763
- out.append(cast(ChatCompletionContentPartTextParam, c))
764
- return out
765
-
766
- @classmethod
767
- def extract_all_content(
768
- cls, content: str | Iterable[ResponseInputContentParam]
769
- ) -> str | list[ChatCompletionContentPartParam]:
770
- if isinstance(content, str):
771
- return content
772
- out: list[ChatCompletionContentPartParam] = []
773
-
774
- for c in content:
775
- if isinstance(c, dict) and c.get("type") == "input_text":
776
- casted_text_param = cast(ResponseInputTextParam, c)
777
- out.append(
778
- ChatCompletionContentPartTextParam(
779
- type="text",
780
- text=casted_text_param["text"],
781
- )
782
- )
783
- elif isinstance(c, dict) and c.get("type") == "input_image":
784
- casted_image_param = cast(ResponseInputImageParam, c)
785
- if "image_url" not in casted_image_param or not casted_image_param["image_url"]:
786
- raise UserError(
787
- f"Only image URLs are supported for input_image {casted_image_param}"
788
- )
789
- out.append(
790
- ChatCompletionContentPartImageParam(
791
- type="image_url",
792
- image_url={
793
- "url": casted_image_param["image_url"],
794
- "detail": casted_image_param["detail"],
795
- },
796
- )
797
- )
798
- elif isinstance(c, dict) and c.get("type") == "input_file":
799
- raise UserError(f"File uploads are not supported for chat completions {c}")
800
- else:
801
- raise UserError(f"Unknown content: {c}")
802
- return out
803
-
804
- @classmethod
805
- def items_to_messages(
806
- cls,
807
- items: str | Iterable[TResponseInputItem],
808
- ) -> list[ChatCompletionMessageParam]:
809
- """
810
- Convert a sequence of 'Item' objects into a list of ChatCompletionMessageParam.
811
-
812
- Rules:
813
- - EasyInputMessage or InputMessage (role=user) => ChatCompletionUserMessageParam
814
- - EasyInputMessage or InputMessage (role=system) => ChatCompletionSystemMessageParam
815
- - EasyInputMessage or InputMessage (role=developer) => ChatCompletionDeveloperMessageParam
816
- - InputMessage (role=assistant) => Start or flush a ChatCompletionAssistantMessageParam
817
- - response_output_message => Also produces/flushes a ChatCompletionAssistantMessageParam
818
- - tool calls get attached to the *current* assistant message, or create one if none.
819
- - tool outputs => ChatCompletionToolMessageParam
820
- """
821
-
822
- if isinstance(items, str):
823
- return [
824
- ChatCompletionUserMessageParam(
825
- role="user",
826
- content=items,
827
- )
828
- ]
829
-
830
- result: list[ChatCompletionMessageParam] = []
831
- current_assistant_msg: ChatCompletionAssistantMessageParam | None = None
832
-
833
- def flush_assistant_message() -> None:
834
- nonlocal current_assistant_msg
835
- if current_assistant_msg is not None:
836
- # The API doesn't support empty arrays for tool_calls
837
- if not current_assistant_msg.get("tool_calls"):
838
- del current_assistant_msg["tool_calls"]
839
- result.append(current_assistant_msg)
840
- current_assistant_msg = None
841
-
842
- def ensure_assistant_message() -> ChatCompletionAssistantMessageParam:
843
- nonlocal current_assistant_msg
844
- if current_assistant_msg is None:
845
- current_assistant_msg = ChatCompletionAssistantMessageParam(role="assistant")
846
- current_assistant_msg["tool_calls"] = []
847
- return current_assistant_msg
848
-
849
- for item in items:
850
- # 1) Check easy input message
851
- if easy_msg := cls.maybe_easy_input_message(item):
852
- role = easy_msg["role"]
853
- content = easy_msg["content"]
854
-
855
- if role == "user":
856
- flush_assistant_message()
857
- msg_user: ChatCompletionUserMessageParam = {
858
- "role": "user",
859
- "content": cls.extract_all_content(content),
860
- }
861
- result.append(msg_user)
862
- elif role == "system":
863
- flush_assistant_message()
864
- msg_system: ChatCompletionSystemMessageParam = {
865
- "role": "system",
866
- "content": cls.extract_text_content(content),
867
- }
868
- result.append(msg_system)
869
- elif role == "developer":
870
- flush_assistant_message()
871
- msg_developer: ChatCompletionDeveloperMessageParam = {
872
- "role": "developer",
873
- "content": cls.extract_text_content(content),
874
- }
875
- result.append(msg_developer)
876
- elif role == "assistant":
877
- flush_assistant_message()
878
- msg_assistant: ChatCompletionAssistantMessageParam = {
879
- "role": "assistant",
880
- "content": cls.extract_text_content(content),
881
- }
882
- result.append(msg_assistant)
883
- else:
884
- raise UserError(f"Unexpected role in easy_input_message: {role}")
885
-
886
- # 2) Check input message
887
- elif in_msg := cls.maybe_input_message(item):
888
- role = in_msg["role"]
889
- content = in_msg["content"]
890
- flush_assistant_message()
891
-
892
- if role == "user":
893
- msg_user = {
894
- "role": "user",
895
- "content": cls.extract_all_content(content),
896
- }
897
- result.append(msg_user)
898
- elif role == "system":
899
- msg_system = {
900
- "role": "system",
901
- "content": cls.extract_text_content(content),
902
- }
903
- result.append(msg_system)
904
- elif role == "developer":
905
- msg_developer = {
906
- "role": "developer",
907
- "content": cls.extract_text_content(content),
908
- }
909
- result.append(msg_developer)
910
- else:
911
- raise UserError(f"Unexpected role in input_message: {role}")
912
-
913
- # 3) response output message => assistant
914
- elif resp_msg := cls.maybe_response_output_message(item):
915
- flush_assistant_message()
916
- new_asst = ChatCompletionAssistantMessageParam(role="assistant")
917
- contents = resp_msg["content"]
918
-
919
- text_segments = []
920
- for c in contents:
921
- if c["type"] == "output_text":
922
- text_segments.append(c["text"])
923
- elif c["type"] == "refusal":
924
- new_asst["refusal"] = c["refusal"]
925
- elif c["type"] == "output_audio":
926
- # Can't handle this, b/c chat completions expects an ID which we dont have
927
- raise UserError(
928
- f"Only audio IDs are supported for chat completions, but got: {c}"
929
- )
930
- else:
931
- raise UserError(f"Unknown content type in ResponseOutputMessage: {c}")
932
-
933
- if text_segments:
934
- combined = "\n".join(text_segments)
935
- new_asst["content"] = combined
936
-
937
- new_asst["tool_calls"] = []
938
- current_assistant_msg = new_asst
939
-
940
- # 4) function/file-search calls => attach to assistant
941
- elif file_search := cls.maybe_file_search_call(item):
942
- asst = ensure_assistant_message()
943
- tool_calls = list(asst.get("tool_calls", []))
944
- new_tool_call = ChatCompletionMessageToolCallParam(
945
- id=file_search["id"],
946
- type="function",
947
- function={
948
- "name": "file_search_call",
949
- "arguments": json.dumps(
950
- {
951
- "queries": file_search.get("queries", []),
952
- "status": file_search.get("status"),
953
- }
954
- ),
955
- },
956
- )
957
- tool_calls.append(new_tool_call)
958
- asst["tool_calls"] = tool_calls
959
-
960
- elif func_call := cls.maybe_function_tool_call(item):
961
- asst = ensure_assistant_message()
962
- tool_calls = list(asst.get("tool_calls", []))
963
- arguments = func_call["arguments"] if func_call["arguments"] else "{}"
964
- new_tool_call = ChatCompletionMessageToolCallParam(
965
- id=func_call["call_id"],
966
- type="function",
967
- function={
968
- "name": func_call["name"],
969
- "arguments": arguments,
970
- },
971
- )
972
- tool_calls.append(new_tool_call)
973
- asst["tool_calls"] = tool_calls
974
- # 5) function call output => tool message
975
- elif func_output := cls.maybe_function_tool_call_output(item):
976
- flush_assistant_message()
977
- msg: ChatCompletionToolMessageParam = {
978
- "role": "tool",
979
- "tool_call_id": func_output["call_id"],
980
- "content": func_output["output"],
981
- }
982
- result.append(msg)
983
-
984
- # 6) item reference => handle or raise
985
- elif item_ref := cls.maybe_item_reference(item):
986
- raise UserError(
987
- f"Encountered an item_reference, which is not supported: {item_ref}"
988
- )
989
-
990
- # 7) If we haven't recognized it => fail or ignore
991
- else:
992
- raise UserError(f"Unhandled item type or structure: {item}")
993
-
994
- flush_assistant_message()
995
- return result
996
-
997
-
998
- class ToolConverter:
999
- @classmethod
1000
- def to_openai(cls, tool: Tool) -> ChatCompletionToolParam:
1001
- if isinstance(tool, FunctionTool):
1002
- return {
1003
- "type": "function",
1004
- "function": {
1005
- "name": tool.name,
1006
- "description": tool.description or "",
1007
- "parameters": tool.params_json_schema,
1008
- },
1009
- }
1010
-
1011
- raise UserError(
1012
- f"Hosted tools are not supported with the ChatCompletions API. Got tool type: "
1013
- f"{type(tool)}, tool: {tool}"
1014
- )
1015
-
1016
- @classmethod
1017
- def convert_handoff_tool(cls, handoff: Handoff[Any]) -> ChatCompletionToolParam:
1018
- return {
1019
- "type": "function",
1020
- "function": {
1021
- "name": handoff.tool_name,
1022
- "description": handoff.tool_description,
1023
- "parameters": handoff.input_json_schema,
1024
- },
1025
- }