Skip to content

AI Request Logs: Warn when monthly token usage nears a limit - #1419

Open
HILAYTRIVEDI wants to merge 7 commits into
WordPress:developfrom
HILAYTRIVEDI:feature/348-monthly-token-limit
Open

HILAYTRIVEDI wants to merge 7 commits into
WordPress:developfrom
HILAYTRIVEDI:feature/348-monthly-token-limit

Conversation

@HILAYTRIVEDI

@HILAYTRIVEDI HILAYTRIVEDI commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What?

See #348

Adds a monthly token limit with an alert threshold to the AI Request Logging experiment. When usage for the current month reaches the threshold or the limit, administrators get an admin notice and an email, and Tools → AI Request Logs shows a usage meter. Requests are not blocked by default; a filter can opt in to blocking them once the limit is reached.

Why?

In #348 we agreed on a phased approach: v1 covers usage visibility (#1418), and a monthly limit warning was the planned fast follow. Site owners currently have no way to find out that AI usage is climbing until a provider bill arrives. This adds that early warning without changing how requests behave by default. Sites that want a hard stop can opt in to blocking with a filter. Per-plugin limits are left for a follow-up.

How?

  • Settings: the AI Request Logging experiment gets two fields on Settings → AI: Monthly token limit (default 0, off) and Alert threshold (%) (default 80, range 1–100). Both are registered with sanitizers and preloaded with the feature toggles.
  • Usage_Limit_Monitor (new):
    • Sums tokens_total from the start of the current calendar month in the site's time zone, using the new AI_Request_Log_Repository::get_tokens_since().
    • Caches the total for five minutes and adds each new request's tokens on wpai_request_logged, so logging a request doesn't trigger a full recount.
    • Reports a state of ok, warning (at or above the threshold) or exceeded (at or above the limit).
    • Shows administrators a warning notice at the threshold and an error notice at the limit.
    • Emails the admin address once per state per month. If usage goes straight past the limit, only the limit email is sent.
    • Does nothing when the limit is 0.
  • Logs screen: a new UsageLimitCard shows tokens used, the threshold marker, the state and the reset date, with a link to change the limit.
  • Opt-in blocking: the wpai_usage_limit_block_requests filter (default false) is checked only once usage reaches the limit. When it returns true, the monitor hooks core's wp_ai_client_prevent_prompt, so generate_* calls return a prompt_prevented error and is_supported* checks return false until next month. The notice, email and usage card then say requests are paused until the reset date. It's a soft cap: usage is cached for up to five minutes and the request that crosses the limit still completes.
  • Filters: wpai_monthly_token_limit, wpai_usage_limit_block_requests, wpai_usage_limit_send_email and wpai_usage_limit_email_recipients.
  • Docs updated in docs/experiments/ai-request-logging.md.

This branch is based on develop and doesn't depend on #1418.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Help with implementation, tests and the PR description; all changes were reviewed, tested and edited by me.

Testing Instructions

  1. Enable AI Request Logging under Settings → AI.
  2. In the experiment's settings, set Monthly token limit to a small number (e.g. 10000) and leave Alert threshold at 80.
  3. Make AI requests until this month's usage passes 80% of the limit. To seed usage without a provider, run wp eval with a few \WordPress\AI\Logging\Logging_Integration::get_log_manager()->log( [...] ) calls that include tokens_input.
  4. Check that:
    • wp-admin shows a warning notice ("…used 90% of the monthly token limit…") linking to the logs.
    • Tools → AI Request Logs shows a Monthly token limit card with an "Approaching limit" state.
    • One email was sent to the admin address (check with a mail catcher, or wpai_usage_limit_alerts in wp_options).
  5. Go past the limit. The notice becomes an error, the card shows "Limit reached", and a second email is sent once. Further requests send no more emails this month.
  6. Add add_filter( 'wpai_usage_limit_block_requests', '__return_true' ); (e.g. in an mu-plugin). The notice and card now say AI requests are paused until the reset date, and AI features fail with prompt_prevented. Remove the filter and requests work again.
  7. Set the limit back to 0. The notice and the card disappear.

