Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/api/providers/__tests__/kimi-code.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,59 @@ describe("KimiCodeHandler", () => {
expect(handler.getModel().id).toBe("future-kimi-model")
})

it("does not send max_completion_tokens when includeMaxTokens is unset (#2668 review)", async () => {
// Kimi Code has no "Include max output tokens" checkbox, so the
// OpenAI Compatible default (include when unset) must not apply;
// unset keeps the pre-#2230 behavior of omitting the field.
// NOTE: spy on fetch before constructing the handler — the OpenAI
// SDK resolves `fetch` at client construction time.
const fetchSpy = vi.spyOn(globalThis, "fetch")
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [{ message: { content: "response" }, finish_reason: "stop" }] }), {
status: 200,
}),
)
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "kimi-key" })
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
try {
for await (const _chunk of gen) {
// consume
}
} catch {
// expected - mock is incomplete
}
// A swallowed createMessage error must not masquerade as a passing
// unset assertion: prove a request was actually captured, then
// parse the real body (no "{}" fallback).
expect(fetchSpy).toHaveBeenCalledOnce()
const body = JSON.parse((fetchSpy.mock.calls[0]?.[1] as { body: string }).body)
expect(body.max_completion_tokens).toBeUndefined()
})

it("sends max_completion_tokens when includeMaxTokens is explicitly enabled (#2668 review)", async () => {
const fetchSpy = vi.spyOn(globalThis, "fetch")
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [{ message: { content: "response" }, finish_reason: "stop" }] }), {
status: 200,
}),
)
const handler = new KimiCodeHandler({
kimiCodeAuthMethod: "api-key",
kimiCodeApiKey: "kimi-key",
includeMaxTokens: true,
})
const gen = handler.createMessage("system", [{ role: "user", content: "test" }])
try {
for await (const _chunk of gen) {
// consume
}
} catch {
// expected - mock is incomplete
}
const body = JSON.parse((fetchSpy.mock.calls[0]?.[1] as { body?: string })?.body ?? "{}")
expect(body.max_completion_tokens).toBe(131_072)
})

it("uses kimi-for-coding only when no model is selected", () => {
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "kimi-key" })
expect(handler.getModel().id).toBe("kimi-for-coding")
Expand Down
29 changes: 26 additions & 3 deletions src/api/providers/__tests__/openai.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,10 +712,12 @@ describe("OpenAiHandler", () => {
expect(callArgs.max_completion_tokens).toBeUndefined()
})

