nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Feature] Architecture: One-shot model calibration for local inference capabilities

Open akramcodez opened this issue 1 month ago • 5 comments

Description

Introduce a /calibrate command that runs a deterministic benchmark against the active local model to measure its capabilities, then auto-tunes Nanocoder's prompts and tool profiles based on the results.

Use Case

Nanocoder relies on heuristics (like model names) to guess if a model is "smart" or "dumb." This breaks when users load custom GGUFs, fine-tunes, or new open-weights models (e.g., Qwen 2.5). Users end up fighting the UI because the model can't handle complex XML schemas.

Proposed Solution

  1. User runs /calibrate.
  2. Nanocoder sends 3 hidden prompts testing: JSON schema adherence, multi-step instruction following, and exact-string matching.
  3. Based on the pass/fail of these tests, Nanocoder saves a local profile for that specific endpoint.
  4. The system automatically degrades to "simple" tool formats (or disables complex MCPs) if the model scores poorly, ensuring a stable experience.

Alternatives Considered

  • Hardcoding a massive list of known model capabilities (impossible to maintain).
  • Forcing users to manually configure "tool complexity" sliders (bad UX).

Additional Context

  • [x] I have searched existing issues to ensure this is not a duplicate
  • [x] This feature aligns with the project's goals (local-first AI assistance)

akramcodez avatar Oct 05 '26 09:10 akramcodez

Taking this one! will propose my plan soon!

rishu685 avatar Oct 07 '26 10:10 rishu685

@rishu685 thanks for your interest in this. A quick note on process so this goes smoothly next time: please wait to be assigned to an issue before opening a PR for it.

For this issue:

  1. This one is labelled proposal, so please don't start (or continue) the implementation until a maintainer has agreed the design here.
  2. Post a short plan in this thread. It should cover which settings calibration changes and how each is applied, how failures are handled (a down or misconfigured endpoint must not save a profile), how profiles are keyed and looked up, and where results are stored.
  3. Ask to be assigned. A maintainer will reply and assign it once the approach is agreed.
  4. Only then open or update a PR.

This keeps contributors from spending time on work that may need a different direction. Thanks for understanding!

addyCooks avatar Oct 09 '26 11:10 addyCooks

Hi @addyCooks, thanks for the guidance and apologies for jumping straight to the PR I should have created an implementation plan

Here is the proposed design plan addressing each of the points:


1. Which Settings Calibration Changes & How Applied

  • Tool Profile (toolProfile):
    • When tuneConfig.toolProfile === 'auto' (the default), resolveToolProfile and inferToolProfile check if a saved calibration profile exists for the active model.
    • If a calibrated profile exists, it resolves directly to the recommended tier ('full', 'minimal', or 'nano') instead of relying on parameter-count name heuristics (e.g., matching :7b).
    • This directly controls ToolManager.getAvailableToolNames(), dictating tool surface filtering, single-tool mode enforcement, and ultra-slim prompt budgeting.
  • Recommended Tool Formatting:
    • Scores the model's adherence to XML vs. JSON schemas and records the recommended mode (native, xml, or json), displayed to the user via /calibrate and /calibrate view.

2. Failure Handling (Down or Misconfigured Endpoints)

  • Zero-Save on Failure: If any benchmark test encounters a network timeout, connection refused, 4xx/5xx HTTP error, or invalid API credentials:
    • The benchmark aborts immediately.
    • No profile is saved or overwritten (preventing a down endpoint from being misclassified as a failing/tier-3 model).
    • A clear error message is returned to the user (e.g. Calibration aborted: endpoint unreachable. Existing configuration preserved.).
  • Existing configuration and any previously valid calibration profiles remain intact.

3. Keying and Lookup Strategy

  • Keying: Profiles are keyed by provider:model (case-insensitive and trimmed), e.g. ollama:qwen2.5-coder:7b or openrouter:anthropic/claude-3.5-haiku.
  • Lookup:
    • Primary: Direct lookup by provider:model when both are known at the call site.
    • Fallback: If provider is omitted at a generic call site (such as inferToolProfile(model)), look up by model across existing stored profiles.
    • Heuristic Fallback: If no calibration profile exists, cleanly fall back to the existing parameter-count heuristics (modelParamsBillions).

4. Storage Location

  • Profiles are stored in user preferences (nanocoder-preferences.json under modelCalibrations) via loadPreferences() / savePreferences().
  • This ensures profiles persist across sessions and projects on the user's machine without polluting local project repositories.
  • Users can inspect their active calibration via /calibrate view or revert to heuristic defaults at any time via /calibrate reset.

Can you please review this approach would love to see and will update my PR accordingly as mentioned

rishu685 avatar Oct 09 '26 12:10 rishu685

Thanks @rishu685, the plan looks good. A few things to fix before I assign this:

  1. Keying: the code that picks the tool profile only gets the model name, not the provider. So provider:model can't be looked up there, and a model-only fallback is unclear when the same model runs on two providers. Please pass the provider through and drop the fallback.
  2. Failures: if the endpoint is down or the key is wrong, save nothing. If the model just answers badly or rejects a feature, that is a valid low score and should be saved.
  3. Please list the 3 tests and the score needed for each tier (full, minimal, nano).
  4. tune.toolMode already exists. Should calibration only suggest a mode, or set it when the user hasn't? A setting the user chose should always win.
  5. Calibration costs money on paid providers, so please warn before running there.

