Просмотр исходного кода

fix: import declared reasoning effort from provider presets

Import explicit models.dev effort options without deriving effort support from the reasoning flag. Cover preset normalization, saved metadata, roster selection, TUI controls and offline headless request bodies.

Adapted from hezhongtang/minimax-code@098fcf98cef044c885b611b3a3eebb03075be980 with additional integration and transport regression coverage.

Co-authored-by: hezhongtang <he_alexander91@126.com>
hetaoBackend 2 месяцев назад
Родитель
Сommit
79ad56e0d7

+ 23 - 0
packages/local-runtime-v2/src/service/model-system/catalog/list-models.test.ts

@@ -274,6 +274,29 @@ describe('model catalog entry helpers', () => {
     });
   });
 
+  it('exposes Kimi K3 low/high/max effort options in the model roster', () => {
+    const entry = buildModelEntry({
+      providerId: 'custom_provider:moonshotai',
+      modelId: 'kimi-k3',
+      model: {
+        name: 'Kimi K3',
+        reasoning: true,
+        thinking: { effortOptions: ['low', 'high', 'max'] },
+      },
+      selected: false,
+      providerSource: 'custom_provider',
+      providerKind: 'custom',
+      providerName: 'Moonshot AI',
+    });
+
+    expect(entry).toMatchObject({
+      modelId: 'kimi-k3',
+      displayName: 'Kimi K3',
+      effortOptions: ['low', 'high', 'max'],
+    });
+    expect(entry.defaultEffort).toBeUndefined();
+  });
+
   it('exposes context option hints only for managed models', () => {
     const model = {
       limit: { context: 512_000 },

+ 113 - 0
packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.test.ts

@@ -7,6 +7,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
 import { providerCompletionUrl, providerModelsUrls } from '../../connectivity/provider-request.js';
 import { ProviderPresetCatalog } from './provider-presets.service.js';
 import { readProviderPresetSnapshotCandidates } from './provider-presets.repository.js';
+import { modelsFromInputs } from '../../management/service-input.js';
+import { buildModelEntry } from '../list-models.js';
 
 vi.mock('./provider-presets.repository.js', async (importOriginal) => {
   const actual = await importOriginal<typeof import('./provider-presets.repository.js')>();
@@ -371,6 +373,117 @@ describe('models.dev Provider Presets', () => {
       },
     ]);
   });
+
+  it('parses declared reasoning effort options for Kimi K3 on both Moonshot providers', async () => {
+    const k3 = {
+      name: 'Kimi K3',
+      tool_call: true,
+      attachment: true,
+      reasoning: true,
+      reasoning_options: [
+        { type: 'toggle' },
+        { type: 'effort', values: ['low', 'high', 'max'] },
+      ],
+      temperature: false,
+      modalities: { input: ['text', 'image', 'video'], output: ['text'] },
+      limit: { context: 1_048_576, output: 131_072 },
+    };
+    const presets = await parsePresetsForTest({
+      moonshotai: {
+        name: 'Moonshot AI',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.moonshot.ai/v1',
+        models: {
+          'kimi-k3': k3,
+          'kimi-k2.6': {
+            name: 'Kimi K2.6',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'toggle' }],
+          },
+          'kimi-k2.7-code': {
+            name: 'Kimi K2.7 Code',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [],
+          },
+        },
+      },
+      'moonshotai-cn': {
+        name: 'Moonshot AI China',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.moonshot.cn/v1',
+        models: { 'kimi-k3': k3 },
+      },
+    });
+
+    for (const providerId of ['moonshotai', 'moonshotai-cn'] as const) {
+      const preset = presets.find((candidate) => candidate.providerId === providerId);
+      expect(preset?.models.find((model) => model.modelId === 'kimi-k3')).toMatchObject({
+        reasoning: true,
+        effortOptions: ['low', 'high', 'max'],
+      });
+      if (!preset) throw new Error(`Missing preset ${providerId}`);
+      const savedModel = modelsFromInputs(preset.models)['kimi-k3'];
+      expect(savedModel?.thinking).toEqual({ effortOptions: ['low', 'high', 'max'] });
+      expect(buildModelEntry({
+        providerId: `custom_provider:${providerId}`,
+        modelId: 'kimi-k3',
+        model: savedModel,
+        selected: false,
+        providerSource: 'custom_provider',
+        providerKind: 'custom',
+        providerName: preset.name,
+      }).effortOptions).toEqual(['low', 'high', 'max']);
+    }
+    const moonshot = presets.find((candidate) => candidate.providerId === 'moonshotai');
+    // A toggle-only or bare reasoning model can think, but declares no
+    // selectable effort levels, so it must not gain effortOptions.
+    for (const modelId of ['kimi-k2.6', 'kimi-k2.7-code'] as const) {
+      const model = moonshot?.models.find((candidate) => candidate.modelId === modelId);
+      expect(model).toMatchObject({ reasoning: true });
+      expect(model).not.toHaveProperty('effortOptions');
+    }
+  });
+
+  it('normalizes effort metadata without inventing or dropping declared levels', async () => {
+    const [preset] = await parsePresetsForTest({
+      compatible: {
+        name: 'Compatible API',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.example.test/v1',
+        models: {
+          custom: {
+            name: 'Custom',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [null, {}, { type: 'effort', values: 'high' },
+              { type: 'effort', values: [' light ', 'light', '', ' ', 7, null, 'max'] }],
+          },
+          'empty-effort': {
+            name: 'Empty effort',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'effort', values: [] }],
+          },
+          'budget-only': {
+            name: 'Budget only',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'budget_tokens', min: 128, max: 32_768 }],
+          },
+        },
+      },
+    });
+
+    const model = (modelId: string) =>
+      preset?.models.find((candidate) => candidate.modelId === modelId);
+    // Unknown levels are preserved verbatim; blanks, duplicates and
+    // non-strings never reach the roster.
+    expect(model('custom')).toMatchObject({ effortOptions: ['light', 'max'] });
+    expect(model('empty-effort')).not.toHaveProperty('effortOptions');
+    expect(model('budget-only')).not.toHaveProperty('effortOptions');
+  });
 });
 
 describe('models.dev Provider Preset snapshots', () => {

+ 28 - 0
packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.ts

@@ -169,6 +169,7 @@ function parseModel(modelId: string, value: unknown): UserModelInputView | undef
     modelId,
     displayName: stringValue(value.name) ?? modelId,
     ...parseModelCapabilities(value),
+    ...parseModelEffortOptions(value),
     ...parseModelModalities(value),
     ...parseModelLimit(value),
   };
@@ -183,6 +184,33 @@ function parseModelCapabilities(value: Record<string, unknown>): Partial<UserMod
   };
 }
 
