ccproxy.utils.streaming_metrics¶
ccproxy.utils.streaming_metrics
¶
Streaming metrics extraction utilities.
This module provides utilities for extracting token usage and calculating costs from Anthropic streaming responses in a testable, modular way.
StreamingMetricsCollector
¶
Collects and manages token metrics during streaming responses.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request_id
|
str | None
|
Optional request ID for logging context |
None
|
Source code in ccproxy/utils/streaming_metrics.py
process_chunk
¶
Process a streaming chunk to extract token metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chunk_str
|
str
|
Raw chunk string from streaming response |
required |
Returns:
Type | Description |
---|---|
bool
|
True if this was the final chunk with complete metrics, False otherwise |
Source code in ccproxy/utils/streaming_metrics.py
calculate_final_cost
¶
Calculate the final cost based on collected metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
str | None
|
Model name for pricing lookup |
required |
Returns:
Type | Description |
---|---|
float | None
|
Final cost in USD or None if calculation fails |
Source code in ccproxy/utils/streaming_metrics.py
get_metrics
¶
Get the current collected metrics.
Returns:
Type | Description |
---|---|
StreamingTokenMetrics
|
Current token metrics |
extract_usage_from_streaming_chunk
¶
Extract usage information from Anthropic streaming response chunk.
This function looks for usage information in both message_start and message_delta events from Anthropic's streaming API responses. message_start contains initial input tokens, message_delta contains final output tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chunk_data
|
Any
|
Streaming response chunk dictionary |
required |
Returns:
Type | Description |
---|---|
UsageData | None
|
UsageData with token counts or None if no usage found |