Raise `ModelAPIError` when the OpenAI Responses API reports a failed response or an `error` stream event

Merged
DO
2mo ago
+168-1

Related: #8722 (found while auditing provider error mapping; no separate issue)

OpenAIResponsesModel ignored the error the Responses API reports when it fails a response inside a 200:

  • A stream error event (ResponseErrorEvent) hit the "not yet implemented" warning and was dropped.
  • response.failed, and a non-streamed body with status: failed, only set finish_reason='error'.

Either way the response ended with no parts, so the agent sent the model an output retry. That cost a second paid request, and then the run raised UnexpectedModelBehavior('Exceeded maximum output retries'). A lone error event was worse: it left the response suspended, and the run re-polled 10 times. The provider's code and message were lost in both cases, and FallbackModel never fell back.

Now each of these raises ModelAPIError with the provider's code: message. There is no HTTP status to report, so none is invented. Giving ModelAPIError a structured provider error code of its own is left to a separate design discussion.

  • An error event that opens the stream raises while the stream opens, so FallbackModel's default fallback_on falls back on it. The early insufficient_quota case looks like this.
  • response.failed records the terminal state before raising, so a failed background job is not sent a pointless responses.cancel.
  • cancelled responses and a failed response without an error object behave as before.
  • Policy codes such as invalid_prompt surface as ModelAPIError, just as an HTTP 400 invalid_prompt surfaces as ModelHTTPError on Chat Completions. They are not ContentFilterError.

OpenAI also sends a nested {"type": "error", "error": {...}} event. The SDK raises a bare openai.APIError for it, which #9313 (merged) maps to ModelAPIError; the [stream-error-event-nested] case below covers it.

New public surface: none.

What changes for existing users: a failed Responses API response raises ModelAPIError instead of retrying the model and raising UnexpectedModelBehavior.

Verification

  • tests/models/test_openai_responses.py::test_response_error_raises_model_api_error: real SSE/JSON bytes through httpx2.MockTransport for a mid-stream error event, an opening error event (top-level and nested shapes), a background response.failed, and a non-streamed failed body. It also asserts exactly one request, meaning no retry, re-poll or cancel.
  • tests/models/test_openai_responses.py::test_response_error_event_first_falls_back
  • Each fails with its production change reverted.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.