+/**
+ * Reads the catalog's declared reasoning-effort levels. models.dev describes
+ * reasoning controls as `reasoning_options` entries; only an explicit
+ * `{ type: 'effort', values: [...] }` entry means the model accepts effort
+ * selection. A bare `reasoning: true` or a `toggle` entry only means the model
+ * can think, so neither one produces `effortOptions` here. Declared strings
+ * are preserved as-is (trimmed, de-duplicated, in catalog order) so levels the
+ * CLI does not know about still reach validation and the wire unchanged.
+ */
+function parseModelEffortOptions(value: Record<string, unknown>): Partial<UserModelInputView> {
+  if (!Array.isArray(value.reasoning_options)) return {};
+  for (const option of value.reasoning_options) {
+    if (!isRecord(option) || option.type !== 'effort' || !Array.isArray(option.values)) continue;
+    const effortOptions: string[] = [];
+    const seen = new Set<string>();
+    for (const candidate of option.values) {
+      if (typeof candidate !== 'string') continue;
+      const effort = candidate.trim();
+      if (!effort || seen.has(effort)) continue;
+      seen.add(effort);
+      effortOptions.push(effort);
+    }
+    if (effortOptions.length > 0) return { effortOptions };
+  }
+  return {};
+}
+
 function parseModelModalities(value: Record<string, unknown>): Partial<UserModelInputView> {
   const modalities = isRecord(value.modalities) ? value.modalities : undefined;
   const input = stringArray(modalities?.input);

+ 17 - 0
packages/local-runtime-v2/src/service/model-system/management/service-input.test.ts

@@ -96,6 +96,23 @@ describe('model provider input normalization', () => {
     });
   });
 
