|
21 | 21 | from openai.types.responses.response_code_interpreter_tool_call import ( |
22 | 22 | ResponseCodeInterpreterToolCall, |
23 | 23 | ) |
| 24 | +from openai.types.responses.response_function_call_output_item_list_param import ( |
| 25 | + ResponseFunctionCallOutputItemListParam, |
| 26 | + ResponseFunctionCallOutputItemParam, |
| 27 | +) |
| 28 | +from openai.types.responses.response_input_file_content_param import ResponseInputFileContentParam |
| 29 | +from openai.types.responses.response_input_image_content_param import ResponseInputImageContentParam |
24 | 30 | from openai.types.responses.response_input_item_param import ( |
25 | 31 | ComputerCallOutput, |
26 | 32 | FunctionCallOutput, |
|
36 | 42 | ) |
37 | 43 | from openai.types.responses.response_reasoning_item import ResponseReasoningItem |
38 | 44 | from pydantic import BaseModel |
39 | | -from typing_extensions import TypeAlias |
| 45 | +from typing_extensions import TypeAlias, assert_never |
40 | 46 |
|
41 | 47 | from .exceptions import AgentsException, ModelBehaviorError |
| 48 | +from .logger import logger |
| 49 | +from .tool import ( |
| 50 | + ToolOutputFileContent, |
| 51 | + ToolOutputImage, |
| 52 | + ToolOutputText, |
| 53 | + ValidToolOutputPydanticModels, |
| 54 | + ValidToolOutputPydanticModelsTypeAdapter, |
| 55 | +) |
42 | 56 | from .usage import Usage |
43 | 57 |
|
44 | 58 | if TYPE_CHECKING: |
@@ -298,11 +312,93 @@ def text_message_output(cls, message: MessageOutputItem) -> str: |
298 | 312 |
|
299 | 313 | @classmethod |
300 | 314 | def tool_call_output_item( |
301 | | - cls, tool_call: ResponseFunctionToolCall, output: str |
| 315 | + cls, tool_call: ResponseFunctionToolCall, output: Any |
302 | 316 | ) -> FunctionCallOutput: |
303 | | - """Creates a tool call output item from a tool call and its output.""" |
| 317 | + """Creates a tool call output item from a tool call and its output. |
| 318 | +
|
| 319 | + Accepts either plain values (stringified) or structured outputs using |
| 320 | + input_text/input_image/input_file shapes. Structured outputs may be |
| 321 | + provided as Pydantic models or dicts, or an iterable of such items. |
| 322 | + """ |
| 323 | + |
| 324 | + converted_output = cls._convert_tool_output(output) |
| 325 | + |
304 | 326 | return { |
305 | 327 | "call_id": tool_call.call_id, |
306 | | - "output": output, |
| 328 | + "output": converted_output, |
307 | 329 | "type": "function_call_output", |
308 | 330 | } |
| 331 | + |
| 332 | + @classmethod |
| 333 | + def _convert_tool_output(cls, output: Any) -> str | ResponseFunctionCallOutputItemListParam: |
| 334 | + """Converts a tool return value into an output acceptable by the Responses API.""" |
| 335 | + |
| 336 | + # If the output is either a single or list of the known structured output types, convert to |
| 337 | + # ResponseFunctionCallOutputItemListParam. Else, just stringify. |
| 338 | + if isinstance(output, (list, tuple)): |
| 339 | + maybe_converted_output_list = [ |
| 340 | + cls._maybe_get_output_as_structured_function_output(item) for item in output |
| 341 | + ] |
| 342 | + if all(maybe_converted_output_list): |
| 343 | + return [ |
| 344 | + cls._convert_single_tool_output_pydantic_model(item) |
| 345 | + for item in maybe_converted_output_list |
| 346 | + if item is not None |
| 347 | + ] |
| 348 | + else: |
| 349 | + return str(output) |
| 350 | + else: |
| 351 | + maybe_converted_output = cls._maybe_get_output_as_structured_function_output(output) |
| 352 | + if maybe_converted_output: |
| 353 | + return [cls._convert_single_tool_output_pydantic_model(maybe_converted_output)] |
| 354 | + else: |
| 355 | + return str(output) |
| 356 | + |
| 357 | + @classmethod |
| 358 | + def _maybe_get_output_as_structured_function_output( |
| 359 | + cls, output: Any |
| 360 | + ) -> ValidToolOutputPydanticModels | None: |
| 361 | + if isinstance(output, (ToolOutputText, ToolOutputImage, ToolOutputFileContent)): |
| 362 | + return output |
| 363 | + elif isinstance(output, dict): |
| 364 | + try: |
| 365 | + return ValidToolOutputPydanticModelsTypeAdapter.validate_python(output) |
| 366 | + except pydantic.ValidationError: |
| 367 | + logger.debug("dict was not a valid tool output pydantic model") |
| 368 | + return None |
| 369 | + |
| 370 | + return None |
| 371 | + |
| 372 | + @classmethod |
| 373 | + def _convert_single_tool_output_pydantic_model( |
| 374 | + cls, output: ValidToolOutputPydanticModels |
| 375 | + ) -> ResponseFunctionCallOutputItemParam: |
| 376 | + if isinstance(output, ToolOutputText): |
| 377 | + return {"type": "input_text", "text": output.text} |
| 378 | + elif isinstance(output, ToolOutputImage): |
| 379 | + # Forward all provided optional fields so the Responses API receives |
| 380 | + # the correct identifiers and settings for the image resource. |
| 381 | + result: ResponseInputImageContentParam = {"type": "input_image"} |
| 382 | + if output.image_url is not None: |
| 383 | + result["image_url"] = output.image_url |
| 384 | + if output.file_id is not None: |
| 385 | + result["file_id"] = output.file_id |
| 386 | + if output.detail is not None: |
| 387 | + result["detail"] = output.detail |
| 388 | + return result |
| 389 | + elif isinstance(output, ToolOutputFileContent): |
| 390 | + # Forward all provided optional fields so the Responses API receives |
| 391 | + # the correct identifiers and metadata for the file resource. |
| 392 | + result_file: ResponseInputFileContentParam = {"type": "input_file"} |
| 393 | + if output.file_data is not None: |
| 394 | + result_file["file_data"] = output.file_data |
| 395 | + if output.file_url is not None: |
| 396 | + result_file["file_url"] = output.file_url |
| 397 | + if output.file_id is not None: |
| 398 | + result_file["file_id"] = output.file_id |
| 399 | + if output.filename is not None: |
| 400 | + result_file["filename"] = output.filename |
| 401 | + return result_file |
| 402 | + else: |
| 403 | + assert_never(output) |
| 404 | + raise ValueError(f"Unexpected tool output type: {output}") |
0 commit comments