BYOK custom models: incorrect tokenizer estimates can undercount context and break compaction

未关闭
#5,618 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
25/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
领域
ai, backend

调研方向

The report identifies Copilot CLI 1.0.118-2's native Rust runtime and provides a runnable SDK reproduction, but names no source files or tests. Start by locating the runtime's context token accounting and compaction request path, then run the supplied reproduction and compare its counts with the Inkling tokenizer. Done means estimates and request admission account for the custom tokenizer and compaction requests recover from context-limit errors.

由索引模型根据 Issue 内容生成。

描述

area:context-memory area:models
Problem

Copilot's context estimate can substantially undercount input for an OpenAI-compatible BYOK model with a different tokenizer. Requests, including compaction requests, can exceed the provider's context limit while the displayed context still has free space.

Reproduced with Copilot CLI 1.0.118-2, native Rust runtime, Linux x64. The example is Inkling 2 Mini, served through an OpenAI-compatible chat-completions provider. The bundled SDK is used only as an isolated diagnostic harness. Other custom models require independent testing.

Minimal reproduction

Run the complete script in the expandable section below with the SDK and runtime bundled with CLI 1.0.118-2. It replaces the system prompt with 100 repetitions of a fixed sentence, disables tools and instruction discovery, and returns a synthetic response locally. No API key or model generation is needed.

Measurement for the same repeated text Tokens
Copilot contextInfo.systemTokens, including message overhead 2204
OpenAI o200k_base, text only 2200
Published Inkling tokenizer, text only 2600

The observed counts are consistent with OpenAI tokenization being used for this custom model. This is an inference from runtime measurements, not a source-confirmed tokenizer-dispatch implementation.

Impact

The discrepancy also occurs on complete rendered requests:

Synthetic request Copilot estimate Backend input
No tools 2240 2653
20 tool definitions 4867 6320

Schemas occur once. Independent checks against the published Inkling tokenizer match the backend's token IDs, distinguishing this from omitted/duplicated schemas or a major server tokenizer configuration error.

A separate controlled experiment shows that reported usage helps trigger blocking compaction, but the resulting compaction request can still overflow. It measured 10,179 input tokens against a simulated 10,000-token ceiling, then failed after one attempt with inputShrunk: false. Details and the simulation boundary are below.

Expected behavior

Use provider-appropriate tokenization or conservative/provider-calibrated accounting consistently for context display and request admission. Bound the complete compaction request, including its additional instructions, schemas, and output headroom; shrink or chunk its input on context rejection.

Complete runnable counting reproduction and reference tokenizer check

Save the following as repro.mjs. Use the SDK entry point and standalone runtime executable from the same CLI 1.0.118-2 installation:

COPILOT_SDK_ENTRY=/absolute/path/to/copilot-sdk/index.js \
COPILOT_RUNTIME_PATH=/absolute/path/to/prebuilds/linux-x64/copilot-runtime \
node repro.mjs

If using a separately installed compatible SDK, omit COPILOT_SDK_ENTRY to import @microsoft/copilot-sdk. The tested version is the SDK bundled with CLI 1.0.118-2; compatibility with other SDK versions is not assumed.

import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const { CopilotClient, RuntimeConnection, CopilotRequestHandler } =
  await import(process.env.COPILOT_SDK_ENTRY || '@microsoft/copilot-sdk');
const directory = await mkdtemp(join(tmpdir(), 'copilot-token-repro-'));
const sample = 'The quick brown fox jumps over the lazy dog. function foo(x) { return x * 2; }\n';

// Answer locally: no upstream HTTP call, API key, or model generation.
class FakeProvider extends CopilotRequestHandler {
  async sendRequest(request) {
    const data = await request.json();
    if (!data.stream) {
      return Response.json({
        id: 'local-repro', object: 'chat.completion', created: 1,
        model: data.model,
        choices: [{ index: 0, message: { role: 'assistant', content: 'OK' },
          finish_reason: 'stop' }],
      });
    }
    const chunk = {
      id: 'local-repro', object: 'chat.completion.chunk', created: 1,
      model: data.model,
      choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' },
        finish_reason: null }],
    };
    const end = { ...chunk,
      choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] };
    return new Response(
      `data: ${JSON.stringify(chunk)}\n\ndata: ${JSON.stringify(end)}\n\ndata: [DONE]\n\n`,
      { headers: { 'content-type': 'text/event-stream' } },
    );
  }
}

const client = new CopilotClient({
  mode: 'empty',
  github: { useLoggedInUser: false },
  runtime: RuntimeConnection.forSpawnedStdio({
    baseDirectory: directory,
    ...(process.env.COPILOT_RUNTIME_PATH
      ? { path: process.env.COPILOT_RUNTIME_PATH } : {}),
  }),
  models: { requestHandler: new FakeProvider() },
});
try {
  const session = await client.createSession({
    model: 'Example/inkling-2-mini',
    inference: {
      capi: { enabled: false },
      providers: [{ name: 'Example', type: 'openai',
        wireApi: 'completions', baseUrl: 'http://127.0.0.1:1/v1' }],
      models: [{ provider: 'Example', id: 'inkling-2-mini',
        maxPromptTokens: 10000, maxOutputTokens: 512,
        maxContextWindowTokens: 11000 }],
    },
    tools: { availableTools: [] },
    instructions: { skipCustomInstructions: true },
    systemMessage: { mode: 'replace', content: sample.repeat(100) },
    workingDirectory: directory,
  });
  await session.sendAndWait({ prompt: 'hello' }, 30000);
  const { contextInfo } = await session.rpc.metadata.contextInfo({
    promptTokenLimit: 0, outputTokenLimit: 0,
  });
  console.log('Copilot systemTokens:', contextInfo.systemTokens);
  console.log('Reference Inkling text tokens: 2600 (before message overhead)');
} finally {
  await client.stop();
}

