sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

fix(openai): support tools returning image content

Open Ratish1 opened this issue 2 months ago • 10 comments

Description

This PR resolves an invalid_request_error from the OpenAI API that occurred when a tool returned image content. The API requires that image content only to be included in messages with the user role, whereas tool results are sent with the tool role.

This fix implements a workaround by post-processing tool messages before they are sent to the API:

  • A new _split_tool_message_images helper method separates any image_url content from the text content in a tool's output.
  • The original tool message is sent with only the text content. If no text was present, a default success message is used.
  • A new user message is created immediately following the tool message, containing only the extracted images.

Note: I've also enabled the integration test (test_tool_returning_images), but I don't have an OpenAI API key with credits in them to verify it myself. The unit tests all pass on my end, so the core logic is confirmed to be working.

Related Issues

Closes #320

Documentation PR

N/A

Type of Change

Bug fix

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce warnings in consuming repositories: agents-docs, agents-tools, agents-cli

  • [x] I ran hatch run prepare
  • [x] I ran pre-commit hooks, formatting and linting
  • [x] Added unit tests to tests/strands/models/test_openai.py:
  • test_split_tool_message_images_with_image → passed
  • test_split_tool_message_images_without_image → passed
  • test_split_tool_message_images_only_image → passed
  • test_format_request_messages_with_tool_result_containing_image → passed
  • test_format_request_messages_with_multiple_images_in_tool_result → passed

Checklist

  • [x] I have read the CONTRIBUTING document
  • [x] I have added any necessary tests that prove my fix is effective or my feature works
  • [ ] I have updated the documentation accordingly
  • [ ] I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • [x] My changes generate no new warnings
  • [x] Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Ratish1 avatar Oct 23 '25 11:10 Ratish1