config-overlay.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. EnumOptionSpecConfig,
  4. LimitOptionSpecConfig,
  5. ModelConfig,
  6. ModelInputFormatConfig,
  7. ModelOptionSpecsConfig,
  8. ModelOutputFormatConfig,
  9. ModelPropertiesConfig,
  10. ApiKeyAccessConfig,
  11. ProviderApiConfig,
  12. ProviderConfig,
  13. ProviderConfigMap,
  14. parseModelConfig,
  15. parseProviderConfigMap,
  16. } from "../src/index.js";
  17. describe("ProviderConfigMap overlay", () => {
  18. it("Provider enabled 位于外层;Overlay、往返及后续配置写入保留 false", () => {
  19. const base = parseProviderConfigMap([{ providerId: "p", enabled: true, config: {} }]);
  20. const off = parseProviderConfigMap([{ providerId: "p", enabled: false, config: {} }]);
  21. const updated = base
  22. .overlay(off)
  23. .overlay(parseProviderConfigMap([{ providerId: "p", providerName: "renamed", config: {} }]));
  24. expect(updated.getRule("p")?.enabled).toBe(false);
  25. expect(parseProviderConfigMap(updated.toJSON()).getRule("p")?.enabled).toBe(false);
  26. expect(() =>
  27. parseProviderConfigMap([{ providerId: "p", config: { enabled: false } }]),
  28. ).toThrow();
  29. });
  30. it.each([0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])(
  31. "完整属性和保存 Schema 一致拒绝非法 contextWindow:%s",
  32. (contextWindow) => {
  33. const properties = new ModelPropertiesConfig({
  34. contextWindow,
  35. inputFormat: {
  36. supportsText: true,
  37. supportsImage: false,
  38. supportsVideo: false,
  39. supportsAudio: false,
  40. supportsPdf: false,
  41. },
  42. outputFormat: { supportsText: true },
  43. supportsToolCall: true,
  44. supportsJsonSchemaOutput: true,
  45. supportsNativeWebSearch: false,
  46. supportsMidConversationSystem: false,
  47. });
  48. expect(() => parseModelConfig({ properties: properties.toJSON() })).toThrow();
  49. expect(properties.validateComplete()).toContainEqual(
  50. expect.objectContaining({ path: ["contextWindow"] }),
  51. );
  52. },
  53. );
  54. it.each([{ values: [" "] }, { values: ["low", "low"] }])(
  55. "稀疏 Schema 同样拒绝非法档位 $values",
  56. ({ values }) => {
  57. expect(() => parseModelConfig({ optionSpecs: { reasoningLevel: { values } } })).toThrow();
  58. },
  59. );
  60. it("完整输出上限拒绝非安全整数", () => {
  61. const spec = new LimitOptionSpecConfig({
  62. max: Number.MAX_SAFE_INTEGER + 1,
  63. map: "{'max_tokens': maxOutputTokens}",
  64. });
  65. expect(spec.validateComplete()).toContainEqual(expect.objectContaining({ path: ["max"] }));
  66. });
  67. it("保留 ZCodeBuiltin key 的位置,并按 Personal 顺序追加新 key", () => {
  68. const zcodeBuiltin = new ProviderConfigMap([
  69. {
  70. providerId: "A",
  71. providerName: "ZCodeBuiltin A",
  72. config: new ProviderConfig({
  73. logo: { type: "builtin", key: "provider-a" },
  74. builtinModelIds: ["m1", "m2"],
  75. }),
  76. },
  77. ["B", new ProviderConfig({ api: new ProviderApiConfig({ baseUrl: "https://b.example" }) })],
  78. ["C", new ProviderConfig({ api: new ProviderApiConfig({ baseUrl: "https://c.example" }) })],
  79. ]);
  80. const personal = new ProviderConfigMap([
  81. ["Y", new ProviderConfig()],
  82. { providerId: "C", providerName: "Personal C", config: new ProviderConfig({}) },
  83. ["X", new ProviderConfig()],
  84. {
  85. providerId: "A",
  86. providerName: "Personal A",
  87. config: new ProviderConfig({
  88. access: new ApiKeyAccessConfig({
  89. apiKeyManagementUrl: "https://personal.example/api-keys",
  90. }),
  91. personalModelIds: ["m1"],
  92. }),
  93. },
  94. ]);
  95. const effective = zcodeBuiltin.overlay(personal);
  96. expect(effective.keys()).toEqual(["A", "B", "C", "Y", "X"]);
  97. expect(effective.get("A")?.builtinModelIds).toEqual(["m1", "m2"]);
  98. expect(effective.get("A")?.personalModelIds).toEqual(["m1"]);
  99. expect(effective.getRule("A")?.providerName).toBe("Personal A");
  100. expect(effective.get("A")?.logo).toEqual({ type: "builtin", key: "provider-a" });
  101. expect(
  102. effective.get("A")?.access?.type === "api-key"
  103. ? effective.get("A")?.access.apiKeyManagementUrl
  104. : undefined,
  105. ).toBe("https://personal.example/api-keys");
  106. expect(effective.get("C")?.api?.baseUrl).toBe("https://c.example");
  107. expect(effective.getRule("C")?.providerName).toBe("Personal C");
  108. expect(zcodeBuiltin.get("A")?.builtinModelIds).toEqual(["m1", "m2"]);
  109. expect(personal.keys()).toEqual(["Y", "C", "X", "A"]);
  110. });
  111. it("按照给定顺序重排已有 key,同时保留未提到的 key", () => {
  112. const personal = new ProviderConfigMap([
  113. ["Y", new ProviderConfig()],
  114. { providerId: "C", providerName: "Personal C", config: new ProviderConfig({}) },
  115. ["X", new ProviderConfig()],
  116. ["A", new ProviderConfig({ personalModelIds: ["m1"] })],
  117. ["unmentioned", new ProviderConfig()],
  118. ]);
  119. const reordered = personal.reorder(["A", "B", "C", "X", "Y"]);
  120. expect(reordered.keys()).toEqual(["A", "C", "X", "Y", "unmentioned"]);
  121. expect(personal.keys()).toEqual(["Y", "C", "X", "A", "unmentioned"]);
  122. });
  123. it("递归覆盖 Config 字段,并整体替换普通字段", () => {
  124. const base = new ModelConfig({
  125. properties: new ModelPropertiesConfig({
  126. requiresMfjsToolSchema: false,
  127. contextWindow: 200_000,
  128. inputFormat: new ModelInputFormatConfig({
  129. supportsText: true,
  130. supportsImage: false,
  131. supportsPdf: false,
  132. }),
  133. outputFormat: new ModelOutputFormatConfig({ supportsText: true }),
  134. }),
  135. optionSpecs: new ModelOptionSpecsConfig({
  136. reasoningLevel: {
  137. values: ["low", "high"],
  138. map: "{'reasoning': {'effort': reasoningLevel}}",
  139. },
  140. maxOutputTokens: {
  141. max: 32_000,
  142. map: "{'max_output_tokens': maxOutputTokens}",
  143. },
  144. }),
  145. });
  146. const patch = new ModelConfig({
  147. properties: new ModelPropertiesConfig({
  148. requiresMfjsToolSchema: true,
  149. inputFormat: new ModelInputFormatConfig({ supportsImage: true }),
  150. }),
  151. optionSpecs: new ModelOptionSpecsConfig({
  152. reasoningLevel: { values: ["off", "on"] },
  153. }),
  154. });
  155. const effective = base.overlay(patch);
  156. expect(effective.properties?.contextWindow).toBe(200_000);
  157. expect(effective.properties?.inputFormat?.supportsText).toBe(true);
  158. expect(effective.properties?.inputFormat?.supportsImage).toBe(true);
  159. expect(effective.properties?.inputFormat?.supportsPdf).toBe(false);
  160. expect(effective.properties?.outputFormat?.supportsText).toBe(true);
  161. expect(effective.optionSpecs?.reasoningLevel).toEqual({
  162. values: ["off", "on"],
  163. map: "{'reasoning': {'effort': reasoningLevel}}",
  164. });
  165. expect(effective.optionSpecs?.maxOutputTokens).toEqual({
  166. max: 32_000,
  167. map: "{'max_output_tokens': maxOutputTokens}",
  168. });
  169. expect(effective.properties?.requiresMfjsToolSchema).toBe(true);
  170. });
  171. it("最终 Option Spec 必须包含可编译且返回 Object 的 map", () => {
  172. const model = new ModelConfig({
  173. properties: new ModelPropertiesConfig({
  174. requiresMfjsToolSchema: false,
  175. contextWindow: 200_000,
  176. inputFormat: {
  177. supportsText: true,
  178. supportsImage: false,
  179. supportsVideo: false,
  180. supportsAudio: false,
  181. supportsPdf: false,
  182. },
  183. outputFormat: { supportsText: true },
  184. supportsToolCall: true,
  185. supportsJsonSchemaOutput: true,
  186. supportsNativeWebSearch: false,
  187. supportsMidConversationSystem: false,
  188. }),
  189. optionSpecs: new ModelOptionSpecsConfig({
  190. reasoningLevel: {
  191. values: ["low", "high"],
  192. map: "reasoningLevel.field",
  193. },
  194. maxOutputTokens: {
  195. max: 32_000,
  196. map: "{'max_tokens': maxOutputTokens}",
  197. },
  198. }),
  199. });
  200. expect(model.validateComplete(["models", "example"])).toContainEqual({
  201. code: "invalid-option-spec",
  202. path: ["models", "example", "optionSpecs", "reasoningLevel", "map"],
  203. message: expect.stringContaining("member access"),
  204. });
  205. });
  206. it("Option Spec 只能引用自己的同名输入变量", () => {
  207. expect(() =>
  208. parseModelConfig({
  209. optionSpecs: {
  210. reasoningLevel: {
  211. map: "{'reasoning_effort': maxOutputTokens}",
  212. },
  213. },
  214. }),
  215. ).toThrow(/maxOutputTokens/);
  216. expect(() =>
  217. parseModelConfig({
  218. optionSpecs: {
  219. maxOutputTokens: {
  220. map: "{'max_tokens': reasoningLevel}",
  221. },
  222. },
  223. }),
  224. ).toThrow(/reasoningLevel/);
  225. });
  226. it("使用 supportsJsonSchemaOutput 表达严格 JSON Schema 能力", () => {
  227. expect(
  228. parseModelConfig({
  229. properties: { supportsJsonSchemaOutput: true },
  230. }).properties?.supportsJsonSchemaOutput,
  231. ).toBe(true);
  232. expect(() =>
  233. parseModelConfig({
  234. properties: { supportsStructuredOutput: true },
  235. }),
  236. ).toThrow();
  237. });
  238. it("最终 Model Config 必须包含完整 Reasoning Option Spec", () => {
  239. const model = new ModelConfig({
  240. optionSpecs: new ModelOptionSpecsConfig({
  241. maxOutputTokens: {
  242. max: 32_000,
  243. map: "{'max_tokens': maxOutputTokens}",
  244. },
  245. }),
  246. });
  247. expect(
  248. model.optionSpecs?.validateComplete(["models", "example", "optionSpecs"]),
  249. ).toContainEqual(
  250. expect.objectContaining({
  251. code: "required-field-missing",
  252. path: ["models", "example", "optionSpecs", "reasoningLevel"],
  253. }),
  254. );
  255. });
  256. it("接受 disabled 单档位与空 Request Body Patch 作为无推理基线", () => {
  257. const optionSpecs = new ModelOptionSpecsConfig({
  258. reasoningLevel: {
  259. values: ["disabled"],
  260. map: "{}",
  261. },
  262. maxOutputTokens: {
  263. max: 32_000,
  264. map: "{'max_tokens': maxOutputTokens}",
  265. },
  266. });
  267. expect(optionSpecs.validateComplete(["models", "example", "optionSpecs"])).toEqual([]);
  268. });
  269. it.each([
  270. { values: [], message: "reasoningLevel.values 不能为空" },
  271. { values: ["low", ""], message: "reasoningLevel.values 必须是非空字符串" },
  272. { values: ["low", "low"], message: "reasoningLevel.values 不能重复" },
  273. ])("拒绝不完整的 Reasoning 档位:$message", ({ values, message }) => {
  274. const spec = new EnumOptionSpecConfig({ values, map: "{}" });
  275. expect(spec.validateComplete(["optionSpecs", "reasoningLevel"])).toContainEqual(
  276. expect.objectContaining({ code: "invalid-option-spec", message }),
  277. );
  278. });
  279. it("Schema 在写入边界拒绝返回非 Object 的 Option map", () => {
  280. expect(() =>
  281. parseModelConfig({
  282. optionSpecs: {
  283. reasoningLevel: {
  284. values: ["low", "high"],
  285. map: "reasoningLevel",
  286. },
  287. },
  288. }),
  289. ).toThrow(/object/i);
  290. });
  291. it("Schema 拒绝已退役的 Option Spec default", () => {
  292. expect(() =>
  293. parseModelConfig({
  294. optionSpecs: {
  295. reasoningLevel: {
  296. values: ["low", "high"],
  297. default: "high",
  298. map: "{'reasoning': {'effort': reasoningLevel}}",
  299. },
  300. },
  301. }),
  302. ).toThrow(/unrecognized|default/i);
  303. });
  304. it("用 null 清除字段,并在最终完整性校验中报告必填值缺失", () => {
  305. const base = new ModelConfig({
  306. properties: new ModelPropertiesConfig({
  307. requiresMfjsToolSchema: false,
  308. contextWindow: 200_000,
  309. inputFormat: {
  310. supportsText: true,
  311. supportsImage: false,
  312. supportsVideo: false,
  313. supportsAudio: false,
  314. supportsPdf: false,
  315. },
  316. outputFormat: { supportsText: true },
  317. supportsToolCall: true,
  318. supportsJsonSchemaOutput: true,
  319. supportsNativeWebSearch: false,
  320. supportsMidConversationSystem: false,
  321. }),
  322. optionSpecs: new ModelOptionSpecsConfig({
  323. maxOutputTokens: {
  324. max: 32_000,
  325. map: "{'max_tokens': maxOutputTokens}",
  326. },
  327. }),
  328. });
  329. const effective = base.overlay(
  330. new ModelConfig({
  331. properties: new ModelPropertiesConfig({
  332. requiresMfjsToolSchema: null,
  333. contextWindow: null,
  334. }),
  335. }),
  336. );
  337. expect(effective.properties?.contextWindow).toBeNull();
  338. expect(effective.validateComplete(["models", "example"])).toContainEqual({
  339. code: "required-field-missing",
  340. path: ["models", "example", "properties", "contextWindow"],
  341. message: "缺少必填配置 models.example.properties.contextWindow",
  342. });
  343. expect(effective.validateComplete(["models", "example"])).toContainEqual({
  344. code: "required-field-missing",
  345. path: ["models", "example", "properties", "requiresMfjsToolSchema"],
  346. message: "缺少必填配置 models.example.properties.requiresMfjsToolSchema",
  347. });
  348. });
  349. it("从普通 Object 解析,并拒绝未知字段", () => {
  350. const parsed = parseProviderConfigMap([
  351. {
  352. providerId: "local",
  353. config: {
  354. access: { type: "api-key", apiKey: "test-key" },
  355. api: {
  356. type: "anthropic-messages",
  357. baseUrl: "https://api.example.com",
  358. },
  359. builtinModelIds: ["model-a"],
  360. },
  361. },
  362. ]);
  363. expect(parsed.keys()).toEqual(["local"]);
  364. expect(parsed.get("local")?.api?.baseUrl).toBe("https://api.example.com");
  365. expect(() =>
  366. parseProviderConfigMap([{ providerId: "invalid", config: { unknownField: true } }]),
  367. ).toThrow();
  368. });
  369. });