Observed output on the affected runtime:

Copilot systemTokens: 2204
Reference Inkling text tokens: 2600 (before message overhead)

Verify the reference count independently with pip install tokenizers tiktoken, then:

from urllib.request import urlretrieve
from tokenizers import Tokenizer
import tiktoken

revision = "c9d028302cd0f035fdf8e7e91f089a4ce94d2195"
urlretrieve(
    f"https://huggingface.co/thinkingmachines/Inkling-2-Mini/resolve/{revision}/tokenizer.json",
    "inkling-tokenizer.json",
)
reference = Tokenizer.from_file("inkling-tokenizer.json")
openai = tiktoken.get_encoding("o200k_base")
text = "The quick brown fox jumps over the lazy dog. function foo(x) { return x * 2; }\n"
print(len(openai.encode(text)))  # 22
print(len(reference.encode(text, add_special_tokens=False).ids))  # 26

The script uses a fresh temporary Copilot directory and a synthetic provider response. Its token totals come from the runtime's context-info API, not fabricated provider usage metadata.

Additional tokenizer fingerprint and backend validation

A distinguishing fingerprint, repeated 50 times:

fingerprint = "お誕生日おめでとうございます。你好,世界! antidisestablishmentarianism 😀🚀\n"

produces 1,200 tokens with o200k_base, 1,500 with cl100k_base, and 1,204 system tokens in Copilot's Inkling context info, including overhead.

Recounting the same session with model identifiers inkling-2-mini, gpt-4o, and gpt-5 gives identical counts; a Claude identifier gives different counts. The behavior is consistent with the custom model being counted using the OpenAI tokenizer. The private native tokenizer-dispatch implementation has not been source-audited.

The published Inkling tokenizer shares the o200k pre-tokenization regex but has a different vocabulary/merge-rank table. Matching the regex or exposing an OpenAI-compatible API does not make token counts compatible.

Additional public-text checks used llama.cpp b12627-225a5345b, /apply-template, and /tokenize:

Input OpenAI o200k Published Inkling llama.cpp
Model-card prose 16240 21331 21331
TypeScript SDK declarations 12769 15383 15383
Full synthetic tools request 4868 6320 6320

For these checks the published reference and backend token IDs were identical. One separate compaction-text sample differed by two backend tokens, which does not explain the systematic undercount.

Controlled compaction-overflow experiment and diagnostics

The standalone script above reproduces the counting mismatch. The following is supporting evidence from a separate captured-request/response-adapter experiment, not an additional claim about what that script executes.

Reported usage is not entirely ignored. Internal compaction predictions can use provider-reported input plus locally estimated growth, while contextInfo and session.usage_info continue exposing lower local totals.

A controlled harness used the following test limits, chosen to reproduce the problem with small requests:

{
  "maxPromptTokens": 9000,
  "maxOutputTokens": 512,
  "maxContextWindowTokens": 10000
}

A response adapter simulated the 10,000-token backend ceiling. Each captured request was independently rendered/tokenized by the actual Inkling backend before the adapter returned its measured usage or a context-limit error. No model inference was performed.

  1. The first ordinary request has a local count of 7067 and measured input of 8920. The adapter returns success with prompt_tokens: 8920.
  2. Send a small continue message.
  3. The runtime predicts 8952 = 8920 + 32, correctly triggering blocking compaction above its 95% threshold.
  4. The resulting compaction request measures 10179 tokens, exceeding the simulated 10,000-token ceiling.
  5. Compaction retains all 20 schemas, despite tool_choice: "none". Removing only schemas reduces the same request to 6512 tokens.
  6. The runtime records failureReason: "context_limit", attemptCount: 1, and inputShrunk: false, then proceeds with the ordinary request.
  7. That ordinary continuation measures 8959, succeeds, and the context display reports 7100. Compaction has not reduced history.

Relevant compaction diagnostics:

{
  "success": false,
  "failureReason": "context_limit",
  "summarizerProgress": {
    "attemptCount": 1,
    "inputTokensEstimate": 5536,
    "inputShrunk": false
  },
  "attemptMetrics": {
    "triggerThreshold": 0.95,
    "maxOutputTokens": 512,
    "failedRequestCount": 1,
    "failedRequestInputTokensEstimate": 5536
  }
}

The inputTokensEstimate field appears message-oriented; it is not being treated here as a documented complete-request count. The full rendered input was independently measured at 10,179.

This demonstrates a recovery failure before the ordinary conversation itself becomes too large. If ordinary requests subsequently exceed the backend ceiling as well, the failed compaction path cannot recover the session.

Related: microsoft/copilot-sdk#975, microsoft/copilot-sdk#1072, microsoft/copilot-sdk#2355. Originally filed as microsoft/copilot-sdk#2939; this CLI issue supersedes it.

主要语言
Python
星标
11.5k
派生
2k
平均合并
6 小时 34 分钟
30 天内合并 PR
3

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

github/copilot-cli 的其他 Issue

查看 github/copilot-cli 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。