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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. expect(rule.modelMatch).toBe(reference.modelMatch);
  86. expect(rule.apiTypeMatch).toBe(reference.apiMatch);
  87. expect(rule.baseUrlMatch).toBe(reference.baseURLMatch);
  88. const compile = (map: string) =>
  89. compileModelOptionMaps({
  90. reasoningLevel: { map },
  91. maxOutputTokens: { map: outputMaps[reference.apiMatch]! },
  92. });
  93. const before = compile(entry.map);
  94. const after = compile(rule.config.optionSpecs!.reasoningLevel!.map!);
  95. for (const reasoningLevel of levels[group]!) {
  96. for (const base of bases) {
  97. const options = { reasoningLevel, maxOutputTokens: 32000 };
  98. // C 改名比较旧输入/旧 Map 与新输入/新 Map;A/B 的请求基线保持不变。
  99. const renamed =
  100. reasoningLevel === "off" || reasoningLevel === "nothink"
  101. ? "disabled"
  102. : reasoningLevel;
  103. expect(
  104. after.apply(base, { ...options, reasoningLevel: renamed }),
  105. reasoningLevel,
  106. ).toEqual(before.apply(base, options));
  107. }
  108. }
  109. });
  110. }
  111. }
  112. it("历史专用 Map 不遗漏;新增型号与 Go 站点由独立配置及 wire 验证承接", () => {
  113. const newModelMatchers = new Set([
  114. // OpenRouter 的无预算 enabled 修复由 openrouter-reasoning-contract.test.ts 独立验收。
  115. ".*(?:glm-|deepseek-|kimi-k2|qwen|mimo-).*",
  116. ".*gpt-6-astra(?:[.\\-:/\\[].*)?",
  117. ".*claude-(?:fable|mythos)-5[.-]1(?:[.\\-:/\\[].*)?",
  118. ".*deepseek-flash(?:[.\\-:/\\[].*)?",
  119. "deepseek-flash",
  120. ".*gpt-5\\.4(?:-(?:pro|mini|nano))?(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  121. ".*deepseek-v4[.-]1-flash(?:[.\\-:/\\[].*)?",
  122. ".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash))(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  123. ".*qwen3\\.8-omni-flash(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?",
  124. ]);
  125. const current = ["modelApiRules", "providerSiteRules"].flatMap((scope) =>
  126. rules[scope]!.flatMap((rule) =>
  127. rule.modelMatch !== ".*" &&
  128. !newModelMatchers.has(rule.modelMatch) &&
  129. // Go 新站点不属于 Todo95 历史基线;成员/档位/请求由 opencode-go 独立用例验证。
  130. !(
  131. scope === "providerSiteRules" && rule.baseUrlMatch === "https://opencode\\.ai/zen/go/v1/?"
  132. ) &&
  133. rule.config.optionSpecs?.reasoningLevel?.map
  134. ? [JSON.stringify([scope, rule.modelMatch, rule.apiTypeMatch, rule.baseUrlMatch])]
  135. : [],
  136. ),
  137. );
  138. expect(current.sort()).toEqual(
  139. baseline
  140. .flatMap((group) =>
  141. group.rules.map((rule) =>
  142. JSON.stringify([rule.scope, rule.modelMatch, rule.apiMatch, rule.baseURLMatch]),
  143. ),
  144. )
  145. .sort(),
  146. );
  147. });
  148. });
  149. describe("Todo95 API Schema 兜底", () => {
  150. for (const apiType of [
  151. "anthropic-messages",
  152. "openai-chat-completions",
  153. "openai-responses",
  154. ] as const) {
  155. it(`${apiType} 未知模型仅加档位即可继承 Map,Personal Map 保持权威`, () => {
  156. const original = snapshot.models.resolve({
  157. providerId: "unknown",
  158. modelId: "future-unknown-model",
  159. apiType,
  160. baseUrl: "https://example.test/v1",
  161. });
  162. expect(original.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  163. const configured = original.overlay(
  164. new ModelConfig({
  165. optionSpecs: new ModelOptionSpecsConfig({
  166. reasoningLevel: {
  167. values: [
  168. "disabled",
  169. "enabled",
  170. "low",
  171. "high",
  172. "max",
  173. ...(apiType === "anthropic-messages" ? [] : ["none"]),
  174. ],
  175. },
  176. }),
  177. }),
  178. );
  179. expect(configured.validateComplete()).toEqual([]);
  180. const selectionModel = {
  181. config: {
  182. optionSpecs: {
  183. reasoningLevel: { values: configured.optionSpecs!.reasoningLevel!.values! },
  184. },
  185. },
  186. };
  187. expect(
  188. validateModelSelectionOptions(selectionModel, {
  189. providerId: "unknown",
  190. modelId: "future-unknown-model",
  191. options: { reasoningLevel: "not-declared" },
  192. }),
  193. ).toMatchObject({ ok: false, code: "reasoning-level-not-supported" });
  194. const apply = (config: ModelConfig, reasoningLevel: string) =>
  195. compileModelOptionMaps({
  196. reasoningLevel: { map: config.optionSpecs!.reasoningLevel!.map! },
  197. maxOutputTokens: { map: config.optionSpecs!.maxOutputTokens!.map! },
  198. }).apply(
  199. { model: "future-unknown-model", messages: [] },
  200. { reasoningLevel, maxOutputTokens: 32000 },
  201. );
  202. for (const level of configured.optionSpecs!.reasoningLevel!.values!) {
  203. const effort = level === "disabled" ? "none" : level === "enabled" ? "high" : level;
  204. const disabled = level === "disabled" || level === "none";
  205. const expected =
  206. apiType === "anthropic-messages"
  207. ? level === "disabled"
  208. ? { thinking: { type: "disabled" } }
  209. : { thinking: { type: "adaptive" }, output_config: { effort } }
  210. : apiType === "openai-responses"
  211. ? { reasoning: { effort } }
  212. : {
  213. thinking: { type: disabled ? "disabled" : "enabled" },
  214. enable_thinking: !disabled,
  215. reasoning_effort: effort,
  216. reasoning: { effort },
  217. };
  218. const outputField =
  219. apiType === "anthropic-messages"
  220. ? "max_tokens"
  221. : apiType === "openai-responses"
  222. ? "max_output_tokens"
  223. : "max_completion_tokens";
  224. expect(apply(configured, level)).toEqual({
  225. model: "future-unknown-model",
  226. messages: [],
  227. ...expected,
  228. [outputField]: 32000,
  229. });
  230. }
  231. const custom = configured.overlay(
  232. new ModelConfig({
  233. optionSpecs: new ModelOptionSpecsConfig({
  234. reasoningLevel: { map: '{"custom_effort":reasoningLevel}' },
  235. }),
  236. }),
  237. );
  238. const request = apply(custom, "high");
  239. expect(request.custom_effort).toBe("high");
  240. expect(request).not.toHaveProperty("thinking");
  241. expect(request).not.toHaveProperty("reasoning");
  242. expect(original.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  243. });
  244. }
  245. });
  246. describe("Todo138 Model 层兜底与专用档位", () => {
  247. it("没有 API 信息也有 Model 两档;API 通用规则不声明档位", () => {
  248. const result = snapshot.models.resolve({
  249. providerId: "unknown",
  250. modelId: "future-unknown-model",
  251. });
  252. expect(result.optionSpecs!.reasoningLevel!.values).toEqual(["disabled", "enabled"]);
  253. expect(result.optionSpecs!.reasoningLevel!.map).toBe("{}");
  254. for (const rule of rules.modelApiRules!.filter((rule) => rule.modelMatch === ".*")) {
  255. expect(rule.config.optionSpecs?.reasoningLevel).not.toHaveProperty("values");
  256. }
  257. });
  258. it.each([
  259. ["gpt-5.4", ["none", "low", "medium", "high", "xhigh"]],
  260. ["GLM-5.3", ["low", "high", "max"]],
  261. ])("%s 专用档位在三种 API 下保持", (modelId, values) => {
  262. for (const apiType of [
  263. "anthropic-messages",
  264. "openai-chat-completions",
  265. "openai-responses",
  266. ] as const) {
  267. expect(
  268. snapshot.models.resolve({
  269. providerId: "unknown",
  270. modelId,
  271. apiType,
  272. baseUrl: "https://example.test/v1",
  273. }).optionSpecs!.reasoningLevel!.values,
  274. ).toEqual(values);
  275. }
  276. });
  277. });