Skip to content

Add model property to TokenUsage for cost calculation - #1566

Merged
chr-hertel merged 1 commit into
mainfrom
copilot/add-token-usage-model-info
Sep 4, 2026
Merged

chr-hertel merged 1 commit into
mainfrom
copilot/add-token-usage-model-info

Conversation

Copilot AI commented Feb 7, 2026

Copy link
Copy Markdown
Contributor
Q A
Bug fix? no
New feature? yes
Docs? no
Issues Pays into #1565
License MIT

TokenUsage lacked model information, making it impossible to calculate costs accurately when using multiple models with different pricing (e.g., GPT-4o vs embeddings).

Changes

  • TokenUsageInterface/TokenUsage: Added model property and getModel() method
  • TokenUsageAggregation: Returns model name if all usages share the same model, null otherwise
  • All bridge extractors: Extract and populate model from API responses (OpenAI, Anthropic, Gemini, VertexAI, DeepSeek, Perplexity, Mistral, Ollama, Generic)
  • Tests: Added coverage for model property and aggregation behavior
  • Examples: Updated print_token_usage() function in examples/bootstrap.php to display the model property in all token usage examples

Usage

$result = $platform->request('gpt-4o', 'Hello');
$tokenUsage = $result->getMetadata()->get('token_usage');

// Model now available for cost calculation
$model = $tokenUsage->getModel(); // "gpt-4o-2024-08-06"

// Calculate costs based on actual model used
$pricing = [
    'gpt-4o' => ['input' => 2.50, 'output' => 10.00],
    'text-embedding-3-small' => ['input' => 0.02, 'output' => 0],
];

foreach ($pricing as $prefix => $prices) {
    if (str_starts_with($model, $prefix)) {
        $cost = ($tokenUsage->getPromptTokens() / 1_000_000 * $prices['input'])
              + ($tokenUsage->getCompletionTokens() / 1_000_000 * $prices['output']);
    }
}

The model parameter is optional (nullable) for backward compatibility.

Q A
Bug fix? no
New feature? yes
Docs? no
Issues Fix #1583
License MIT
Original prompt

This section details on the original issue you should resolve

<issue_title>[Platform] Token usage - information about used model</issue_title>
<issue_description>Hi, I’m trying to calculate the total cost of a request. For example, a single request may include two or three calls to the OpenAI GPT-4o model and to the embeddings model.

However, when I look at the token usage in the response:

$tokenUsage = $response->getMetadata()->get('token_usage');

I get an array of TokenUsage objects that does not contain any information about which model was used. Since each model has different pricing, how can I correctly calculate the total cost?

Is there another way to retrieve this information?</issue_description>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI changed the title [WIP] Add information about used models in token usage [Platform] Add model property to TokenUsage for cost calculation Feb 7, 2026
Copilot AI requested a review from OskarStark February 7, 2026 19:25
@carsonbot carsonbot changed the title [Platform] Add model property to TokenUsage for cost calculation Add model property to TokenUsage for cost calculation Feb 7, 2026
@OskarStark

Copy link
Copy Markdown
Contributor

@copilot can you update the examples

Copilot AI commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

@copilot can you update the examples

Updated the examples to display the model property in the token usage output. The print_token_usage function in examples/bootstrap.php now shows the model as the first row in the token usage table. (13ba1a7)

Copilot AI changed the title Add model property to TokenUsage for cost calculation Add model property to TokenUsage for cost calculation Feb 7, 2026
@OskarStark

Copy link
Copy Markdown
Contributor

Add changelog entries to components @copilot

@OskarStark

Copy link
Copy Markdown
Contributor

@copilot it's for 0.4 for all components

