BYOK `provider.maxOutputTokens` never reaches the upstream request body (chat completions & responses)
When using a BYOK (OpenAI-compatible) provider, the max_output_tokens option documented on ProviderConfig is accepted and forwarded to the runtime over JSON-RPC, but the runtime never includes it in the request body sent to the upstream provider — under any configuration path I could find. The same applies to modelCapabilities.limits.maxOutputTokens and to ProviderModelConfig.maxOutputTokens.
The docs for ProviderConfig.maxOutputTokens say:
Overrides the resolved model's default max output tokens. When hit, the model stops generating and returns a truncated response.
As observed, no truncation limit is ever communicated to the provider, so the provider's own default applies instead.
Environment
github-copilot-sdk(Python): 1.0.14- Runtime bundle: CLI 1.0.85 (
~/.cache/github-copilot-sdk/cli/1.0.85), also reproduced with the VS Code-bundled runtime - OS: Linux x64
- Upstream: an OpenAI-compatible
/v1/chat/completionsendpoint (SenseNova), verified to accept and honormax_tokens
Repro
import asyncio
from copilot import CopilotClient
async def main():
client = CopilotClient()
session = await client.create_session(
model="deepseek-flash",
provider={
"type": "openai",
"base_url": "http://127.0.0.1:39221/v1", # local recording proxy
"api_key": "sk-...",
"max_output_tokens": 2345,
},
available_tools=[],
)
await session.send("hi")
await session.disconnect()
await client.stop()
asyncio.run(main())
The proxy sits between the SDK and the real provider and records request bodies verbatim (no TLS issues, plain HTTP hop).
Evidence
1. The Python SDK does forward the option. Tracing the session.create JSON-RPC request shows:
{
"method": "session.create",
"params": {
"model": "deepseek-flash",
"provider": {
"type": "openai",
"baseUrl": "http://127.0.0.1:39221/v1",
"apiKey": "sk-...",
"maxOutputTokens": 2345
}
}
}
2. The upstream request body does not contain it. Captured POST /v1/chat/completions (the runtime uses an embedded OpenAI JS client — User-Agent: OpenAI/JS 5.20.1):
{
"model": "deepseek-flash",
"messages": [...],
"reasoning_effort": "high",
"temperature": 1
}
No max_tokens, max_completion_tokens, or max_output_tokens — the field is silently dropped by the runtime.
Variants tested
| Configuration path | wire API | max_tokens in upstream body |
|---|---|---|
provider["max_output_tokens"] |
completions | no |
provider["max_output_tokens"] + model_id="gpt-5.4" + wire_model |
completions | no |
model_capabilities=ModelCapabilitiesOverride(limits=ModelLimitsOverride(max_output_tokens=...)) |
completions | no |
named providers: providers=[{...}] + models=[{... max_output_tokens: ...}] |
completions | no |
provider["max_output_tokens"] |
responses | no |
For the responses wire API the body carries model/instructions/input/tools/reasoning/store/include — still no max_output_tokens, even though that is the exact parameter name the OpenAI Responses API uses.
Expected behavior
At minimum, one of:
provider.maxOutputTokens(andmodels[].maxOutputTokens) is translated into the provider-appropriate request field (max_completion_tokens/max_tokensfor completions,max_output_tokensfor responses); or- The docs clarify that these are runtime-internal limits only (never sent to the provider), and an explicit opt-in is added for putting them on the wire.
Workaround
Run a local OpenAI-compatible proxy between the SDK and the provider that injects the missing field into the request body (e.g. inject max_tokens: 4096 when absent). Verified working with SenseNova.
The captured request makes this look like a wire-contract mapping gap rather than a BYOK configuration problem. I would keep the SDK's model-limit semantics separate from the provider-specific field name and map them at the final transport boundary.
A focused acceptance matrix could cover:
- Chat Completions: map the internal limit to the provider-appropriate field (max_completion_tokens or max_tokens) and preserve an explicitly configured zero/omitted value according to the SDK contract.
- Responses: map to max_output_tokens; do not reuse the Completions field name.
- Apply the same mapping for inline provider config, named providers, and model capability overrides.
- Add a recording HTTP fixture that asserts the outbound JSON for both APIs, plus a test proving that an unset limit is not silently replaced by a large default.
- Keep the upstream request and response diagnostics secret-safe; report the selected API surface and mapped field, not API keys or full prompts.
For an optional external check of the ordinary OpenAI-compatible Chat Completions mapping, I operate AI Router at https://api.ai-router.dev/v1. It should be used only with an account-visible model and only for the Chat Completions case here; I am not claiming Responses API support or any particular max-token behavior.
Disclosure: I represent AI Router. This is a provider-neutral compatibility suggestion, not a request for a provider-specific integration or default.
Retest 2026-09-29, SDK 1.0.15 + CLI 1.0.89: still not fixed. All variants still produce upstream bodies without max_tokens / max_completion_tokens / max_output_tokens. The completions body is unchanged (messages/model/reasoning_effort/temperature); the responses body now includes prompt_cache_key but still no token limit. RPC trace confirms SDK 1.0.15 still forwards all the options on session.create, so the runtime is still the component dropping them.
Retest 2026-10-01, SDK 1.0.16 + CLI 1.0.90: still not fixed. Identical results across all variants — no token-limit field on the wire anywhere; RPC trace again shows the SDK forwarding provider.maxOutputTokens / models[].maxOutputTokens / modelCapabilities.limits.maxOutputTokens on session.create. (The summary field on the responses wire API still breaks non-OpenAI upstreams.)
Thanks for the detailed captures and retests. The runtime now forwards BYOK provider output caps such as maxOutputTokens into the upstream request body for Chat Completions providers, while explicit session and per-call overrides still take precedence; this is fixed in Copilot CLI 1.0.95 and available in Copilot SDK v1.0.19 and later. Your last retests were on CLI 1.0.90, before this landed, so please retest on the latest version (SDK v1.0.26 with CLI 1.0.103), covering the Responses API path and the models[].maxOutputTokens / modelCapabilities.limits.maxOutputTokens variants as well. If any of them still omit the limit, please reply here with the captured request bodies.
Triaged as part of a Copilot SDK backlog review, with help from GitHub Copilot.
I tested the actual upstream request bodies on the current published runtimes. The provider and named-model paths work now, but the capability-only variant still omits the output cap, so I am leaving this open rather than closing the entire report on the provider fix.
Checked on macOS 26.7.2 / arm64, Node 26.0.0, using the published packages @github/[email protected] (bundled runtime 1.0.112) and @microsoft/[email protected] (bundled runtime 1.0.113). These are verified versions, not a claim about the earliest fixed version.
With the requested value 2345:
| Configuration source | Chat Completions | Responses |
|---|---|---|
| v1 provider.maxOutputTokens | max_tokens: 2345 | max_output_tokens: 2345 |
| v1 models[].maxOutputTokens | max_tokens: 2345 | max_output_tokens: 2345 |
| v1 modelCapabilities.limits.max_output_tokens only | no output-cap field | no output-cap field |
| v2 inference.models[].maxOutputTokens | max_tokens: 2345 | max_output_tokens: 2345 |
| v2 inference.capabilities.limits.max_output_tokens only | no output-cap field | no output-cap field |
The singular provider form was removed in v2, so it was not treated as a v2 API. The capability rows use the current schema's snake_case limit key, not the old camelCase spelling.
The model endpoint below is a loopback HTTP fixture; the SDK and bundled native runtime are real. No external model credentials are needed. This checks runtime behavior/request construction, not a live external model service.
All ten final test cases completed with valid fixture replies; the assertion boundary is the captured HTTP request, not a presumed request inferred from source. For callers needing an immediate workaround, the explicit provider (v1) or named-model output cap is demonstrated above.
Runnable reproduction / diagnostic (repro-2748.mjs)
Put the files below together in an otherwise empty directory. Install the exact packages and run:
npm install --save-exact @github/[email protected] @microsoft/[email protected]
node repro-2748.mjs
node repro-2748.mjs --v2
repro-2748.mjs:
import { fixture, isV2 } from "./repro-support.mjs";
const f = await fixture(2748);
const results = [];
try {
for (const wireApi of ["completions", "responses"]) {
for (const source of ["provider", "capabilities", "named-model"]) {
if (isV2 && source === "provider") continue;
const config = f.options({
model: "gpt-4.1", wireApi,
...(!isV2 && source === "provider" ? { provider: { maxOutputTokens: 2345 } } : {}),
...(source === "capabilities" ? { capabilities: { limits: { max_output_tokens: 2345 } } } : {}),
...(isV2 && source === "named-model" ? { modelConfig: { maxOutputTokens: 2345 } } : {}),
});
if (!isV2 && source === "named-model") {
delete config.provider;
config.model = "fixture/test";
config.providers = [{ name: "fixture", type: "openai", baseUrl: f.baseUrl, apiKey: "local-fixture", wireApi }];
config.models = [{ id: "test", provider: "fixture", modelId: "gpt-4.1", wireModel: "gpt-4.1", maxOutputTokens: 2345 }];
}
const session = await f.client.createSession(config);
const before = f.requests.length;
let sendError;
try { await session.sendAndWait({ prompt: "Reply briefly." }, 15000); }
catch (error) { sendError = error.message; }
const captured = f.requests.slice(before).find((r) => r.path.includes(wireApi === "responses" ? "/responses" : "/chat/completions"));
if (!captured) throw new Error(`No ${wireApi} request captured: ${sendError}`);
results.push({ wireApi, source, fields: Object.fromEntries(
["max_tokens", "max_completion_tokens", "max_output_tokens"].filter((key) => key in captured.body).map((key) => [key, captured.body[key]])),
...(sendError ? { responseFixtureError: sendError } : {}) });
await session.disconnect();
}
}
await f.finish(results);
} catch (error) { await f.finish(results, error); }
The shared fixture below supplies the isolated spawned runtime and loopback endpoint. Its Responses/Completions replies only drive the runtime through the operation; they are not claims about live provider behavior.
repro-support.mjs:
import { createServer } from "node:http";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as v1 from "@github/copilot-sdk";
import * as v2 from "@microsoft/copilot-sdk";
export const isV2 = process.argv.includes("--v2");
export const sdk = isV2 ? v2 : v1;
export const version = isV2 ? "2.0.0" : "1.0.34";
export const root = fileURLToPath(new URL(".", import.meta.url)).replace(/\/$/, "");
export async function fixture(issue, respond) {
const directory = await mkdtemp(`${root}/repro-${issue}-v${isV2 ? 2 : 1}-`);
await mkdir(`${directory}/tmp`);
const requests = [];
const server = createServer(async (req, res) => {
try {
let raw = "";
for await (const chunk of req) raw += chunk;
const body = raw ? JSON.parse(raw) : {};
requests.push({ path: req.url, body });
if (respond) return await respond(req, res, body, requests);
if (req.url.includes("/responses")) responses(res, body);
else completion(res, body);
} catch (error) {
res.writeHead(500, { "content-type": "application/json" });
res.end(JSON.stringify({ error: { message: error.message } }));
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
const env = { PATH: process.env.PATH, HOME: directory, TMPDIR: `${directory}/tmp` };
const client = new sdk.CopilotClient(isV2 ? {
runtime: sdk.RuntimeConnection.forSpawnedStdio({ baseDirectory: directory, env, workingDirectory: directory }),
mode: "empty", github: { useLoggedInUser: false },
} : {
connection: sdk.RuntimeConnection.forStdio(), mode: "empty",
baseDirectory: directory, workingDirectory: directory, env, useLoggedInUser: false,
});
const record = { issue, sdk: version, platform: process.platform, arch: process.arch, directory };
await client.start();
record.runtime = await client.getStatus();
function options({ model = "gpt-4.1", wireApi = "completions", provider = {}, modelConfig = {}, capabilities, ...extra } = {}) {
if (!isV2) return {
model, provider: { type: "openai", baseUrl, apiKey: "local-fixture", wireApi, ...provider },
availableTools: [], onPermissionRequest: sdk.approveAll,
infiniteSessions: { enabled: false }, enableSessionStore: false,
...(capabilities ? { modelCapabilities: capabilities } : {}), ...extra,
};
const { modelId = model, wireModel = model, ...connection } = provider;
return {
model: "fixture/test",
inference: {
providers: [{ name: "fixture", type: "openai", baseUrl, apiKey: "local-fixture", wireApi, ...connection }],
models: [{ id: "test", provider: "fixture", modelId, wireModel, ...modelConfig }],
...(capabilities ? { capabilities } : {}),
},
github: { capi: { enabled: false } },
tools: { availableTools: [] }, permissions: { onRequest: sdk.approveAll },
state: { infiniteSessions: { enabled: false }, enableCrossSessionStore: false }, ...extra,
};
}
async function finish(result, error) {
record.result = result;
if (error) record.error = error.stack;
const errors = await client.stop();
record.teardownErrors = errors.map(String);
server.closeAllConnections();
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
await writeFile(`${directory}/requests.json`, `${JSON.stringify(requests, null, 2)}\n`);
await writeFile(`${directory}/result.json`, `${JSON.stringify(record, null, 2)}\n`);
console.log(JSON.stringify(record));
if (error || errors.length) process.exitCode = 1;
}
return { client, directory, baseUrl, requests, options, finish };
}
export function completion(res, body, { content = "fixture-complete", toolCalls } = {}) {
const message = { role: "assistant", content: toolCalls ? null : content, ...(toolCalls ? { tool_calls: toolCalls } : {}) };
if (!body.stream) {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion", created: 1, model: body.model,
choices: [{ index: 0, message, finish_reason: toolCalls ? "tool_calls" : "stop" }],
usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 } }));
return;
}
res.writeHead(200, { "content-type": "text/event-stream" });
for (const [delta, finish_reason] of [[message, null], [{}, toolCalls ? "tool_calls" : "stop"]]) {
res.write(`data: ${JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 1, model: body.model,
choices: [{ index: 0, delta: { ...delta, ...(toolCalls ? { tool_calls: toolCalls.map((call, index) => ({ index, ...call })) } : {}) }, finish_reason }] })}\n\n`);
}
res.end("data: [DONE]\n\n");
}
export function responses(res, body) {
const content = { type: "output_text", text: "fixture-complete", annotations: [] };
const item = { id: "msg_fixture", type: "message", status: "completed", role: "assistant", content: [content] };
const response = { id: "resp_fixture", object: "response", created_at: 1, status: "completed",
model: body.model, output: [item], usage: { input_tokens: 10, output_tokens: 4, total_tokens: 14 } };
if (!body.stream) {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(response));
return;
}
res.writeHead(200, { "content-type": "text/event-stream" });
const events = [
{ type: "response.created", response: { ...response, status: "in_progress", output: [] } },
{ type: "response.output_item.added", output_index: 0, item: { ...item, status: "in_progress", content: [] } },
{ type: "response.content_part.added", item_id: item.id, output_index: 0, content_index: 0, part: { ...content, text: "" } },
{ type: "response.output_text.delta", item_id: item.id, output_index: 0, content_index: 0, delta: content.text },
{ type: "response.output_text.done", item_id: item.id, output_index: 0, content_index: 0, text: content.text },
{ type: "response.content_part.done", item_id: item.id, output_index: 0, content_index: 0, part: content },
{ type: "response.output_item.done", output_index: 0, item },
{ type: "response.completed", response },
];
events.forEach((event, sequence_number) => res.write(`event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`));
res.end();
}