Fix: Handle content moderation in responses.parse() #2850
+229
−12
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
Fixed
responses.parse()to properly handle content moderation responses. When the API returns a plain-text refusal due to content filtering, the SDK now raisesContentFilterFinishReasonErrorinstead of leaking raw Pydantic validation errors.Problem
When using
responses.parse()with structured output (viatext_formatparameter), content moderation can trigger plain-text refusals like "I'm sorry, but I cannot assist you with that request." These refusals are not valid JSON and causepydantic_core.ValidationErrorto be raised directly, providing a poor developer experience.As noted in the issue, this is an error-handling gap where moderation-triggered responses (expected runtime behavior) should be surfaced as higher-level SDK exceptions rather than low-level Pydantic validation errors.
Solution
Modified
parse_text()to:response.incomplete_details.reason == "content_filter"to detect moderationContentFilterFinishReasonErrorfor content filter casesAPIResponseValidationErrorwith helpful context for other parsing failuresTesting
Added comprehensive test cases:
Impact
Fixes #2834