Comment thread src/platform/CHANGELOG.md Outdated
Comment thread src/platform/src/Bridge/Anthropic/CHANGELOG.md
Comment thread src/platform/src/Bridge/DeepSeek/CHANGELOG.md
Comment thread src/platform/src/Bridge/Gemini/CHANGELOG.md
Comment thread src/platform/src/Bridge/Generic/CHANGELOG.md
Comment thread src/platform/src/Bridge/Mistral/CHANGELOG.md
Comment thread src/platform/src/Bridge/Ollama/CHANGELOG.md
Comment thread src/platform/src/Bridge/Perplexity/CHANGELOG.md
Comment thread src/platform/src/Bridge/VertexAi/CHANGELOG.md
@OskarStark

Copy link
Copy Markdown
Contributor

@copilot

$tokenUsage = $response->getMetadata()->get('token_usage');

returns a TokenUsageAggregation object, which contains a private array of TokenUsage objects.

Each TokenUsage object should have a model property.

There is also an issue with iterating over the TokenUsage objects, since the array is private.

@OskarStark

Copy link
Copy Markdown
Contributor

@copilot rebase and make changes if needed

@RVXD

RVXD commented Mar 13, 2026

Copy link
Copy Markdown

When will this feature be available? Need token_usage stats.

@chr-hertel
chr-hertel force-pushed the copilot/add-token-usage-model-info branch 2 times, most recently from 46dc065 to 19708a0 Compare April 6, 2026 00:28
@chr-hertel
chr-hertel marked this pull request as ready for review April 6, 2026 00:28
@chr-hertel
chr-hertel self-requested a review as a code owner April 6, 2026 00:28
@carsonbot carsonbot added the Feature New feature label Apr 6, 2026
@carsonbot carsonbot changed the title Add model property to TokenUsage for cost calculation Add model property to TokenUsage for cost calculation Apr 6, 2026
@chr-hertel
chr-hertel force-pushed the copilot/add-token-usage-model-info branch 3 times, most recently from a228316 to 2a7b46d Compare April 6, 2026 00:38
@chr-hertel
chr-hertel force-pushed the copilot/add-token-usage-model-info branch from 2a7b46d to bc33af3 Compare September 4, 2026 22:23
@chr-hertel chr-hertel added the BC Break Breaking the Backwards Compatibility Promise label Sep 4, 2026
chr-hertel added a commit that referenced this pull request Sep 4, 2026
Follow-up on the review of #1566:

* Document the BC break: `TokenUsageInterface::getModel()` is a new interface
  method, and `CompletionsConversionTrait::convertStreamUsage()` gained an
  optional `$model` argument -- both get an `UPGRADE.md` entry, and the platform
  CHANGELOG entry is marked `[BC BREAK]`.
* Report the model from the embeddings extractors (OpenAI, Generic, Mistral,
  Scaleway, Docker Model Runner) and from MiniMax, which all name it next to the
  usage. This is the case the reported issue is about: pricing a run that mixes
  a chat model with an embeddings one.
* Report it on the streamed paths too -- Anthropic (carried from `message_start`
  to the `message_delta` usage), Vertex AI, Ollama and the generic completions
  trait -- where the usage previously aggregated to a null model.
* Record and replay it in `Test\Recording\ResultSerializer`, which dropped the
  field silently, against its own promise never to lose a recorded value; a
  cassette written before the field existed still replays.
* Cover the model in the extractor tests of every touched bridge, in the
  streaming converter tests, and in the serializer round trip.
* Document token usage and per-call pricing in the Platform component docs.

Cohere, the Vertex AI embeddings endpoint and the Claude Code / Codex CLI
bridges still report no model: their payloads do not name one.
@chr-hertel
chr-hertel force-pushed the copilot/add-token-usage-model-info branch from b41c2a6 to 179b306 Compare September 4, 2026 23:34
@chr-hertel
chr-hertel merged commit dd83749 into main Sep 4, 2026
36 checks passed
@chr-hertel
chr-hertel deleted the copilot/add-token-usage-model-info branch September 4, 2026 23:48
@RVXD

RVXD commented Sep 5, 2026

Copy link
Copy Markdown

Thanks for all the work on this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BC Break Breaking the Backwards Compatibility Promise Feature New feature Status: Reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Platform] Token usage - information about used model

5 participants