new-model-round2-wire.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import { readFile } from "node:fs/promises";
  2. import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
  3. import type { ModelMessageContentBlock } from "@zcode/contracts";
  4. import {
  5. createRegistryModelConfig,
  6. createRegistryProviderConfig,
  7. parseProviderConfig,
  8. parseZCodeBuiltinModelConfigRules,
  9. } from "@zcode/provider";
  10. import { AiSdkModelAdapter } from "../src/model/runner.js";
  11. import { AiSdkModelExecution } from "../src/model/model-execution.js";
  12. type Api = "anthropic-messages" | "openai-chat-completions" | "openai-responses";
  13. let rules: ReturnType<typeof parseZCodeBuiltinModelConfigRules>;
  14. beforeAll(async () => {
  15. const release = JSON.parse(
  16. await readFile(
  17. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  18. "utf8",
  19. ),
  20. );
  21. rules = parseZCodeBuiltinModelConfigRules(release.config.modelConfigRules);
  22. });
  23. afterEach(() => vi.unstubAllGlobals());
  24. const image: ModelMessageContentBlock = {
  25. type: "image",
  26. mediaType: "image/png",
  27. dataUrl: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB",
  28. };
  29. const video: ModelMessageContentBlock = {
  30. type: "video",
  31. mediaType: "video/mp4",
  32. dataUrl: "data:video/mp4;base64,ZmFrZQ==",
  33. };
  34. async function capture(
  35. modelId: string,
  36. apiType: Api,
  37. baseUrl: string,
  38. reasoningLevel: string,
  39. media: ModelMessageContentBlock[] = [],
  40. schema = false,
  41. ) {
  42. const config = createRegistryModelConfig(
  43. rules.resolve({ providerId: "fixture", modelId, apiType, baseUrl }),
  44. );
  45. const provider = createRegistryProviderConfig(
  46. parseProviderConfig({
  47. group: "standard-personal",
  48. access: { type: "api-key", apiKey: "fixture" },
  49. api: { type: apiType, baseUrl },
  50. }),
  51. );
  52. if (!config.ok || !provider.ok) throw new Error("incomplete fixture");
  53. let body: Record<string, unknown> | undefined;
  54. vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
  55. body = await new Request(url, init).json();
  56. const text = schema ? '{"ok":true}' : "ok";
  57. if (apiType === "anthropic-messages")
  58. return Response.json({
  59. id: "fixture",
  60. type: "message",
  61. role: "assistant",
  62. model: modelId,
  63. content: [{ type: "text", text }],
  64. stop_reason: "end_turn",
  65. stop_sequence: null,
  66. usage: { input_tokens: 1, output_tokens: 1 },
  67. });
  68. if (apiType === "openai-chat-completions")
  69. return Response.json({
  70. id: "fixture",
  71. object: "chat.completion",
  72. created: 1,
  73. model: modelId,
  74. choices: [
  75. { index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" },
  76. ],
  77. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  78. });
  79. return Response.json({
  80. id: "resp_fixture",
  81. object: "response",
  82. created_at: 1,
  83. status: "completed",
  84. model: modelId,
  85. output: [
  86. {
  87. id: "msg_fixture",
  88. type: "message",
  89. role: "assistant",
  90. status: "completed",
  91. content: [{ type: "output_text", text, annotations: [] }],
  92. },
  93. ],
  94. usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
  95. });
  96. });
  97. const adapter = new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } });
  98. const model = adapter.createModel({
  99. providerId: "fixture",
  100. modelId,
  101. modelConfig: config.config,
  102. providerConfig: provider.config,
  103. options: { reasoningLevel, maxOutputTokens: 4096 },
  104. });
  105. await model.generateText({
  106. messages: [{ role: "user", content: [{ type: "text", text: "hi" }, ...media] }],
  107. tools: [
  108. {
  109. name: "Read",
  110. inputSchema: {
  111. type: "object",
  112. properties: { path: { type: "string" } },
  113. required: ["path"],
  114. additionalProperties: false,
  115. },
  116. },
  117. ],
  118. ...(schema
  119. ? {
  120. responseJsonSchema: {
  121. type: "object",
  122. properties: { ok: { type: "boolean" } },
  123. required: ["ok"],
  124. additionalProperties: false,
  125. },
  126. }
  127. : {}),
  128. });
  129. expect(body?.model).toBe(modelId);
  130. expect(body?.tools).toEqual(
  131. expect.arrayContaining([
  132. expect.objectContaining(
  133. apiType === "openai-chat-completions" ? { type: "function" } : { name: "Read" },
  134. ),
  135. ]),
  136. );
  137. expect(
  138. body?.[
  139. apiType === "openai-responses"
  140. ? "max_output_tokens"
  141. : apiType === "anthropic-messages"
  142. ? "max_tokens"
  143. : "max_completion_tokens"
  144. ],
  145. ).toBe(4096);
  146. if (media.some((m) => m.type === "image")) expect(JSON.stringify(body)).toContain("iVBORw0KGgo");
  147. if (media.some((m) => m.type === "video")) expect(JSON.stringify(body)).toContain("ZmFrZQ==");
  148. return body!;
  149. }
  150. describe("Todo113 第二轮真实 SDK 序列化,不请求付费模型", () => {
  151. it("Schema 能力在 binding 时冻结,后续配置不能改变已创建 Model", () => {
  152. const p = createRegistryProviderConfig(
  153. parseProviderConfig({
  154. group: "standard-personal",
  155. access: { type: "api-key", apiKey: "fixture" },
  156. api: { type: "openai-chat-completions", baseUrl: "https://fixture.invalid/v1" },
  157. }),
  158. );
  159. if (!p.ok) throw new Error("invalid fixture");
  160. const execution = new AiSdkModelExecution({});
  161. const input = {
  162. providerId: "fixture",
  163. modelId: "gpt-5.4",
  164. providerConfig: p.config,
  165. supportsJsonSchemaOutput: true,
  166. optionSpecs: { reasoningLevel: { map: "{}" }, maxOutputTokens: { map: "{}" } },
  167. };
  168. const old = execution.bindModel(input);
  169. input.supportsJsonSchemaOutput = false;
  170. const fresh = execution.bindModel(input);
  171. expect(old.resolved.model).toHaveProperty("supportsStructuredOutputs", true);
  172. expect(
  173. old.resolveRequest({ options: { reasoningLevel: "none", maxOutputTokens: 100 } }).model,
  174. ).toHaveProperty("supportsStructuredOutputs", true);
  175. expect(fresh.resolved.model).toHaveProperty("supportsStructuredOutputs", false);
  176. });
  177. for (const id of ["gpt-5.4", "gpt-5.4-pro", "gpt-5.4-mini", "gpt-5.4-nano"]) {
  178. for (const level of id.endsWith("-pro") ? ["medium", "xhigh"] : ["none", "xhigh"]) {
  179. it(`${id}/${level} 原厂 Responses 图片/Schema/工具`, async () => {
  180. expect(
  181. await capture(id, "openai-responses", "https://api.openai.com/v1", level, [image], true),
  182. ).toMatchObject({
  183. reasoning: { effort: level },
  184. text: { format: { type: "json_schema" } },
  185. });
  186. });
  187. it(`${id}/${level} OpenRouter Messages`, async () => {
  188. const body = await capture(
  189. `openai/${id}`,
  190. "anthropic-messages",
  191. "https://openrouter.ai/api",
  192. level,
  193. [image],
  194. );
  195. expect(body).toMatchObject(
  196. level === "none"
  197. ? { thinking: { type: "disabled" } }
  198. : { output_config: { effort: level } },
  199. );
  200. if (level !== "none") expect(body).not.toHaveProperty("thinking");
  201. });
  202. }
  203. }
  204. for (const id of [
  205. "qwen3.7-max",
  206. "qwen3.7-plus",
  207. "qwen3.7-flash",
  208. "qwen3.6-plus",
  209. "qwen3.6-flash",
  210. ]) {
  211. for (const api of [
  212. "anthropic-messages",
  213. "openai-chat-completions",
  214. "openai-responses",
  215. ] as const) {
  216. for (const level of ["disabled", "enabled"])
  217. it(`${id}/${api}/${level}`, async () => {
  218. const url =
  219. api === "anthropic-messages"
  220. ? "https://dashscope.aliyuncs.com/apps/anthropic"
  221. : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
  222. const body = await capture(id, api, url, level, id.endsWith("-max") ? [] : [image]);
  223. expect(body).toMatchObject(
  224. api === "anthropic-messages"
  225. ? { thinking: { type: level } }
  226. : api === "openai-responses"
  227. ? { reasoning: { effort: level === "disabled" ? "none" : "high" } }
  228. : { enable_thinking: level === "enabled" },
  229. );
  230. if (api === "openai-chat-completions") expect(body).not.toHaveProperty("thinking");
  231. });
  232. }
  233. }
  234. it.each(["none", "max"])("Omni Chat %s / 图片 / 视频", async (level) => {
  235. expect(
  236. await capture(
  237. "qwen3.8-omni-flash",
  238. "openai-chat-completions",
  239. "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
  240. level,
  241. [image, video],
  242. ),
  243. ).toMatchObject({ reasoning_effort: level });
  244. });
  245. it("Omni Chat 音频输入保留为音频而不是文本占位", async () => {
  246. const body = await capture(
  247. "qwen3.8-omni-flash",
  248. "openai-chat-completions",
  249. "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
  250. "low",
  251. [
  252. {
  253. type: "file",
  254. mediaType: "audio/wav",
  255. dataUrl: "data:audio/wav;base64,UklGRg==",
  256. name: "fixture.wav",
  257. },
  258. ],
  259. );
  260. expect(JSON.stringify(body)).toContain('"input_audio"');
  261. expect(JSON.stringify(body)).toContain("UklGRg==");
  262. });
  263. it.each(["anthropic-messages", "openai-chat-completions"] as const)(
  264. "Kimi 高速版 %s 共用 Code 请求",
  265. async (api) => {
  266. expect(
  267. await capture(
  268. "kimi-k2.7-code-highspeed",
  269. api,
  270. api === "anthropic-messages"
  271. ? "https://api.moonshot.cn/anthropic"
  272. : "https://api.moonshot.cn/v1",
  273. "enabled",
  274. [image, video],
  275. ),
  276. ).toMatchObject({ thinking: { type: "enabled" } });
  277. },
  278. );
  279. it.each(["disabled", "max"])(
  280. "OpenRouter V4.1 Flash Chat %s,统一 reasoning 与 Schema",
  281. async (level) => {
  282. expect(
  283. await capture(
  284. "deepseek/deepseek-v4.1-flash",
  285. "openai-chat-completions",
  286. "https://openrouter.ai/api/v1",
  287. level,
  288. [image],
  289. true,
  290. ),
  291. ).toMatchObject({
  292. reasoning: level === "disabled" ? { enabled: false } : { effort: "max" },
  293. response_format: { type: "json_schema" },
  294. });
  295. },
  296. );
  297. it.each(["qwen3.6-plus", "qwen3.6-flash"])("OpenRouter %s 的 Schema 是网关能力", async (id) => {
  298. const body = await capture(
  299. `qwen/${id}`,
  300. "openai-chat-completions",
  301. "https://openrouter.ai/api/v1",
  302. "enabled",
  303. [image],
  304. true,
  305. );
  306. expect(body).toMatchObject({
  307. reasoning: { enabled: true },
  308. response_format: { type: "json_schema" },
  309. });
  310. expect(body).not.toHaveProperty("enable_thinking");
  311. });
  312. it.each(["minimal", "xhigh"])("OpenRouter Qwen3.8 快照 %s 映射", async (level) => {
  313. const body = await capture(
  314. "qwen/qwen3.8-max-0902",
  315. "anthropic-messages",
  316. "https://openrouter.ai/api",
  317. level,
  318. [image],
  319. );
  320. expect(body).toMatchObject({ output_config: { effort: level } });
  321. });
  322. });
  323. describe("Todo138 通用两档的真实 SDK 请求体", () => {
  324. for (const api of [
  325. "anthropic-messages",
  326. "openai-chat-completions",
  327. "openai-responses",
  328. ] as const) {
  329. for (const level of ["disabled", "enabled"]) {
  330. it(`${api}/${level} 不把 enabled 直接传成 effort`, async () => {
  331. const body = await capture(
  332. "future-unknown-model",
  333. api,
  334. "https://fixture.invalid/v1",
  335. level,
  336. );
  337. const effort = level === "disabled" ? "none" : "high";
  338. if (api === "anthropic-messages") {
  339. expect(body.thinking).toEqual({ type: level === "disabled" ? "disabled" : "adaptive" });
  340. if (level === "disabled") expect(body).not.toHaveProperty("output_config");
  341. else expect(body.output_config).toEqual({ effort: "high" });
  342. } else {
  343. expect(body.reasoning).toEqual({ effort });
  344. if (api === "openai-chat-completions") {
  345. expect(body.reasoning_effort).toBe(effort);
  346. expect(body.thinking).toEqual({ type: level === "disabled" ? "disabled" : "enabled" });
  347. expect(body.enable_thinking).toBe(level !== "disabled");
  348. }
  349. }
  350. });
  351. }
  352. }
  353. });