Withdrawn Proposal #00216ai
Provider-Specific Token Usage Mapping
An internal module to extract token usage from AI provider responses and convert them to a unified format.
Superseded. The public API described here (
TokenUsageProvider,extract_token_usage,TokenUsage) was consolidated into the privatefilters/src/token_usage/subsystem. Provider parsing is now handled by private modules (providers.rs,streaming.rs) with no public exports beyond the two filter types. See proposal #210 for the current design.
What?
An internal module to extract token usage from AI provider responses and convert them to a unified format.
Each provider returns token counts in different JSON structures:
| Provider | Field Path |
|---|---|
| OpenAI | usage.prompt_tokens, usage.completion_tokens |
| Anthropic | usage.input_tokens, usage.output_tokens |
usageMetadata.promptTokenCount, usageMetadata.candidatesTokenCount | |
| Bedrock (InvokeModel) | inputTokenCount, outputTokenCount (root level) |
| Bedrock (Converse) | usage.inputTokens, usage.outputTokens |
| Azure | Same as OpenAI |
This proposal adds a mapping library that:
- Takes a provider identifier and response body
- Parses the provider-specific JSON structure
- Returns a unified
TokenUsagestruct
pub struct TokenUsage { /* fields private */ }
impl TokenUsage {
pub fn input_tokens(&self) -> u64;
pub fn output_tokens(&self) -> u64;
pub fn total_tokens(&self) -> u64; // from response, or computed: input + output
}
pub enum TokenUsageProvider {
OpenAi,
Anthropic,
Google,
Bedrock,
Azure,
}
/// Extracts token usage from a provider's JSON response body.
/// Returns `None` if usage data is missing or malformed.
pub fn extract_token_usage(provider: TokenUsageProvider, body: &[u8]) -> Option<TokenUsage>;
Goals
- Extract token usage from 5 AI provider response formats
- Provide a unified
TokenUsagerepresentation - Enable reuse by other filters (#210, #212) and systems
Non-Goals
- Rate limiting logic (separate issue)
- Streaming-specific logic: SSE parsing, chunk identification (#211)
- Exposing tokens in headers or metrics (#214)
Note on streaming: This module parses JSON containing usage data,
regardless of whether it came from a non-streaming response or the
final chunk of a streaming response. The JSON structure is the same
in both cases. Streaming-specific handling (SSE format, identifying
which chunk has usage) is #211’s scope.
Why?
Motivation
Other filters and systems need token counts in a consistent format. Without this library, each consumer would need to implement provider-specific parsing separately.
This is foundational work for the Token Counting epic (#20) that enables:
- Token-based rate limiting
- Usage logging and metrics
- Cost tracking
User Stories
As a rate limiting filter, I need consistent token counts regardless of which AI provider was used, so that I can enforce limits without provider-specific code.
As the token counting filter (#210), I need a mapping from each provider’s field names to a unified format, so that I can parse any provider’s response.
As a logging/metrics system, I need token data in a predictable structure, so that I can track usage across all providers consistently.
How?
Module Location
The module lives at filter/src/builtins/http/ai/token_usage/ with the
following structure:
token_usage/
├── mod.rs # Public API: TokenUsage, Provider, extract_token_usage()
├── providers.rs # Internal parsing logic per provider
└── tests.rs # Unit tests
Implementation Approach
Private fields with public getters -
TokenUsagefields are private to allow internal representation changes without breaking the API. Thetotal_tokens()getter returns the provider’s value if present, otherwise computesinput + output.Serde for JSON parsing - Each provider has internal structs with
#[derive(Deserialize)]that map to their specific JSON format. Field renaming (e.g.,camelCase) is handled via serde attributes.Bedrock dual-format support - The parser tries Converse API format first (
usage.inputTokens), then falls back to InvokeModel format (inputTokenCountat root level).All-or-nothing parsing -
extract_token_usage()returnsOption<TokenUsage>. If parsing succeeds, all fields are present. If any required field is missing or JSON is malformed, returnsNone.
Public API
Exported from praxis_filter crate:
use praxis_filter::{TokenUsage, TokenUsageProvider, extract_token_usage};
let usage = extract_token_usage(TokenUsageProvider::OpenAi, response_body);
if let Some(u) = usage {
// Access token counts via getters:
// u.input_tokens(), u.output_tokens(), u.total_tokens()
}
Open Question
This proposal focuses on extracting token usage only. Should we consider a broader “provider response translator” that normalizes the entire response to a common format (e.g., OpenAI)?
If there are future requirements that would benefit from full response translation, it may be worth designing the library with that in mind.