Skip to content

Fixes #1582: Handling of structured CompletionUsage response values for token usage #1583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions evals/cli/oaieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ def to_number(x: str) -> Union[int, float, str]:
try:
add_token_usage_to_result(result, recorder)
except Exception as e:
logger.error(f"Failed to add token usage to result: {e}. Eval results will be reported and are not affected.")
logger.error(
f"Failed to add token usage to result: {e}. Eval results will be reported and are not affected."
)
recorder.record_final_report(result)

if not (args.dry_run or args.local_run):
Expand Down Expand Up @@ -266,6 +268,13 @@ def build_recorder(
)


def _extract_token_count(token_field: Any) -> int:
if isinstance(token_field, int):
return token_field
if hasattr(token_field, "total"):
return token_field.total
return 0 # safe default clearly stated

def add_token_usage_to_result(result: dict[str, Any], recorder: RecorderBase) -> None:
"""
Add token usage from logged sampling events to the result dictionary from the recorder.
Expand All @@ -274,16 +283,20 @@ def add_token_usage_to_result(result: dict[str, Any], recorder: RecorderBase) ->
sampling_events = recorder.get_events("sampling")
for event in sampling_events:
if "usage" in event.data:
usage_events.append(dict(event.data["usage"]))
usage_events.append(event.data["usage"])

logger.info(f"Found {len(usage_events)}/{len(sampling_events)} sampling events with usage data")

if usage_events:
# Sum up the usage of all samples (assumes the usage is the same for all samples)
total_usage = {
key: sum(u[key] if u[key] is not None else 0 for u in usage_events)
for key in usage_events[0]
key: sum(_extract_token_count(getattr(u, key, 0)) for u in usage_events)
for key in ["completion_tokens", "prompt_tokens", "total_tokens"]
}

total_usage_str = "\n".join(f"{key}: {value:,}" for key, value in total_usage.items())
logger.info(f"Token usage from {len(usage_events)} sampling events:\n{total_usage_str}")

for key, value in total_usage.items():
keyname = f"usage_{key}"
if keyname not in result:
Expand Down