fix: convert ContentBlock to proper Union type #1399
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #148
Refactored
ContentBlockfrom a single TypedDict with optional fields to a Union of 9 specific TypedDict classes. This enforces the Bedrock API constraint that each ContentBlock must contain exactly one content type (text, image, document, video, toolUse, toolResult, guardContent, reasoningContent, or citationsContent).Changes
Type System Refactoring
Created specific TypedDict classes for each content type:
ContentBlockText- for text contentContentBlockImage- for image contentContentBlockDocument- for document contentContentBlockVideo- for video contentContentBlockToolUse- for tool use requestsContentBlockToolResult- for tool resultsContentBlockGuardContent- for guardrail contentContentBlockReasoningContent- for reasoning contentContentBlockCitations- for citationsAdded TypeGuard functions for type narrowing:
is_text_block(),is_image_block(),is_document_block(), etc.Added
CONTENT_BLOCK_KEYSconstant for runtime validation of content block fieldsCode Updates
ContentBlockTextfor instantiation instead of the now-removedContentBlock()constructorCONTENT_BLOCK_KEYSinstead of accessing__annotations__on the Union typeType Safety Improvements
Before:
After:
Testing
hatch fmt --linter)hatch fmt --formatter)Breaking Changes
Code that was using
ContentBlock(text="...")must now useContentBlockText(text="...").This affects:
Migration:
The
ContentBlocktype itself remains importable as the Union type for type annotations.Rationale
The previous implementation using
TypedDictwithtotal=Falsewas too permissive:The new Union type implementation: