TECHNOLOGY

Pydantic AI input limits need explicit preflight counting

In this article
THE QUICK TAKE

Select preflight counting when preventing an oversized send matters, and distinguish full-context size from cumulative usage or cache-miss cost.

Identify what the input boundary must prevent

A research agent accumulates extracted passages until its next prompt becomes too large for the application’s intended context budget. Pydantic AI’s agent guide provides an input limit for each request. Before configuring it, distinguish a limit that detects an oversized response’s reported input from a guard that must stop an oversized request before it is sent. Those behaviors have different cost and timing consequences.

Read the default observation timing

The usage reference defines per_request_input_tokens_limit and explains that without preflight counting, it uses provider-reported input tokens after the response. The request can already have been sent and billed when the limit is detected. Do not present this default as a guarantee that no oversized prompt crosses the provider boundary. It is an enforcement decision based on an observation that arrives later.

Enable counting before the request deliberately

Setting count_tokens_before_request=True requests a counting pass before sending, supporting advance enforcement of input limits. The reference notes additional counting overhead. Review support and behavior of the selected model implementation rather than assuming counting is free local arithmetic. If source collection must be shortened, make that selection explicit before generation, preserving the passages required for the user’s question instead of blindly discarding the end of the prompt.

Separate per-request size from cumulative usage

A per-request cap evaluates an individual request’s input, while the cumulative input limit concerns the run’s aggregate usage. Cached-prefix tokens count toward the full input size under the documented normalization. A largely cached context can therefore still exceed a size cap; cache efficiency does not make its context smaller. Task budgets should state which dimension the application is controlling and avoid using a context limit as a promise about uncached billing.

Treat the limit outcome as interrupted work

The exception reference defines the limit failure rather than an ordinary accepted result. Preserve the evidence collected before it and record whether the rejected step was stopped by preflight or after a billed response. Tool observations make that difference inspectable. The operational explanation can then distinguish excessive accumulated evidence, a deliberately bounded send and an already-paid response that triggered later enforcement.

Earn rental income from GPUs

Have idle GPUs or looking to fund AI infrastructure? Retrivium finds a rental platform, sets up the server and helps you assess income and costs with a pilot.

Explore GPU hosting
← All articles