Automated tests:

  • npm run test:php -- --filter 'Usage_Limit_Monitor|AI_Request_Log|AI_Request_Logging'

Screenshots or screencast

Before After
No usage limit Screenshot 2026-11-20 at 4 06 02 PM Screenshot 2026-11-20 at 4 06 57 PM

Changelog Entry

Added - AI Request Logging: optional monthly token limit with admin notices, email alerts, a usage meter on the AI Request Logs screen, and a filter to block requests once the limit is reached.

Open WordPress Playground Preview

Add a monthly token limit and an alert threshold to the AI Request
Logging experiment. When usage for the current calendar month reaches
the threshold or the limit, administrators see an admin notice and get
one email per state per month, and the logs screen shows a usage meter.
Requests are never blocked.

- Usage_Limit_Monitor sums tokens since the start of the month in the
  site's time zone, caches the total and tops it up as requests are
  logged.
- Filters: wpai_monthly_token_limit, wpai_usage_limit_send_email and
  wpai_usage_limit_email_recipients.

See WordPress#348.
@HILAYTRIVEDI
HILAYTRIVEDI requested a review from a team November 20, 2026 09:19
@github-actions

github-actions Bot commented Nov 20, 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.

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: HILAYTRIVEDI <hilayt24@git.wordpress.org>
Co-authored-by: jeffpaul <jeffpaul@git.wordpress.org>

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


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

@HILAYTRIVEDI
HILAYTRIVEDI marked this pull request as draft November 20, 2026 09:22
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.19028% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.80%. Comparing base (b2bdae5) to head (d8d5f83).

Files with missing lines Patch % Lines
includes/Logging/AI_Request_Log_Manager.php 0.00% 2 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             develop    #1419      +/-   ##
=============================================
+ Coverage      85.62%   85.80%   +0.17%     
- Complexity      5155     5218      +63     
=============================================
  Files            194      195       +1     
  Lines          18637    18881     +244     
=============================================
+ Hits           15958    16200     +242     
- Misses          2679     2681       +2     
Flag Coverage Δ
unit 85.80% <99.19%> (+0.17%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@HILAYTRIVEDI
HILAYTRIVEDI marked this pull request as ready for review November 20, 2026 10:37
@dkotter dkotter added this to the 1.7.0 milestone Nov 20, 2026
@jeffpaul

Copy link
Copy Markdown
Member

Requests are never blocked.

Perhaps a filter so that while requests are not blocked at the limit by default, the filter could adjust things so that token usage is halted at the limit (again, not the default setting)?

Adds the wpai_usage_limit_block_requests filter (default false). When it
returns true and this month's usage has reached the limit, the monitor
hooks core's wp_ai_client_prevent_prompt so prompts are prevented until
usage resets. The admin notice, email and usage card say requests are
paused when blocking is on.
@HILAYTRIVEDI

Copy link
Copy Markdown
Contributor Author

Requests are never blocked.

Perhaps a filter so that while requests are not blocked at the limit by default, the filter could adjust things so that token usage is halted at the limit (again, not the default setting)?

Good idea, added in the latest commit. There's now a wpai_usage_limit_block_requests filter (default false). When it returns true and this month's usage has reached the limit, the monitor hooks core's wp_ai_client_prevent_prompt, so AI requests get a prompt_prevented error and is_supported* checks return false until the next month. The admin notice, email and logs card then say requests are paused until the reset date. It's a soft cap: usage is cached for up to five minutes and the request that crosses the limit still finishes, so usage can end slightly over the limit

@HILAYTRIVEDI

Copy link
Copy Markdown
Contributor Author

Hi @jeffpaul , The testes are failing because of the memory , can you please check ?

@jeffpaul
jeffpaul requested a review from dkotter December 2, 2026 14:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants