zcode-builtin-reasoning-map.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { readFile } from "node:fs/promises";
  2. import { fileURLToPath } from "node:url";
  3. import { beforeAll, afterAll, describe, expect, it } from "vitest";
  4. import { compileModelOptionMaps } from "@zcode/model-option-map";
  5. import {
  6. ModelConfig,
  7. ModelOptionSpecsConfig,
  8. validateModelSelectionOptions,
  9. } from "@zcode/provider";
  10. import { NodeZCodeBuiltinProviderConfigSource } from "../src/index.js";
  11. import baseline from "./fixtures/reasoning-map-before-todo95.json";
  12. const source = new NodeZCodeBuiltinProviderConfigSource({
  13. bundledFilePath: fileURLToPath(
  14. new URL("../../../config/provider/zcode-builtin.json", import.meta.url),
  15. ),
  16. watch: false,
  17. });
  18. let snapshot: Awaited<ReturnType<typeof source.read>>;
  19. type Rule = {
  20. modelMatch: string;
  21. apiTypeMatch: string;
  22. baseUrlMatch?: string;
  23. config: { optionSpecs?: { reasoningLevel?: { map?: string } } };
  24. };
  25. let rules: Record<string, Rule[]>;
  26. beforeAll(async () => {
  27. snapshot = await source.read();
  28. rules = JSON.parse(
  29. await readFile(new URL("../../../config/provider/zcode-builtin.json", import.meta.url), "utf8"),
  30. ).config.modelConfigRules;
  31. });
  32. afterAll(() => source.dispose());
  33. // 基线取自 a56dc32c26 的专用表达式,按相同表达式分组但逐条验证规则,不能随美化更新预期。
  34. const levels = [
  35. ["low", "high", "max"],
  36. ["low", "high", "max"],
  37. ["off", "nothink", "disabled", "enabled"],
  38. ["nothink", "high", "max"],
  39. ["low", "high", "max"],
  40. ["none", "low", "medium", "high", "xhigh", "max"],
  41. ["low", "medium", "high", "xhigh"],
  42. ["low", "medium", "high", "xhigh", "max"],
  43. ["low", "high", "max"],
  44. ["off", "enabled"],
  45. ["off", "enabled"],
  46. ["off", "low", "high", "max"],
  47. ["off", "low", "high", "max"],
  48. ["low", "medium", "xhigh"],
  49. ["low", "medium", "xhigh"],
  50. ["low", "medium", "xhigh"],
  51. ["disabled", "off", "enabled"],
  52. ["none", "low", "medium", "high", "xhigh", "max"],
  53. ["off", "low", "high", "max"],
  54. ];
  55. const outputMaps: Record<string, string> = {
  56. "anthropic-messages": '{"max_tokens":maxOutputTokens}',
  57. "openai-chat-completions": '{"max_completion_tokens":maxOutputTokens}',
  58. "openai-responses": '{"max_output_tokens":maxOutputTokens}',
  59. };
  60. const bases = [
  61. { model: "unchanged", messages: [] },
  62. {
  63. model: "unchanged",
  64. messages: [],
  65. thinking: { type: "before", budget_tokens: 777 },
  66. output_config: { effort: "before", extra: true },
  67. reasoning: { effort: "before", summary: "auto" },
  68. reasoning_effort: "before",
  69. enable_thinking: null,
  70. },
  71. ];
  72. describe("Todo95 专用 Map 合法请求等价", () => {
  73. for (const [group, entry] of baseline.entries()) {
  74. for (const reference of entry.rules) {
  75. it(`${reference.scope}[${reference.index}] ${reference.modelMatch} ${reference.apiMatch}`, () => {
  76. // 规则重组会改变下标;按完整匹配条件定位,基线表达式及请求断言不变。
  77. const matches = rules[reference.scope]!.filter(
  78. (rule) =>
  79. rule.modelMatch === reference.modelMatch &&
  80. rule.apiTypeMatch === reference.apiMatch &&
  81. rule.baseUrlMatch === reference.baseURLMatch,
  82. );
  83. expect(matches).toHaveLength(1);
  84. const rule = matches[0]!;
  85. const compile = (map: string) =>
  86. compileModelOptionMaps({
  87. reasoningLevel: { map },
  88. maxOutputTokens: { map: outputMaps[reference.apiMatch]! },
  89. });
  90. const before = compile(entry.map);
  91. const after = compile(rule.config.optionSpecs!.reasoningLevel!.map!);
  92. for (const reasoningLevel of levels[group]!) {
  93. for (const base of bases) {
  94. const options = { reasoningLevel, maxOutputTokens: 32000 };
  95. // C 改名比较旧输入/旧 Map 与新输入/新 Map;A/B 的请求基线保持不变。
  96. const renamed =
  97. reasoningLevel === "off" || reasoningLevel === "nothink"
  98. ? "disabled"
  99. : reasoningLevel;
  100. expect(
  101. after.apply(base, { ...options, reasoningLevel: renamed }),
  102. reasoningLevel,
  103. ).toEqual(before.apply(base, options));
  104. }
  105. }
  106. });
  107. }
  108. }
  109. it("历史专用 Map 不遗漏;新增型号与 Go 站点由独立配置及 wire 验证承接", () => {
  110. const newModelMatchers = new Set([
  111. // OpenRouter 的无预算 enabled 修复由 openrouter-reasoning-contract.test.ts 独立验收。
  112. ".*(?:glm-|deepseek-|kimi-k2|qwen|mimo-).*",
  113. ".*gpt-6-astra(?:[.\\-:/\\[].*)?",
  114. ".*claude-(?:fable|mythos)-5[.-]1(?:[.\\-:/\\[].*)?",
  115. ".*deepseek-flash(?:[.\\-:/\\[].*)?",
  116. "deepseek-flash",
  117. ".*gpt-5\\.4(?:-(?:pro|mini|nano))?(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  118. ".*deepseek-v4[.-]1-flash(?:[.\\-:/\\[].*)?",
  119. ".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash))(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  120. ".*qwen3\\.8-omni-flash(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  121. // 简化后的 Model/API matcher;Site 仍保留原选择条件。
  122. ".*gpt-6-astra.*",
  123. ".*claude-(?:fable|mythos)-5[.-]1.*",
  124. ".*deepseek-flash.*",
  125. ".*deepseek-v4[.-]1-flash.*",
  126. ".*qwen3\\.8-omni-flash.*",
  127. ".*gpt-5\\.4.*",
  128. ".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash)).*",
  129. // 新型号已由 MiMo 配置与 wire 用例验收,不属于 Todo95 历史 Map 基线。
  130. // 依据:docs/provider-mimo-templates.md「模型及兼容边界」「验收」MIMO-01/02;
  131. // 独立覆盖见同目录 mimo-templates.test.ts(含 thinking.type / max_tokens 请求映射)。
  132. ".*mimo-v2\\.6-(?:pro|flash).*",
  133. ]);
  134. const current = ["modelApiRules", "providerSiteRules"].flatMap((scope) =>
  135. rules[scope]!.flatMap((rule) =>
  136. rule.modelMatch !== ".*" &&
  137. !newModelMatchers.has(rule.modelMatch) &&
  138. // Go 新站点不属于 Todo95 历史基线;成员/档位/请求由 opencode-go 独立用例验证。
  139. !(
  140. scope === "providerSiteRules" && rule.baseUrlMatch === "https://opencode\\.ai/zen/go/v1/?"
  141. ) &&
  142. rule.config.optionSpecs?.reasoningLevel?.map
  143. ? [JSON.stringify([scope, rule.modelMatch, rule.apiTypeMatch, rule.baseUrlMatch])]
  144. : [],
  145. ),
  146. );
  147. expect(current.sort()).toEqual(
  148. baseline
  149. .flatMap((group) =>
  150. group.rules.map((rule) =>
  151. JSON.stringify([rule.scope, rule.modelMatch, rule.apiMatch, rule.baseURLMatch]),
  152. ),
  153. )
  154. .sort(),
  155. );
  156. });
  157. });
  158. describe("Todo95 API Schema 兜底", () => {
  159. for (const apiType of [
  160. "anthropic-messages",
  161. "openai-chat-completions",
  162. "openai-responses",
  163. ] as const) {
  164. it(`${apiType} 未知模型仅加档位即可继承 Map,Personal Map 保持权威`, () => {
  165. const original = snapshot.models.resolve({
  166. providerId: "unknown",
  167. modelId: "future-unknown-model",
  168. apiType,
  169. baseUrl: "https://example.test/v1",
  170. });
  171. expect(original.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  172. const configured = original.overlay(
  173. new ModelConfig({
  174. optionSpecs: new ModelOptionSpecsConfig({
  175. reasoningLevel: {
  176. values: [
  177. "disabled",
  178. "enabled",
  179. "low",
  180. "high",
  181. "max",
  182. ...(apiType === "anthropic-messages" ? [] : ["none"]),
  183. ],
  184. },
  185. }),
  186. }),
  187. );
  188. expect(configured.validateComplete()).toEqual([]);
  189. const selectionModel = {
  190. config: {
  191. optionSpecs: {
  192. reasoningLevel: { values: configured.optionSpecs!.reasoningLevel!.values! },
  193. },
  194. },
  195. };
  196. expect(
  197. validateModelSelectionOptions(selectionModel, {
  198. providerId: "unknown",
  199. modelId: "future-unknown-model",
  200. options: { reasoningLevel: "not-declared" },
  201. }),
  202. ).toMatchObject({ ok: false, code: "reasoning-level-not-supported" });
  203. const apply = (config: ModelConfig, reasoningLevel: string) =>
  204. compileModelOptionMaps({
  205. reasoningLevel: { map: config.optionSpecs!.reasoningLevel!.map! },
  206. maxOutputTokens: { map: config.optionSpecs!.maxOutputTokens!.map! },
  207. }).apply(
  208. { model: "future-unknown-model", messages: [] },
  209. { reasoningLevel, maxOutputTokens: 32000 },
  210. );
  211. for (const level of configured.optionSpecs!.reasoningLevel!.values!) {
  212. const effort = level === "disabled" ? "none" : level === "enabled" ? "high" : level;
  213. const disabled = level === "disabled" || level === "none";
  214. const expected =
  215. apiType === "anthropic-messages"
  216. ? level === "disabled"
  217. ? { thinking: { type: "disabled" } }
  218. : { thinking: { type: "adaptive" }, output_config: { effort } }
  219. : apiType === "openai-responses"
  220. ? { reasoning: { effort } }
  221. : {
  222. thinking: { type: disabled ? "disabled" : "enabled" },
  223. enable_thinking: !disabled,
  224. reasoning_effort: effort,
  225. reasoning: { effort },
  226. };
  227. const outputField =
  228. apiType === "anthropic-messages"
  229. ? "max_tokens"
  230. : apiType === "openai-responses"
  231. ? "max_output_tokens"
  232. : "max_completion_tokens";
  233. expect(apply(configured, level)).toEqual({
  234. model: "future-unknown-model",
  235. messages: [],
  236. ...expected,
  237. [outputField]: 32000,
  238. });
  239. }
  240. const custom = configured.overlay(
  241. new ModelConfig({
  242. optionSpecs: new ModelOptionSpecsConfig({
  243. reasoningLevel: { map: '{"custom_effort":reasoningLevel}' },
  244. }),
  245. }),
  246. );
  247. const request = apply(custom, "high");
  248. expect(request.custom_effort).toBe("high");
  249. expect(request).not.toHaveProperty("thinking");
  250. expect(request).not.toHaveProperty("reasoning");
  251. expect(original.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  252. });
  253. }
  254. });
  255. describe("Todo138 Model 层兜底与专用档位", () => {
  256. it("没有 API 信息也有 Model 两档;API 通用规则不声明档位", () => {
  257. const result = snapshot.models.resolve({
  258. providerId: "unknown",
  259. modelId: "future-unknown-model",
  260. });
  261. expect(result.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  262. expect(result.optionSpecs!.reasoningLevel!.map).toBe("{}");
  263. for (const rule of rules.modelApiRules!.filter((rule) => rule.modelMatch === ".*")) {
  264. expect(rule.config.optionSpecs?.reasoningLevel).not.toHaveProperty("values");
  265. }
  266. });
  267. it.each([
  268. ["gpt-5.4", ["none", "low", "medium", "high", "xhigh"]],
  269. ["GLM-5.3", ["low", "high", "max"]],
  270. ])("%s 专用档位在三种 API 下保持", (modelId, values) => {
  271. for (const apiType of [
  272. "anthropic-messages",
  273. "openai-chat-completions",
  274. "openai-responses",
  275. ] as const) {
  276. expect(
  277. snapshot.models.resolve({
  278. providerId: "unknown",
  279. modelId,
  280. apiType,
  281. baseUrl: "https://example.test/v1",
  282. }).optionSpecs!.reasoningLevel!.values,
  283. ).toEqual(values);
  284. }
  285. });
  286. });