Skip to content

Handle malformed API response values in model parsing - #5

Open
IFAKA wants to merge 1 commit into
romanmichaelpaolucci:mainfrom
IFAKA:fix/model-parsing-safety
Open

Handle malformed API response values in model parsing#5
IFAKA wants to merge 1 commit into
romanmichaelpaolucci:mainfrom
IFAKA:fix/model-parsing-safety

Conversation

@IFAKA

@IFAKA IFAKA commented Dec 19, 2025

Copy link
Copy Markdown

Problem

The AnalysisResult.from_dict() method uses direct float() and int() conversions without error handling:

confidence=float(classification.get("confidence", 0)),
word_count=int(analysis.get("word_count", 0)),

If the API returns malformed data (non-numeric strings, None when key exists, etc.), the SDK crashes with ValueError:

>>> AnalysisResult.from_dict({"classification": {"confidence": "invalid"}})
ValueError: could not convert string to float: 'invalid'

Fix

Add safe conversion helpers that return defaults on failure:

def _safe_float(value: Any, default: float = 0.0) -> float:
    if value is None:
        return default
    try:
        return float(value)
    except (ValueError, TypeError):
        return default

Test

Test 1: Valid data
  ✓ Parsed correctly: confidence=0.85, word_count=10

Test 2: Non-numeric strings
  ✓ Handled gracefully: confidence=0.0, outlook=0.0

Test 3: None values
  ✓ Handled None: confidence=0.0

Test 4: Missing keys
  ✓ Handled missing keys: confidence=0.0

Test 5: Empty dict
  ✓ Handled empty dict: label=neutral

==================================================
All tests passed!

Add safe type conversion helpers to prevent ValueError crashes
when API returns non-numeric values for numeric fields.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant