GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Feature: Dynamic context length detection for OpenAI-compatible providers · Issue #40908 · anomalyco/opencode

Feature: Dynamic context length detection for OpenAI-compatible providers #40908

New issue
Copy link
New issue
Copy link
Open
Open
Feature: Dynamic context length detection for OpenAI-compatible providers#40908
Copy link

Description

@PGCRT
PGCRT
opened on Aug 6, 2026
Issue body actions

Summary

When using a custom OpenAI-compatible provider (via @ai-sdk/openai-compatible), opencode does not dynamically detect the context length of the currently loaded model from the server's /models endpoint. Instead, it requires limit.context to be hardcoded in the config for each model.

Problem

Local model servers (LM Studio, Unsloth Studio, etc.) expose context_length for the loaded model in their /models API response. However, opencode ignores this and requires static configuration. This means:

  1. Users must manually set limit.context for every model
  2. If the user changes the context size on the server, opencode doesn't know
  3. Different models may have different context lengths, requiring constant config updates

Expected Behavior

opencode should query the provider's /models endpoint at runtime and read the context_length field to determine the appropriate context window for the currently loaded model.

Example Server Response

{
  "object": "list",
  "data": [
    {
      "id": "DavidAU/Qwen3.5-9B-...",
      "object": "model",
      "owned_by": "unsloth-studio",
      "context_length": 262144,
      "max_context_length": 208128,
      "native_context_length": 262144,
      "loaded": true
    }
  ]
}

Current Workaround

Users must manually specify limit.context (and limit.output) in opencode.json for each model definition under provider.<name>.models.

Suggested Solution

For OpenAI-compatible providers, fetch the /models endpoint at connection time and use the context_length from the loaded model's metadata as the context window. This could be refreshed periodically or on model switch.

Environment

  • Provider type: @ai-sdk/openai-compatible
  • Local server: Unsloth Studio (also applies to LM Studio, Ollama, etc.)
Reacted by Alldar, Kiwi, Scott Williams, Kevin Abraham, sklryb and Paulo C. B. Sincos
Reacted by Dustin Wenz and Paulo C. B. Sincos

Activity

  1. throny commented on Sep 25, 2026

    @throny
    throny
    on Sep 25, 2026
    More actions

    Adding concrete data from another report of this, since it's still reproducible on the current 2.0.x desktop builds and the exact source of the fallback turns out to be identifiable.

    The 200000/32000 is a schema default, not a missing-value path

    Model.Info carries a default constructor, so limit is populated before provider resolution runs. Every model declared with an empty object gets this, with no warning:

    limit: o({ context: Je, input: Je.pipe(m), output: Je })
      .pipe(withDefaultDefault((providerID, modelID) => ({
        /* ... */
        limit: { context: 200000, output: 32000 }
      })))

    The 200000/32000 pair was already reported in #1735 (closed April 2026) and is still in the code, so this reads as a deliberate default rather than drift.

    Discovery already exists — just not on this path

    context_length / max_output_length / max_model_len are parsed from a models endpoint, but only by four dedicated plugins: LM Studio, Ollama, vLLM, and Modal. A provider declared as @opencode/ai/providers/openai-compatible never gets a discovery pass, so GET /v1/models is never consulted.

    The server in this case does return the field:

    {
      "object": "list",
      "data": [
        { "id": "<model>", "object": "model", "owned_by": "OpenAI", "context_length": 1050000 }
      ]
    }

    That's 5.25x the 200000 that actually gets used. So this is a narrow gap — reusing the existing discovery path for openai-compatible providers — rather than new ground.

    Why a silent 200000 is worse in one direction

    When the real context exceeds the default, the symptom is benign: auto-compaction fires early. Wasted context, not breakage.

    The dangerous direction is the opposite — a model whose real context is below 200000. A 32k-context model on the same gateway resolved to 200000/32000, a 6x over-report, so OpenCode will build a prompt the server then rejects, with no indication the limit is a guess rather than a real value.

    Minimal repro

    {
      "$schema": "https://opencode.ai/config.json",
      "providers": {
        "example": {
          "name": "Example",
          "package": "@opencode/ai/providers/openai-compatible",
          "settings": { "baseURL": "https://example.invalid/v1" },
          "models": { "some-model": {} }
        }
      }
    }

    GET /v1/models reports context_length: 1050000, but GET /api/model resolves that model to {"context":200000,"output":32000}. Adding an explicit limit to the model entry corrects it immediately, which is a working workaround but requires hardcoding every model by hand.

    Secondary ask, if auto-discovery isn't the plan

    Even if discovery stays opt-in, it would help if the fallback were distinguishable — e.g. a warning, or a marker in the /models output when a limit is the schema default rather than a configured or discovered value. Right now there's no way to tell the two apart from outside, which is what makes this easy to miss.


    Environment: opencode desktop 2.0.14 and 2.0.23 — both reproduce, and the placeholder default plus the discovery provider list are unchanged between the two. Linux x86_64.

    Related: #53235 tracks this on its own, and the open PR #54398 ports a fix to V2 that calls out the same Model.Info placeholder behaviour described above.

  2. Tarquinen
    marked [FEATURE]: Fill context limits for OpenAI-compatible providers from their /models advertisement #53235 as a duplicate of this issue on Oct 20, 2026
  3. opencodejr commented on Oct 28, 2026

    @opencodejr
    opencodejrBot
    on Oct 28, 2026
    Contributor
    More actions

    Thanks for the detailed request! In short: for custom OpenAI-compatible providers (like Unsloth Studio), you'd like OpenCode to read context_length from the server's /models endpoint and keep it updated, instead of needing limit.context set by hand for each model.

    In v2, the built-in LM Studio, Ollama and vLLM providers already detect this: they read the models and the loaded model's context length from the server and refresh it regularly. Custom @ai-sdk/openai-compatible providers don't do this yet, so for now limit.context in opencode.json is still the way to set it.

    Related:

    • feat(core): discover context limits for custom OpenAI-compatible providers #59520: open community PR that adds /models limit discovery (context_length, max_input_tokens, max_output_tokens) for custom OpenAI-compatible providers. It is waiting for review.
    • [FEATURE]: Fill context limits for OpenAI-compatible providers from their /models advertisement #53235: the same request, closed as a duplicate of this issue.
    • [FEATURE]: provider: auto-detect context window from provider #52346: the same idea for Ollama; Ollama context detection already exists.

    Maintainers will consider this request.

  4. hamedmirza commented on Nov 21, 2026

    @hamedmirza
    hamedmirza
    on Nov 21, 2026
    More actions

    Reproduced on Desktop 2.3.2 with Unsloth Studio — the missing detection turns a 262,144-token server into a 16,768-token session

    Adding current data for the custom @ai-sdk/openai-compatible case, because the symptom is easy to misread as "Unsloth caps context at 17K" when nothing in Unsloth is involved.

    Environment

    • opencode: Desktop 2.3.2 (bundled opencode-cli 2.3.2-x64), macOS Darwin 24.6.0 (x64)
    • provider: custom @ai-sdk/openai-compatible → Unsloth Studio, self-hosted at http://<lan-host>:8888/v1
    • model: unsloth/Qwen3.8-27B-GGUF (UD-Q2_K_XL)
    • active plugins: none relevant (local factory plugin only)

    What the server reports

    GET /v1/models (loaded model; key fields only):

    {
      "id": "unsloth/Qwen3.8-27B-GGUF",
      "owned_by": "unsloth-studio",
      "loaded": true,
      "context_length": 65536,
      "max_context_length": 262144,
      "native_context_length": 262144,
      "vram_fit_context_length": 262144
    }

    The architecture maximum is 262,144; Studio had that model loaded at 65,536 at the time.

    What opencode did with it

    Config (opencode.jsonc, the only place a custom provider can express this):

    "unsloth/Qwen3.8-27B-GGUF": { "limit": { "context": 32768, "output": 16384 } }

    The session's usable window topped out at 16,768 tokens, displayed as "17K" — on a server holding a 65,536-token window it could raise to 262,144 at will, with vram_fit_context_length: 262144 telling Studio it fits.

    Why 16,768 — the number is the compaction ceiling, not the window

    From packages/core/src/session/compaction.ts (2.3.x):

    const RESERVE_MIN = 16_000
    const RESERVE_SHARE = 0.15
    
    const calculateCeiling = (limit, buffer) => {
      const window = inputWindow(limit)              // min(input, context)
      if (window <= 0) return Number.POSITIVE_INFINITY
      const tokens = typeof buffer === "string" ? round(window * parseFloat(buffer) / 100) : buffer
      if (tokens !== undefined && tokens < window) return window - tokens
      return window - Math.max(Math.floor(window * RESERVE_SHARE),
                               window >= 2 * RESERVE_MIN ? RESERVE_MIN : 0)
    }

    32,768 − max(4,915, 16,000) = 16,768.

    Two consequences worth naming in the issue:

    1. The number a user sees is a threshold, not a capability. Nothing surfaces the difference, so "my model is 262K but opencode says 17K" reads as a provider limit. Cf. tui: model picker no longer shows context limit and model capabilities #63860 (picker no longer shows context limit) and Feature: Show context/output limits in /models command #40792 (show limits in /models).
    2. With no discovery, limit.context is the user's only lever, and it is written by hand in opencode.jsonc — which is exactly what [FEATURE]: Feature Request: Add GUI Options to Edit Custom Providers and Manage Model Lists #33704 asks to fix. When it is wrong in either direction the session is silently mis-sized: too low compacts early forever; too high (cf. Ollama provider overrides user-configured limit.context with the GGUF context_length, breaking compaction for num_ctx-capped variants #63899, where Ollama discovery overrides it) never compacts before the real window fills.

    Reproduced the other direction, to confirm it is discovery and not the config

    Loading the same model at its maximum on the server:

    POST /api/inference/load
    { "model_path": "unsloth/Qwen3.8-27B-GGUF", "max_seq_length": 262144, "cache_type_kv": "q8_0" }
    
    → GET /v1/models: "context_length": 262144
    

    With limit.context: 262144 on the client the same session computes 262,144 − 39,321 = 222,823 usable tokens — a 13× difference from one server-side reload that opencode had no way to notice on its own.

    What would fix it for custom OpenAI-compatible providers

    1. Read context_length (and max_context_length) from the provider's /models on the same refresh cycle the built-in LM Studio / Ollama / vLLM providers already use, and re-read it when a model loads or changes rather than only at startup.
    2. Define precedence explicitly when limit.context is also set — user config should win, or the override should be visible in the UI. Ollama provider overrides user-configured limit.context with the GGUF context_length, breaking compaction for num_ctx-capped variants #63899 shows the current behaviour is surprising for Ollama; a custom provider needs the rule stated, not implied.
    3. Handle the unloaded case: Studio returns "loaded": false and omits context_length for models not resident. Keep the last known or configured value instead of falling back to a default or zero, and refresh once the model loads.
    4. Surface the effective window in the UI, distinguishing the model's window from the compaction ceiling, so a 16,768 ceiling on a 262,144 model is legible as reserve rather than as a cap.

    Flat-out replacing the hardcoded limit.context for local servers is the request in the issue body; the four points above are the same request seen from a self-hosted Unsloth Studio, where the model, the window and the KV-cache dtype all change between loads.

    Workaround, for anyone who lands here first

    • Set limit.context/limit.output per model in opencode.jsonc, matching what the server currently serves (GET /v1/models → context_length), not the architecture maximum.
    • Tune the reserve if the 15%/16k margin is too large for your window: "compaction": { "buffer": "5%" } or a token count (packages/schema/src/config/compaction.ts).
    • Reload the model at the desired context first (q8_0 KV cache is what made 262,144 fit here), then set the client to match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.