+  it('persists declared Kimi K3 effort options as thinking metadata', () => {
+    expect(
+      modelsFromInputs([
+        {
+          modelId: 'kimi-k3',
+          displayName: 'Kimi K3',
+          reasoning: true,
+          effortOptions: ['low', 'high', 'max'],
+        },
+      ])['kimi-k3'],
+    ).toEqual({
+      name: 'Kimi K3',
+      reasoning: true,
+      thinking: { effortOptions: ['low', 'high', 'max'] },
+    });
+  });
+
   it('applies implicit thinking only to eligible new models', () => {
     expect(modelsFromInputs([{ modelId: 'implicit' }], undefined, true).implicit).toMatchObject({
       reasoning: true,

+ 26 - 0
packages/local-runtime-v2/src/service/model-system/resolution/model-ref.test.ts

@@ -403,6 +403,32 @@ describe('BYOK Think Effort selection', () => {
     });
   });
 
+  it.each(['low', 'high', 'max'] as const)(
+    'carries the Kimi K3 effort %s from catalog metadata to the OpenAI-compatible request patch',
+    (effort) => {
+      // What the models.dev preset chain persists for moonshotai/kimi-k3:
+      // reasoning_options { type: 'effort', values: ['low', 'high', 'max'] }
+      // becomes thinking.effortOptions on the stored model config.
+      const config: LocalModelConfig = {
+        name: 'Kimi K3',
+        reasoning: true,
+        thinking: { effortOptions: ['low', 'high', 'max'] },
+      };
+      const ref = modelRefForModel('custom_provider:moonshotai', 'kimi-k3', config, {
+        thinking: { effort },
+      });
+
+      const selectedEffort = readSelectedThinkingEffort(ref.capabilities);
+      expect(selectedEffort).toBe(effort);
+      expect(
+        resolveByokThinkingProtocol('openai-completions', selectedEffort, ref.model_id),
+      ).toMatchObject({
+        effort,
+        requestPatch: { reasoning_effort: effort },
+      });
+    },
+  );
+
   it.each([`${DEFAULT_THINKING_MODEL_IDS[0]}[1m]`, ...DEFAULT_THINKING_MODEL_IDS.slice(1)])(
     'omits thinking for default-thinking model %s while preserving effort',
     (modelId) => {

+ 39 - 0
packages/tui/test/unit/headless-model-selection.test.ts

@@ -397,3 +397,42 @@ describe('resolveHeadlessModelSelection', () => {
     ).resolves.toEqual({ providerId: 'provider', modelId: 'model', variant: 'fast' });
   });
 });
+
+describe('resolveHeadlessModelSelection with Kimi K3 effort levels', () => {
+  const k3Runtime = () =>
+    runtimeWith(
+      catalog({
+        providerId: 'custom_provider:moonshotai',
+        modelId: 'kimi-k3',
+        selected: true,
+        effortOptions: ['low', 'high', 'max'],
+      }),
+    );
+
+  it.each(['low', 'high', 'max'] as const)('accepts --effort %s', async (effort) => {
+    await expect(
+      resolveHeadlessModelSelection({
+        model: 'custom_provider:moonshotai/kimi-k3',
+        effort,
+        session: session(),
+        runtime: k3Runtime(),
+      }),
+    ).resolves.toEqual({
+      providerId: 'custom_provider:moonshotai',
+      modelId: 'kimi-k3',
+      thinking: { effort },
+    });
+  });
+
+  it('rejects an effort level Kimi K3 does not declare', async () => {
+    await expectInvocationError(
+      resolveHeadlessModelSelection({
+        model: 'custom_provider:moonshotai/kimi-k3',
+        effort: 'medium',
+        session: session(),
+        runtime: k3Runtime(),
+      }),
+      '--effort medium is not available for custom_provider:moonshotai/kimi-k3. Available levels: low, high, max.',
+    );
+  });
+});

+ 22 - 0
packages/tui/test/unit/tui-model-picker.test.ts

@@ -3,6 +3,28 @@ import { describe, expect, it, vi } from "vitest";
 import { TuiModelPicker } from "../../src/tui/features/model/picker.js";
 
 describe("TuiModelPicker", () => {
+  it("selects each declared Kimi K3 effort without inventing a medium level", () => {
+    const onSelect = vi.fn();
+    const model = {
+      providerId: "custom_provider:moonshotai",
+      modelId: "kimi-k3",
+      selected: true,
+      effortOptions: ["low", "high", "max"],
+    };
+    const picker = new TuiModelPicker([model], onSelect, vi.fn());
+    expect(stripAnsi(picker.render(80).join("\n"))).toContain("[ high ]");
+    for (const [key, effort] of [
+      ["\u001b[D", "low"],
+      ["\u001b[C", "high"],
+      ["\u001b[C", "max"],
+    ] as const) {
+      picker.handleInput(key);
+      expect(stripAnsi(picker.render(80).join("\n"))).toContain(`[ ${effort} ]`);
+      picker.handleInput("\r");
+      expect(onSelect).toHaveBeenLastCalledWith(model, effort);
+    }
+  });
+
   it("switches M3 context independently of thinking and restores the saved choice", () => {
     const model = {
       providerId: "minimax",

+ 23 - 1
test/byok.test.mjs

@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";
 import path from "node:path";
 import { fileURLToPath } from "node:url";
 import Database from "better-sqlite3";
-import { parse as parseYaml } from "yaml";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
 import { withoutProxyEnvironment } from "./offline-environment.mjs";
 
 const cli = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
@@ -335,6 +335,28 @@ test(
       assert.equal(savedConfig().defaultModel, config.defaultModel);
     }
     assert.equal(requests.length, beforeSaveOnly, "Limits alone must not test or select a model");
+    // Exercise the metadata persisted by provider preset import through real
+    // config reload, headless validation and the OpenAI-compatible request body.
+    const effortConfig = savedConfig();
+    effortConfig.custom_provider.fixture.models["kimi-k3"] = {
+      reasoning: true,
+      thinking: { effortOptions: ["low", "high", "max"] },
+    };
+    writeFileSync(configPath, stringifyYaml(effortConfig));
+    const effortModel = `${selected.providerId}/kimi-k3`;
+    for (const effort of ["low", "high", "max"]) {
+      const beforeEffort = requests.length;
+      await run(["exec", "EFFORT_TEST", "--model", effortModel, "--effort", effort,
+        "--timeout", "20s", "--max-steps", "1"]);
+      const modelRequests = requests.slice(beforeEffort).filter((r) => r.body.model === "kimi-k3");
+      assert.ok(modelRequests.length > 0);
+      for (const request of modelRequests) assert.equal(request.body.reasoning_effort, effort);
+    }
+    const beforeInvalidEffort = requests.length;
+    await assert.rejects(run(["exec", "EFFORT_TEST", "--model", effortModel,
+      "--effort", "medium", "--timeout", "20s", "--max-steps", "1"]),
+    /Available levels: low, high, max/);
+    assert.equal(requests.length, beforeInvalidEffort, "Invalid effort must fail before transport");
     const modelArgs = ["--model", `${selected.providerId}/fixture-model`];
     // The first run must work through the saved default, without --model or managed login.
     const first = await run([