Fix metadata token counting for Anthropic format responses #109
+45
−6
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes metadata token counting for Anthropic-format API responses (used by /v1/messages endpoint).
The _log_metadata method in TransactionLogger only supported OpenAI format usage keys (prompt_tokens, completion_tokens) but Anthropic responses use different keys (input_tokens, output_tokens). This caused null token counts in metadata.json for providers like dedaluslabs and firmware when using the Anthropic-compatible /v1/messages endpoint.
Changes:
Add fallback from OpenAI to Anthropic format for token counts (prompt_tokens → input_tokens, completion_tokens → output_tokens)
Use explicit None checks instead of or to correctly handle 0 values
Calculate total_tokens if missing from Anthropic responses (sum of input + output)
Handle stop_reason (Anthropic format) as well as finish_reason (OpenAI format)
Testing Done:
Verified dedaluslabs and firmware providers now log token counts correctly in metadata.json when using /v1/messages endpoint
Confirmed OpenAI format responses continue to work unchanged
Tested edge case where token counts are 0 (now correctly logged as 0 instead of falling back)
Important
Fixes token counting for Anthropic-format API responses in
TransactionLoggerby adding support for Anthropic keys and handling zero token counts._log_metadata()oftransaction_logger.py.prompt_tokens,completion_tokens) to Anthropic format keys (input_tokens,output_tokens).Nonechecks to handle zero token counts correctly.total_tokensif missing in Anthropic responses by summinginput_tokensandoutput_tokens.stop_reason(Anthropic) alongsidefinish_reason(OpenAI)./v1/messagesendpoint.This description was created by
for 6a5f601. You can customize this summary. It will automatically update as commits are pushed.