Record each failed `FallbackModel` attempt with its model, timing, error and usage, and count rejected responses in `RunUsage`

Merged
DO
2mo ago
+1503-96

When a FallbackModel moves past one or more models before one answers, the result doesn't say which models failed, how long they took or what they cost. A response a fallback_on handler rejected adds its cost to the winner's usage.cost, but its tokens are dropped. When every response is rejected, nothing is counted. This PR records each attempt with its accounting, counts what was billed, and derives the attempt spans from that same record (#8899). It also settles #8498: request_limit counts turns, not calls to the provider. Part of #9335.

[!WARNING]
Compatibility impact: The answering response's usage.cost no longer includes the cost of rejected responses. result.usage.cost still does. RunUsage tokens and the token limits now include rejected responses' tokens, so a limit can be reached sooner.

Why this can ship in a minor release: it fixes under-counting of billed usage. The fold into the winner's usage was undocumented, and it priced the chat span with another model's cost.

Migration: Read result.usage.cost for a fallback chain's total cost, or add each response.failed_attempts[i].usage.cost to the answering response's own.

New public surface:

  • ModelRequestAttempt (pydantic_ai.messages and top level): model_name, provider_name, outcome ('error' or 'rejected'), error ('Type: message'), timestamp, duration, and usage (None when unknown).
  • ModelResponse.failed_attempts, StreamedResponse.failed_attempts and FallbackExceptionGroup.attempts.

User-visible behavior, for a rejected 100/10-token response followed by an accepted 20/2 (the #8899 repro):

- result.usage == RunUsage(cost=0.003, input_tokens=20, output_tokens=2, requests=1)
+ result.usage == RunUsage(cost=0.003, input_tokens=120, output_tokens=12, requests=1)
- result.response.usage.cost == 0.003   # both models' cost, on the winner
+ result.response.usage.cost == 0.002   # its own
+ result.response.failed_attempts == [ModelRequestAttempt(model_name='primary', outcome='rejected', usage=RequestUsage(100, 10, cost=0.001), ...)]
  • All models fail: the graph still records the attempts' usage and checks the token and cost limits. A limit that is exceeded is raised as UsageLimitExceeded, caused by the group.
  • What doesn't count: attempts never increase RunUsage.requests. The requests/request_limit docstrings, docs/agent.md and docs/retries.md now say so, and the retries formula gains the fallback-chain factor F. No behavior change.
  • What stays out of history: the rejected response's parts never enter the message history.
  • Continuations: the attempts survive when a continuation merges its segments.
  • Spans:
    • The attempt spans come from the same record via pydantic_ai/_model_request_attempts.py, which the Fallback capability in #9348 will reuse.
    • They are renamed model request attempt {model} (attribute pydantic_ai.model_request.attempt), because that loop also retries the same model.
    • A rejected attempt's span carries gen_ai.usage.* and operation.cost, so traces keep its spend.

Verification: in tests/models/test_fallback.py: test_response_handler_rejected_usage_is_attributed_to_its_attempt, test_all_rejected_usage_counts_towards_the_run, test_rejected_usage_counts_towards_token_limits, test_all_rejected_usage_counts_towards_token_limits, test_nested_fallback_keeps_the_inner_attempts, test_failed_attempts_on_a_completed_stream, test_failed_attempts_survive_a_continuation, test_failed_attempts_round_trip_through_message_history and test_response_rejected_span. Content gating: test_no_content_reaches_telemetry_from_a_failed_fallback_attempt, which now also replays the history. Runnable docs example: fallback_model_attempts.py in docs/models/overview.md.

What changes for existing users: fallback runs now report the usage of rejected responses in RunUsage, and the answering response's usage is its own.

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