Please hold #1621 until this is agreed and assigned to you.

addyCooks avatar Oct 10 '26 07:10 addyCooks

Hi @addyCooks!

Thank you for the feedback. Here is the revised implementation plan :


1. Keying and Provider Forwarding (Drop Model-Only Fallback)

  • Strict Keying: Profiles are keyed strictly as provider:model (lowercased and trimmed).
  • Forward Provider: provider is forwarded through all profile resolution call sites:
    • inferToolProfile(model?: string, provider?: string)
    • resolveToolProfile(profile: ToolProfile, model?: string, provider?: string)
    • ToolManager.getAvailableToolNames(..., model, provider)
    • DevelopmentModeIndicator
  • No Ambiguous Fallbacks: The model-only loop fallback has been dropped completely. If provider is not provided or if provider:model is not found in the calibration store, it falls back cleanly to the existing parameter-count heuristics (modelParamsBillions).

2. Failure Handling: Transport/Auth Failures vs. Low Model Scores

  • Transport / Auth / Down Endpoints (Zero-Save):
    • If the client throws a network error, timeout, HTTP 401/403 (bad credentials), or 502/503 (endpoint down), calibration aborts immediately.
    • No profile is created or saved. Existing configurations and stored profiles remain untouched.
    • Returns: Calibration aborted: endpoint unreachable or credentials invalid. Existing configuration preserved.
  • Model Incompetence / Feature Rejection (Valid Low Score):
    • If the endpoint returns HTTP 200, but the model produces invalid JSON, malformed syntax, wrong line counts, or an explicit refusal ("I cannot fulfill this request"), this is treated as a valid test evaluation.
    • The model receives a low/zero benchmark score, resolves to Tier 3 (nano), and the profile is saved.

3. The 3 Benchmark Tests & Tier Thresholds

Each test produces a deterministic score from 0 to 100. Overall score is the mean average:

  1. json_schema (JSON Schema Adherence):
    • Evaluates raw JSON adherence against {"status": "ok", "code": 200, "items": ["alpha", "beta"]}.
    • Score: 100 for exact JSON without codeblock fences; 80 if valid schema but wrapped in markdown fences; 40 if JSON parsed but fields/values mismatch; 0 if invalid JSON.
  2. instruction_following (Multi-Constraint Instruction Following):
    • Evaluates negative/positive constraints (exactly 3 lines, - item_ prefix on each line, uppercase "CALIBRATE" only on line 2, no preamble).
    • Score: 30 base for exact 3-line count, +35 for prefixes on all lines, +35 for keyword placed exclusively on line 2 (max 100).
  3. tool_syntax_matching (Exact XML Tag & Delimiter Matching):
    • Evaluates exact XML tool delimiter reproduction: <tool_call name="read_file"><path>source/app.tsx</path></tool_call>.
    • Score: 100 for exact tag match without surrounding commentary; 75 if valid tags but accompanied by conversational fluff; 50 for partial tags; 0 for complete failure.

Tier Mapping:

  • Tier 1 (Advanced / full): Score $\ge 80$
    • Profile: full (All tools including MCP, multi-tool enabled, standard prompts).
  • Tier 2 (Standard / minimal): Score $50 - 79$
    • Profile: minimal (8 core tools, single-tool mode enforced, slim prompt).
  • Tier 3 (Constrained / nano): Score $< 50$
    • Profile: nano (5 essential tools, diff-block editing, single-tool mode, ultra-slim prompt, AGENTS.md omitted).

4. tune.toolMode Hierarchy (User Choice Always Wins)

  • User Setting Wins: If tune.toolMode has been explicitly chosen by the user (either in preferences or through /tune), calibration never overrides it.
  • Auto Default When Unset: If tune.toolMode is undefined (unset), calibration sets it to the recommended mode (native for Tier 1, xml for Tier 2/3).
  • Status Reporting: /calibrate and /calibrate view indicate the recommended mode, and clearly note if an existing user override was retained.

5. Paid Provider Warning & Guardrails

  • Before dispatching benchmark prompts, /calibrate checks baseURL using isLocalURL().
  • If the provider is a remote / paid API (e.g. OpenRouter, OpenAI, Anthropic, Gemini):
    • Execution stops and prompts the user:

      ⚠️ Provider <name> is a cloud service. Running calibration sends 3 benchmark prompts and consumes API tokens. Re-run with /calibrate --confirm to proceed.

    • Passing --confirm (or -y) bypasses the warning and executes the benchmark.
  • Local endpoints (Ollama, LM Studio, localhost) run immediately without prompting.

I will keep #1621 on hold until assignment is confirmed, and then push the updated implementation matching this exact plan.

rishu685 avatar Oct 10 '26 08:10 rishu685