Raise `ModelAPIError` instead of `ValidationError` when an `OpenRouterModel` stream drops mid-response

Merged
DO
2mo ago
+87-4

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 OpenAIStreamedResponse mapping turns them into ModelAPIError, 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 ModelHTTPError for 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 ValidationError when the fix is reverted. test_openrouter_stream_error (cassette, valid envelope) still raises ModelHTTPError.

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 code rather than the HTTP response (which was 200). Changing that affects except ModelHTTPError handlers and belongs to the error-category design discussion.
  • An error object as the first chunk bypasses _validate_response and escapes as a raw openai.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