nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

Measuring interest: API/Persistent-Usage-Monitor

Open cleyesode opened this issue 9 months ago • 8 comments

I have a few iterations for per response context tracking n_tokens via API. Also, for persistent context monitor in chat. I'd like to measure you interest ahead of PR.

How do you feel about this in light of the existing /usage metrics estimation (and compression) system?

For API usage, I don't presume you are open to a complete replacement of existing integrations, or would you prefer parallell development (or perhaps coexistence as a fallback system when API metrics are unavailable)?

For persistent usage monitor in chat, rendering has some issues for scrolling and window resizing - these would be most easily overcome via sidebar - something you are comfortable with?

A perfect compliment to compression, accurate context would open the doors to enhanced user awareness on the near side, and agent self-awareness on the far side. Autonomous looping would be an excellent place to go from there.

It would also be fairly easy to create var for user setting max context (per config server) in env.

Thoughts? Thanks

cleyesode avatar Feb 23 '26 22:02 cleyesode

Thanks for the proposal! There's a strong foundation to build what already exists in the codebase!

What already exists:

  • 4 tokenizer backends (OpenAI/tiktoken, Anthropic, Llama, fallback) in source/tokenization/
  • A 6-category token breakdown (system, user, assistant, tool defs, tool results, total) in source/usage/calculator.ts
  • Session tracking with persistent storage (last 100 sessions, 30-day aggregates) in source/usage/
  • Real-time context % via useContextPercentage hook
  • Auto-compact triggered at configurable thresholds
  • /usage command with progress bars and category breakdowns

The opportunity is:

  1. API-reported token counts - Right now tokens are estimated client-side (4 chars/token heuristic or tiktoken). The Vercel AI SDK already exposes usage fields in streaming responses, so wiring actual API-reported n_tokens into the existing SessionTracker would be the highest-value change. The current estimation system stays as a fallback for providers that don't report usage.

  2. Env var overrides for context limits - Context limits currently resolve via models.dev API -> hardcoded fallback. Adding something like NANOCODER_MAX_CONTEXT would be a quick, useful win for users who want to cap usage below the model's actual limit. Fits cleanly into source/config/. I'm doing this today to close #379 :)

  3. Persistent monitor - You're right that rendering is tricky. Rather than a sidebar (Ink.js doesn't handle that well, and terminal real estate is tight), I'd suggest enhancing the existing DevelopmentModeIndicator in source/components/development-mode-indicator.tsx - it already shows ctx: NN% inline and could be extended to show more detail without the scroll/resize headaches.

Suggestion on approach: Parallel over replacing - layer API-reported numbers on top of the existing estimation system rather than ripping it out. A scoped first PR focused on API token tracking would be a great starting point.

Let me know what you think!

Would welcome your thoughts too @Avtrkrb :)

will-lamerton avatar Feb 25 '26 12:02 will-lamerton

@Avtrkrb very good, thanks for the excellent guidance. I have a good version for inline reporting that clearly indicates when using API vs fallback, so I'll start there.

The issue that needs a proper sorting is allocations for % n_tokens to be attributed dynamically to each of the existing context categories (system prompt, user messages, assistant messages, tool messages, tool definitions). With n_tokens being the lump sum, your existing estimation system could be used to define ratios and assign appropriately.

While not strictly necessary for inline reporting of only n_tokens, this would allow for /usage menu to use API with fallback without any other aesthetic considerations - I'm thinking this may be the cleanest approach to avoid confusion that might arise from displaying both estimated and actual token counts within the same menu.

And awesome on the #379 !

I'll PR sometime this weekend. Thanks

cleyesode avatar Feb 26 '26 00:02 cleyesode

@will-lamerton **Apologies for the misnomer - let me know if any issues with this direction @Avtrkrb !

cleyesode avatar Feb 26 '26 00:02 cleyesode

Hey @cleyesode - just wanted to check in on this issue - what's your thoughts on where it is and whether it's something to action? If not we can close :)

will-lamerton avatar May 18 '26 13:05 will-lamerton

Hi @will-lamerton @cleyesode — is this still up for grabs? The API-token-tracking direction got full sign-off but seems to have stalled. I'd like to take the scoped first PR you agreed on: read the AI SDK's reported usage from the streamed result, surface it inline on DevelopmentModeIndicator with a clear API-vs-estimate marker, and keep the existing estimation as the fallback for providers that don't report usage (e.g. local models, or OpenRouter without usage:{include:true}).

I'll use the final step's usage rather than totalUsage so the context number reflects occupancy and not the cross-step sum, leave per-category allocation out of this PR (as @cleyesode suggested), and treat NANOCODER_MAX_CONTEXT as already handled by #379.

Happy to take it over if @cleyesode has moved on — I'll tag you both on the PR.

JimStenstrom avatar Jun 04 '26 02:06 JimStenstrom

@JimStenstrom - hey! Very happy for you to take this on in. @cleyesode dips in and out so yes a dual tag in the PR would be great :)

will-lamerton avatar Jun 04 '26 06:06 will-lamerton

I reviewed the current main branch against the scoped API-token-tracking proposal in this issue. The requested behavior is already implemented: API-reported usage is captured from the final streamed step, stored with the post-response message count, and used as the context-usage anchor with an estimated-tail fallback when newer messages arrive.

The implementation also has regression coverage for API anchors, missing usage, partial usage, and context invalidation. I’m avoiding a duplicate PR; if there is still a remaining gap, please point to the specific display or attribution behavior that needs follow-up.

RealBhupesh avatar Aug 03 '26 12:08 RealBhupesh

Fixed by #543: the context indicator now uses API-reported usage, with an estimate as fallback.

Closing as part of a backlog tidy-up. Reopen it if anything here is still broken.

will-lamerton avatar Oct 07 '26 10:10 will-lamerton