Skip to content

Raise MessageParseError when the message field is not a dict - #1214

Open
shashvat-singham wants to merge 1 commit into
anthropics:mainfrom
shashvat-singham:fix/message-parser-non-dict-message
Open

Raise MessageParseError when the message field is not a dict#1214
shashvat-singham wants to merge 1 commit into
anthropics:mainfrom
shashvat-singham:fix/message-parser-non-dict-message

Conversation

@shashvat-singham

Copy link
Copy Markdown

Problem

parse_message wraps every malformation in its own MessageParseError — non-dict input, missing type, missing required fields. But a "message" field that isn't a dict escapes as a bare TypeError:

>>> parse_message({"type": "user", "message": "hi"})
TypeError: string indices must be integers, not 'str'

>>> parse_message({"type": "assistant", "message": "hi"})
TypeError: string indices must be integers, not 'str'

The user/assistant branches catch only KeyError, so indexing into a non-dict falls through. Since this parser consumes the CLI's stream output, one malformed line surfaces as an unrelated-looking TypeError with no message data attached, instead of the documented MessageParseError (which carries data for debugging). The other branches (result, stream_event, system) happen to be shielded because they use .get() first, which makes the asymmetry easy to trip over.

Change

Catch TypeError/AttributeError alongside the existing KeyError in the user and assistant branches and raise MessageParseError("Malformed <kind> message: ...", data), consistent with every other malformation.

Kept as separate except clauses so the existing "Missing required field" wording for KeyError is unchanged — only the previously-uncaught exceptions get the new "Malformed" wording.

Tests

test_parse_non_dict_message_field covers both branches; it fails on main with the raw TypeError and passes with the change.

$ pytest tests/test_message_parser.py -q
81 passed

parse_message wraps malformed input in MessageParseError -- non-dict
data, a missing type, missing required fields all get the parser's own
error type. But a "message" field that is not a dict escaped as a bare
TypeError from indexing into it:

    parse_message({"type": "user", "message": "hi"})
    # TypeError: string indices must be integers, not 'str'

Same for the assistant branch. The existing handlers only catch
KeyError, so TypeError/AttributeError from indexing a non-dict fell
through, and a single malformed line from the CLI stream would surface
as an unrelated-looking TypeError instead of the documented parse error.

Catch TypeError/AttributeError alongside KeyError in both branches and
raise MessageParseError with the offending data attached, like every
other malformation.
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