Skip to content

Fix #14: report Anthropic thinking token usage - #44

Merged
jeffpaul merged 2 commits into
WordPress:trunkfrom
superdav42:fix/14-anthropic-thought-tokens
Oct 1, 2026
Merged

jeffpaul merged 2 commits into
WordPress:trunkfrom
superdav42:fix/14-anthropic-thought-tokens

Conversation

@superdav42

@superdav42 superdav42 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Map Anthropic usage.output_tokens_details.thinking_tokens to TokenUsage::$thoughtTokens.
  • Keep output_tokens as the completion total because Anthropic defines thinking tokens as a billed subset of output tokens.
  • Accumulate the thinking-token breakdown across pause_turn continuation legs.
  • Leave thought-token usage null when an older response omits the breakdown.

Anthropic's current documentation identifies usage.output_tokens_details.thinking_tokens as the authoritative number of billed internal-reasoning tokens. The Messages API exposes the breakdown without a beta header:

This matches the existing Google and OpenAI provider convention: completion tokens include thinking/reasoning, while thoughtTokens reports that subset separately.

Files Changed

  • src/Models/AnthropicTextGenerationModel.php

Runtime Testing

  • Risk level: Critical
  • Verification: runtime-verified — PHPUnit passes with 4 tests and 11 assertions against the pending PHP AI Client 1.3.1 test baseline, covering direct usage parsing, omitted breakdowns, and accumulation across paused turns.
  • PHP syntax and PHPCS pass.
  • PHPStan passes with the pending PHP AI Client 1.3.1 baseline in Fix #24: test PHP AI Client 1.3.1 compatibility #34; current trunk retains its unrelated pre-existing metadata warning.

Resolves #14


aidevops.sh v3.32.317 plugin for OpenCode v1.18.30 with gpt-5.6-sol spent 30m and 251,204 tokens on this with the user in an interactive session.

@superdav42 superdav42 added the origin:interactive Created by interactive user session label Sep 9, 2026
@superdav42

Copy link
Copy Markdown
Member Author

Completion Summary

  • What: Map Anthropic usage.output_tokens_details.thinking_tokens to TokenUsage thoughtTokens and preserve the breakdown across pause_turn continuations.
  • Issue: Add support for thought tokens count in results #14
  • Files changed: .distignore, .github/workflows/deploy-to-wporg.yml, .wordpress-org/blueprints/blueprint.json, composer.json, composer.lock, plugin.php, readme.txt, src/Metadata/AnthropicModelMetadataDirectory.php, src/Models/AnthropicTextGenerationModel.php
  • Testing: Runtime-verified with PHPUnit: 4 tests and 11 assertions pass, including direct, absent, and multi-leg thinking-token usage. PHP syntax and PHPCS pass; PHPStan passes with the pending PHP AI Client 1.3.1 baseline.
  • Key decisions: Use Anthropic's authoritative thinking_tokens field as a subset of output_tokens, matching OpenAI and Google; leave thoughtTokens null when the API omits the breakdown.

aidevops.sh v3.32.317 plugin for OpenCode v1.18.30 with gpt-5.6-sol spent 30m and 251,204 tokens on this with the user in an interactive session.

@superdav42 superdav42 added the status:in-review Non-draft PR ready for review/merge label Sep 9, 2026
@superdav42
superdav42 marked this pull request as ready for review September 9, 2026 18:11
@superdav42
superdav42 requested a review from a team September 9, 2026 18:11
@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: superdav42 <superdav42@git.wordpress.org>
Co-authored-by: jeffpaul <jeffpaul@git.wordpress.org>
Co-authored-by: dkotter <dkotter@git.wordpress.org>
Co-authored-by: Takshil-Kunadia <takshil@git.wordpress.org>
Co-authored-by: felixarntz <flixos90@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The change is localized to usage parsing/accumulation and aligns with the PR’s documented intent without introducing obvious behavioral regressions.

Pull request overview

This PR updates the Anthropic text-generation model to surface Anthropic “thinking tokens” as the SDK’s TokenUsage::$thoughtTokens, while keeping output_tokens as the overall completion/output total and correctly accumulating usage across pause_turn continuation legs.

Changes:

  • Parse usage.output_tokens_details.thinking_tokens from Anthropic responses and map it to TokenUsage::$thoughtTokens.
  • Accumulate thinking_tokens across pause_turn continuation legs (similar to existing accumulation for input/output/cache token counts).
  • Keep thoughtTokens as null when the Anthropic response omits the breakdown.
File summaries
File Description
src/Models/AnthropicTextGenerationModel.php Accumulates and maps Anthropic thinking_tokens into TokenUsage as thoughtTokens, including across paused-turn continuations.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@jeffpaul jeffpaul added this to the 1.0.5 milestone Oct 1, 2026
@jeffpaul
jeffpaul merged commit af743ff into WordPress:trunk Oct 1, 2026
13 checks passed
saarnilauri pushed a commit that referenced this pull request Nov 16, 2026
## What?
Fixes #41

Keeps Anthropic's `usage.server_tool_use` (for example
`web_search_requests`) in the result's additional data, so callers can
tell whether a web search ran and how many were billed.

## Why?
Anthropic bills web search per request, separately from tokens. Today
the count is lost in two places:

1. `parseResponseDataToGenerativeAiResult()` unsets the whole `usage`
key from the additional data. `TokenUsage` keeps the token counts, but
`server_tool_use` is not token data and goes with it.
2. The paused-turn loop in `generateTextResult()` rebuilds `usage` from
the four token counts only. So even with (1) fixed, a paused web-search
turn, which is the common case for search, would still lose the count.

## How?
- The paused-turn loop sums every integer counter in
`usage.server_tool_use` across legs, using the same pattern as the token
accumulation. The key is only added when the API reported it.
- The parser copies `usage.server_tool_use` into the additional data as
`server_tool_use`, next to `stop_reason`.
- `UsageData` gains `server_tool_use?: array<string, int>`.

The `server_tool_use` / `web_search_tool_result` content blocks are
still skipped, as before. The counter is enough for pricing and
reporting, and a provider-agnostic field on `GenerativeAiResult` would
be a php-ai-client decision, as the issue notes.

## Testing Instructions
Adds `tests/Models/AnthropicTextGenerationModelTest.php`, which drives
`generateTextResult()` through a stub `HttpTransporterInterface`:

- one response with `web_search_requests: 1` reports
`['web_search_requests' => 1]`
- a `pause_turn` leg followed by an `end_turn` leg reports `2`, with
token usage still summed
- a response without `server_tool_use` adds no key

The first two fail on `trunk` and pass with this change. PHPUnit and
PHPStan pass locally (PHP 8.4). PHPCS reports no new violations, only
the ones already on `trunk` (unused `AiClient` import and the container
block indentation, which #44 also fixes).

To check against the API: run a prompt with `usingWebSearch()` and read
`$result->getAdditionalData()['server_tool_use']`.

## Changelog Entry
> Fixed - Report server tool usage, such as web search request counts,
in the result's additional data.

<details>
<summary>Use of AI Tools</summary>

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Code and tests.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: muneeb-ashraf <muneebashraf@git.wordpress.org>
Co-authored-by: saarnilauri <laurisaarni@git.wordpress.org>
Co-authored-by: webandseo <webandseofr@git.wordpress.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

origin:interactive Created by interactive user session status:in-review Non-draft PR ready for review/merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for thought tokens count in results

4 participants