nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Feature] Keep a compact models.dev index instead of the 10 MB database in memory

Open addyCooks opened this issue 1 month ago • 1 comments

Description

To find one model's context limit and price, nanocoder reads a 10.4 MB cache file, parses all 230 providers / 8,874 models, and keeps the whole object graph for the life of the process. For unknown or local model names (Ollama tags), every lookup scans all models again.

Environment

  • OS: Windows 11 (10.0.26300)
  • Node version: 22.22.3
  • Nanocoder version: 1.31.0 (main at 5c2e6935)

Steps to Reproduce

  1. Start nanocoder once so ~/.cache/nanocoder/models.json exists.
  2. In a script run with --expose-gc, import dist/models/index.js, call getModelContextLimit('qwen2.5-coder:7b') repeatedly, and print process.memoryUsage().heapUsed after gc().

Evidence

  • The cache file is written pretty-printed: 10,437,878 bytes (5,665,828 minified) (source/models/models-cache.ts:74, JSON.stringify(cached, null, 2)).
  • First lookup 189 ms; 10.1 MB retained heap. Per call: 0.2 ms for an exact id such as gpt-4o, but 6-8.6 ms for mock-model, qwen2.5-coder:7b and llama3.1:8b (full scan in findModelByName, source/models/models-dev-client.ts:283). modelsDataMemo (line 193) memoizes the database, not individual results.
  • The lookup is on the startup path (source/ai-sdk-client/ai-sdk-client.ts:100) and again for compaction and usage reports.
  • With a valid cache nothing is fetched at startup. The TTL is 7 days (source/constants.ts:35).

Proposed Change

  • When fetching, write a compact index (minified; per model only id, name, limit, cost, tool_call) or a pre-built map keyed by lowercase id.
  • Memoize findModelByName / findModelById results per name and drop the raw database after the index is built.
  • Optionally load the index only when the provider's own /models response lacks a context size.

Expected Behavior

  • Retained heap after the first lookup is under 2 MB.
  • Per-call latency for unknown names is under 0.5 ms.
  • Context limits and pricing for a sample of 20 models are identical before and after.

Additional Context

  • Effort: M. Start with source/models/models-dev-client.ts, models-cache.ts, models-types.ts.
  • Estimated impact: about -9 MB heap and -100 to -150 ms on the first lookup. High confidence (measured); the new file size was not measured.
  • Risk: the cache format change needs a version bump so old cache files are handled. Specs: source/models/*.spec.ts.

addyCooks avatar Oct 15 '26 15:10 addyCooks

Hi, I'd like to take this one. I'll build the compact index with a cache version bump and post before/after heap and latency numbers in the PR.

abdd8433 avatar Oct 15 '26 17:10 abdd8433