it("should not include max_tokens when includeMaxTokens is undefined", async () => {
it("includes max_completion_tokens when includeMaxTokens is unset (UI default is checked) (#2230)", async () => {
const optionsWithUndefinedMaxTokens: ApiHandlerOptions = {
...mockOptions,
// includeMaxTokens is not set, should not include max_tokens
// includeMaxTokens is not set: the settings UI reads unset as
// checked (includeMaxTokens ?? true), so the request builder
// must agree and send the limit.
openAiCustomModelInfo: {
contextWindow: 128_000,
maxTokens: 4096,
Expand All @@ -726,7 +728,28 @@ describe("OpenAiHandler", () => {
const stream = handlerWithDefaultMaxTokens.createMessage(systemPrompt, messages)
// Consume the stream to trigger the API call
await collectStream(stream)
// Assert the mockCreate was called without max_tokens
// Assert the mockCreate was called with max_completion_tokens
expect(mockCreate).toHaveBeenCalled()
const callArgs = mockCreate.mock.calls[0][0]
expect(callArgs.max_completion_tokens).toBe(4096)
})

it("does not include max_completion_tokens when the model limit is null (#2668 review)", async () => {
const optionsWithNullMaxTokens: ApiHandlerOptions = {
...mockOptions,
includeMaxTokens: true,
// ModelInfo.maxTokens is nullish in the schema
// (z.number().nullish()), so `null` must not reach the request.
openAiCustomModelInfo: {
contextWindow: 128_000,
maxTokens: null,
supportsPromptCache: false,
},
}
const handlerWithNullMaxTokens = new OpenAiHandler(optionsWithNullMaxTokens)
const stream = handlerWithNullMaxTokens.createMessage(systemPrompt, messages)
// Consume the stream to trigger the API call
await collectStream(stream)
expect(mockCreate).toHaveBeenCalled()
const callArgs = mockCreate.mock.calls[0][0]
expect(callArgs.max_completion_tokens).toBeUndefined()
Expand Down
6 changes: 6 additions & 0 deletions src/api/providers/kimi-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ export class KimiCodeHandler extends OpenAiHandler {
openAiApiKey: options.kimiCodeApiKey ?? NOT_PROVIDED,
openAiModelId: options.apiModelId ?? kimiCodeDefaultModelId,
openAiStreamingEnabled: true,
// No "Include max output tokens" checkbox exists for Kimi Code, so
// the OpenAI Compatible default (include when unset) must not
// silently apply here: preserve the pre-#2230 behavior and only
// send max_completion_tokens when the user explicitly enabled it
// in stored settings (review feedback on #2668).
includeMaxTokens: options.includeMaxTokens ?? false,
})
this.kimiOptions = options
}
Expand Down
13 changes: 10 additions & 3 deletions src/api/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,11 +773,18 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl
| OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming,
modelInfo: ModelInfo,
): void {
// Only add max_completion_tokens if includeMaxTokens is true
if (this.options.includeMaxTokens === true) {
// The settings UI reads an unset value as CHECKED
// (includeMaxTokens ?? true), so the request builder must use the
// same default: include unless the user explicitly unticked the
// checkbox (issue #2230).
if (this.options.includeMaxTokens !== false) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

KimiCodeHandler (and any other subclass) inherits this default flip. They have no checkbox, so users cannot turn the field off. Is it safe for Kimi Code to receive max_completion_tokens by default? Should the default live in a shared constant that the UI also uses?

// Use user-configured modelMaxTokens if available, otherwise fall back to model's default maxTokens
// Using max_completion_tokens as max_tokens is deprecated
requestOptions.max_completion_tokens = this.options.modelMaxTokens || modelInfo.maxTokens
// ModelInfo.maxTokens is nullish in the schema, so `null` must not be sent
const limit = this.options.modelMaxTokens || modelInfo.maxTokens
if (limit) {
requestOptions.max_completion_tokens = limit
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@ it.each([
{ include: true, custom: undefined, model: 1000, expected: 1000 },
{ include: true, custom: 456, model: 1000, expected: 456 },
{ include: false, custom: 456, model: 1000, expected: undefined },
{ include: undefined, custom: 456, model: 1000, expected: undefined },
{ include: undefined, custom: 456, model: 1000, expected: 456 },
{ include: true, custom: undefined, model: undefined, expected: undefined },
{ include: true, custom: undefined, model: null, expected: undefined },
{ include: undefined, custom: undefined, model: null, expected: undefined },
])("honors output limit defaults and omission: %j", ({ include, custom, model, expected }) => {
const body = buildResponsesRequest(
makeInput({
Expand Down
8 changes: 5 additions & 3 deletions src/api/providers/utils/openai-compatible-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,12 @@ export function buildResponsesRequest({
if (String(reasoning.reasoning_effort) !== "none") requestBody.include = ["reasoning.encrypted_content"]
}

// Mirror the Chat Completions max-tokens policy: only cap output when the
// user opted in via includeMaxTokens.
// Mirror the Chat Completions max-tokens policy: the settings UI reads an
// unset includeMaxTokens as CHECKED (include unless explicitly unticked,
// #2230), and ModelInfo.maxTokens is nullish in the schema, so `null`
// must not be sent either.
const maxTokens = options.modelMaxTokens || modelInfo.maxTokens
if (options.includeMaxTokens === true && maxTokens !== undefined) {
if (options.includeMaxTokens !== false && maxTokens) {
requestBody.max_output_tokens = maxTokens
}

Expand Down