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

Improve error messages for Image.to_pil() and ModelClient attribute access

Open Copilot opened this issue 8 months ago • 0 comments

This PR addresses the confusing error messages that users encounter when working with pythonic models, specifically two common scenarios:

Problem

Users were getting unhelpful error messages like:

  • cannot identify image file <_io.BytesIO object at 0x...> when working with invalid image data
  • 'ModelClient' object has no attribute 'predict' with no guidance on available methods

These cryptic messages left users stuck without clear guidance on how to resolve the issues.

Solution

1. Improved Image.to_pil() Error Messages

Before:

# UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f8e01378810>

After:

# ValueError: Invalid image data: The image bytes cannot be decoded as a valid image format. 
# Please ensure the image is in a supported format (JPEG, PNG, GIF, BMP, etc.) and the data 
# is not corrupted. Original error: UnidentifiedImageError: cannot identify image file <_io.BytesIO...>

2. Improved ModelClient.getattr Error Messages

Before:

# AttributeError: 'ModelClient' object has no attribute 'predict'

After:

# AttributeError: 'ModelClient' object has no attribute 'predict'. 
# Available methods: ['generate', 'stream', 'embed']. The model may not have a 'predict' method

Key Features

  • Clear explanations: Users now understand what went wrong
  • Actionable guidance: Specific troubleshooting steps and suggestions
  • Method discovery: Shows available methods when accessing non-existent attributes
  • Context-aware suggestions: Provides hints for common mistakes (e.g., predict vs _predict)
  • Backward compatibility: All existing functionality preserved
  • Comprehensive error handling: Covers edge cases like uninitialized models and None signatures

Changes Made

  • Enhanced Image.to_pil() in clarifai/runners/utils/data_types/data_types.py to catch PIL exceptions and provide helpful error messages
  • Improved ModelClient.__getattr__() in clarifai/client/model_client.py to show available methods and provide suggestions
  • Added comprehensive test coverage for all error scenarios and edge cases

The changes are minimal and surgical, focusing only on error message improvements while preserving all existing behavior.

Fixes #655.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Jun 29 '25 10:06 Copilot