Raise `ModelAPIError` instead of `ValidationError` when an `OpenRouterModel` stream drops mid-response
Related: #8722 (found while auditing provider error mapping for it)
When an OpenRouterModel stream dropped mid-response (read timeout or connection reset), the run failed with a pydantic ValidationError for _OpenRouterError instead of ModelAPIError. OpenRouterStreamedResponse._validate_response caught every openai.APIError to parse OpenRouter's in-stream error envelope, and that includes APIConnectionError, which has no body. An in-stream error object whose code isn't an integer failed the same way.
- Connection errors are re-raised, so the shared
OpenAIStreamedResponsemapping turns them intoModelAPIError, as it already does for OpenAI. - An error object that doesn't validate as OpenRouter's envelope raises
ModelAPIError(no status code) chained from the SDK error. - The existing
ModelHTTPErrorfor a valid envelope is unchanged except that it's now chained from the SDK error (__cause__).
New public surface: none.
User-visible behavior
agent.run_stream(...) on OpenRouterModel, connection drops mid-stream
-pydantic_core.ValidationError: 1 validation error for _OpenRouterError
+pydantic_ai.exceptions.ModelAPIError: Request timed out. (__cause__: openai.APITimeoutError)
Verification
tests/models/test_openrouter.py::test_openrouter_stream_transport_error_raises_model_api_error([read-timeout],[connection-reset])tests/models/test_openrouter.py::test_openrouter_stream_error_without_integer_code_raises_model_api_error- All three fail with
ValidationErrorwhen the fix is reverted.test_openrouter_stream_error(cassette, valid envelope) still raisesModelHTTPError.
What changes for existing users: these failures now raise ModelAPIError instead of ValidationError, so except ModelAPIError handlers catch them. FallbackModel still doesn't fall back mid-stream, as for any provider.
Not changed here
- The status on a valid in-stream envelope still comes from the envelope's
coderather than the HTTP response (which was 200). Changing that affectsexcept ModelHTTPErrorhandlers and belongs to the error-category design discussion. - An error object as the first chunk bypasses
_validate_responseand escapes as a rawopenai.APIError; that is the #8722 fix to_map_api_errors.
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.
๐ค Generated with Claude Code