openai-responses-encrypted-reasoning-wire.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import { readFile } from "node:fs/promises";
  2. import { afterEach, describe, expect, it, vi } from "vitest";
  3. import {
  4. createModelId,
  5. createModelProviderId,
  6. type ModelEvent,
  7. type ModelInputMessage,
  8. } from "@zcode/contracts";
  9. import {
  10. createRegistryModelConfig,
  11. createRegistryProviderConfig,
  12. parseModelConfig,
  13. parseProviderConfig,
  14. parseZCodeBuiltinModelConfigRules,
  15. } from "@zcode/provider";
  16. import { AiSdkModelAdapter } from "../src/model/runner.js";
  17. // gpt-6.1-terra 不在 AI SDK 的推理模型名单里,SDK 不会自动补 include;用它证明 include 由 zcode 显式发送。
  18. const MODEL_ID = "gpt-6.1-terra";
  19. const PROVIDER_ID = "fixture";
  20. const BASE_URL = "https://gateway.example.com/v1";
  21. const ENCRYPTED = "opaque-encrypted-reasoning";
  22. const ENCRYPTED_INCLUDE = "reasoning.encrypted_content";
  23. const READ_TOOL = {
  24. name: "Read",
  25. inputSchema: {
  26. type: "object",
  27. properties: { path: { type: "string" } },
  28. required: ["path"],
  29. additionalProperties: false,
  30. },
  31. } as const;
  32. // 上游标准错误包含结构化错误码;部分兼容网关仅返回密文过期文案。
  33. const INVALID_ENCRYPTED_CONTENT_BODY = {
  34. error: {
  35. message: "The encrypted content for item rs_1 could not be verified.",
  36. type: "invalid_request_error",
  37. param: null,
  38. code: "invalid_encrypted_content",
  39. },
  40. };
  41. const EXPIRED_ENCRYPTED_CONTENT_BODY = {
  42. error: {
  43. message: "reasoning `encrypted_content` has expired",
  44. type: "invalid_request_error",
  45. param: null,
  46. code: null,
  47. },
  48. };
  49. afterEach(() => {
  50. vi.unstubAllGlobals();
  51. });
  52. describe("OpenAI Responses 加密推理回传", () => {
  53. it("请求带 store:false 和 include,流式 reasoning 保留密文", async () => {
  54. const bodies = stubFetch(() => sseResponse(reasoningAndToolCallFrames()));
  55. const model = await createModel();
  56. const events: ModelEvent[] = [];
  57. for await (const event of model.streamText({
  58. messages: [{ role: "user", content: "hi" }],
  59. tools: [READ_TOOL],
  60. })) {
  61. events.push(event);
  62. }
  63. expect(bodies[0]).toMatchObject({ store: false, include: [ENCRYPTED_INCLUDE] });
  64. const ends = events.filter((event) => event.type === "reasoning_end");
  65. // 第一段摘要在第二段开始时结束,不带密文;密文只出现在 output_item.done 结束的最后一段。
  66. expect(ends.map((event) => event.providerMetadata)).toEqual([
  67. { openai: { itemId: "rs_1" } },
  68. { openai: { itemId: "rs_1", reasoningEncryptedContent: ENCRYPTED } },
  69. ]);
  70. });
  71. it("没有摘要的 reasoning 也保留密文,下一轮原样带回", async () => {
  72. // zcode 不请求 reasoning.summary,真实流里常见的就是这种形态:没有摘要正文,只有密文。
  73. const bodies = stubFetchSequence([
  74. () => sseResponse(reasoningAndToolCallFrames([])),
  75. () => jsonResponse(),
  76. ]);
  77. const model = await createModel();
  78. const events: ModelEvent[] = [];
  79. for await (const event of model.streamText({
  80. messages: [{ role: "user", content: "hi" }],
  81. tools: [READ_TOOL],
  82. })) {
  83. events.push(event);
  84. }
  85. const ends = events.filter((event) => event.type === "reasoning_end");
  86. expect(ends.map((event) => event.providerMetadata)).toEqual([
  87. { openai: { itemId: "rs_1", reasoningEncryptedContent: ENCRYPTED } },
  88. ]);
  89. // core 用 reasoning_end 的元数据写块:正文为空,元数据带密文。
  90. await model.generateText({
  91. messages: [
  92. { role: "user", content: "hi" },
  93. {
  94. role: "assistant",
  95. providerId: createModelProviderId(PROVIDER_ID),
  96. modelId: createModelId(MODEL_ID),
  97. content: [{ type: "reasoning", text: "", providerOptions: ends[0]?.providerMetadata }],
  98. toolCalls: [{ id: "call_1", name: "Read", input: { path: "README.md" } }],
  99. },
  100. { role: "tool", toolCallId: "call_1", toolName: "Read", content: "ok" },
  101. ],
  102. });
  103. expect(reasoningItems(bodies[1])).toEqual([
  104. { type: "reasoning", id: "rs_1", encrypted_content: ENCRYPTED, summary: [] },
  105. ]);
  106. });
  107. it("下一轮按 itemId 带回密文,丢弃没有密文的旧 reasoning", async () => {
  108. const bodies = stubFetch(() => jsonResponse());
  109. const model = await createModel();
  110. await model.generateText({ messages: history(PROVIDER_ID, MODEL_ID) });
  111. const input = bodies[0]?.input as Array<Record<string, unknown>>;
  112. expect(input.filter((item) => item.type === "item_reference")).toEqual([]);
  113. expect(input.filter((item) => item.type === "reasoning")).toEqual([
  114. {
  115. type: "reasoning",
  116. id: "rs_1",
  117. encrypted_content: ENCRYPTED,
  118. summary: [
  119. { type: "summary_text", text: "first summary" },
  120. { type: "summary_text", text: "second summary" },
  121. ],
  122. },
  123. ]);
  124. });
  125. it.each([
  126. ["模型", PROVIDER_ID, "gpt-5.4"],
  127. ["Provider", "other-provider", MODEL_ID],
  128. ])("切换%s后不带回其他来源的密文", async (_name, providerId, modelId) => {
  129. const bodies = stubFetch(() => jsonResponse());
  130. const model = await createModel();
  131. await model.generateText({ messages: history(providerId, modelId) });
  132. const input = bodies[0]?.input as Array<Record<string, unknown>>;
  133. expect(input.filter((item) => item.type === "reasoning")).toEqual([]);
  134. expect(input.some((item) => item.type === "function_call")).toBe(true);
  135. });
  136. it("后面没有输出项的 reasoning 不带回", async () => {
  137. const bodies = stubFetch(() => jsonResponse());
  138. const model = await createModel();
  139. const identity = {
  140. providerId: createModelProviderId(PROVIDER_ID),
  141. modelId: createModelId(MODEL_ID),
  142. };
  143. const encrypted = (itemId: string, text: string) => ({
  144. type: "reasoning" as const,
  145. text,
  146. providerOptions: { openai: { itemId, reasoningEncryptedContent: `enc_${itemId}` } },
  147. });
  148. await model.generateText({
  149. messages: [
  150. { role: "user", content: "first" },
  151. // 输出 token 在推理阶段用完:续写保留的 partial 只有 reasoning。
  152. { role: "assistant", ...identity, content: [encrypted("rs_only", "cut off")] },
  153. { role: "user", content: "Continue" },
  154. // 推理完成后停止:末尾的 reasoning 后面没有输出项,前面的保留。
  155. {
  156. role: "assistant",
  157. ...identity,
  158. content: [
  159. encrypted("rs_kept", "kept"),
  160. { type: "text", text: "partial answer" },
  161. encrypted("rs_tail", "stopped"),
  162. ],
  163. },
  164. { role: "user", content: "next" },
  165. ],
  166. });
  167. expect(reasoningItems(bodies[0]).map((item) => item.id)).toEqual(["rs_kept"]);
  168. });
  169. it("Option Map 不写 reasoning 的模型只发 store:false,不发 include", async () => {
  170. const bodies = stubFetch(() => jsonResponse());
  171. // 非推理模型只有在映射不写 reasoning 时才能工作;这时带 include 会被上游 400。
  172. const model = await createModel({ reasoningMap: "{}" });
  173. await model.generateText({ messages: [{ role: "user", content: "hi" }] });
  174. expect(bodies[0]).toMatchObject({ store: false });
  175. expect(bodies[0]).not.toHaveProperty("include");
  176. expect(bodies[0]).not.toHaveProperty("reasoning");
  177. });
  178. it.each([
  179. ["结构化错误码", INVALID_ENCRYPTED_CONTENT_BODY],
  180. ["没有错误码的过期文案", EXPIRED_ENCRYPTED_CONTENT_BODY],
  181. ])("generate 遇到密文被拒(%s)时去掉密文重试一次并报告重置", async (_name, errorBody) => {
  182. const bodies = stubFetchSequence([
  183. () => Response.json(errorBody, { status: 400 }),
  184. () => jsonResponse(),
  185. ]);
  186. const model = await createModel();
  187. const result = await model.generateText({ messages: history(PROVIDER_ID, MODEL_ID) });
  188. expect(bodies).toHaveLength(2);
  189. expect(reasoningItems(bodies[0])).toHaveLength(1);
  190. expect(reasoningItems(bodies[1])).toEqual([]);
  191. expect(inputItems(bodies[1]).some((item) => item.type === "function_call")).toBe(true);
  192. expect(result.signedReasoningReset).toBe(true);
  193. });
  194. it.each([
  195. ["结构化错误码", INVALID_ENCRYPTED_CONTENT_BODY],
  196. ["没有错误码的过期文案", EXPIRED_ENCRYPTED_CONTENT_BODY],
  197. ])("stream 遇到密文被拒(%s)时去掉密文重试一次,finish 报告重置", async (_name, errorBody) => {
  198. const bodies = stubFetchSequence([
  199. () => Response.json(errorBody, { status: 400 }),
  200. () => sseResponse(textFrames()),
  201. ]);
  202. const model = await createModel();
  203. const events: ModelEvent[] = [];
  204. for await (const event of model.streamText({ messages: history(PROVIDER_ID, MODEL_ID) })) {
  205. events.push(event);
  206. }
  207. expect(bodies).toHaveLength(2);
  208. expect(reasoningItems(bodies[0])).toHaveLength(1);
  209. expect(reasoningItems(bodies[1])).toEqual([]);
  210. expect(events.find((event) => event.type === "finish")).toMatchObject({
  211. signedReasoningReset: true,
  212. });
  213. });
  214. it("其他 400 不触发密文修复重试", async () => {
  215. const bodies = stubFetchSequence([
  216. () =>
  217. Response.json(
  218. {
  219. error: {
  220. message: "Invalid value for 'input'.",
  221. type: "invalid_request_error",
  222. param: "input",
  223. code: "invalid_value",
  224. },
  225. },
  226. { status: 400 },
  227. ),
  228. () => jsonResponse(),
  229. ]);
  230. const model = await createModel();
  231. await expect(
  232. model.generateText({ messages: history(PROVIDER_ID, MODEL_ID) }),
  233. ).rejects.toThrow();
  234. expect(bodies).toHaveLength(1);
  235. });
  236. it("修复标记之前的密文不再发送,标记及之后的保留", async () => {
  237. const bodies = stubFetch(() => jsonResponse());
  238. const model = await createModel();
  239. const earlier = history(PROVIDER_ID, MODEL_ID);
  240. const marked: ModelInputMessage = {
  241. role: "assistant",
  242. providerId: createModelProviderId(PROVIDER_ID),
  243. modelId: createModelId(MODEL_ID),
  244. signedReasoningReset: true,
  245. content: [
  246. {
  247. type: "reasoning",
  248. text: "after repair",
  249. providerOptions: { openai: { itemId: "rs_2", reasoningEncryptedContent: "fresh" } },
  250. },
  251. ],
  252. toolCalls: [{ id: "call_2", name: "Read", input: { path: "b.md" } }],
  253. };
  254. await model.generateText({
  255. messages: [
  256. ...earlier,
  257. marked,
  258. { role: "tool", toolCallId: "call_2", toolName: "Read", content: "ok" },
  259. ],
  260. });
  261. expect(reasoningItems(bodies[0])).toEqual([
  262. {
  263. type: "reasoning",
  264. id: "rs_2",
  265. encrypted_content: "fresh",
  266. summary: [{ type: "summary_text", text: "after repair" }],
  267. },
  268. ]);
  269. });
  270. });
  271. async function createModel(options: { reasoningMap?: string } = {}) {
  272. const release = JSON.parse(
  273. await readFile(
  274. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  275. "utf8",
  276. ),
  277. );
  278. const resolved = parseZCodeBuiltinModelConfigRules(release.config.modelConfigRules).resolve({
  279. providerId: PROVIDER_ID,
  280. templateId: "openai",
  281. modelId: MODEL_ID,
  282. apiType: "openai-responses",
  283. baseUrl: BASE_URL,
  284. });
  285. // 用个人覆盖的方式改映射,和用户给非推理模型改配置的路径一致。
  286. const config =
  287. options.reasoningMap === undefined
  288. ? resolved
  289. : resolved.overlay(
  290. parseModelConfig({ optionSpecs: { reasoningLevel: { map: options.reasoningMap } } }),
  291. );
  292. const modelConfig = createRegistryModelConfig(config);
  293. const providerConfig = createRegistryProviderConfig(
  294. parseProviderConfig({
  295. group: "standard-personal",
  296. access: { type: "api-key", apiKey: "fixture" },
  297. api: { type: "openai-responses", baseUrl: BASE_URL },
  298. }),
  299. );
  300. if (!modelConfig.ok || !providerConfig.ok) throw new Error("incomplete fixture");
  301. return new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } }).createModel({
  302. providerId: createModelProviderId(PROVIDER_ID),
  303. modelId: createModelId(MODEL_ID),
  304. providerConfig: providerConfig.config,
  305. modelConfig: modelConfig.config,
  306. options: { maxOutputTokens: 4000, reasoningLevel: "high" },
  307. });
  308. }
  309. function history(providerId: string, modelId: string): ModelInputMessage[] {
  310. return [
  311. { role: "user", content: "read the file" },
  312. {
  313. role: "assistant",
  314. providerId: createModelProviderId(providerId),
  315. modelId: createModelId(modelId),
  316. content: [
  317. // 本改动之前写入的历史:有 itemId,没有密文。
  318. {
  319. type: "reasoning",
  320. text: "legacy summary",
  321. providerOptions: { openai: { itemId: "rs_0", reasoningEncryptedContent: null } },
  322. },
  323. {
  324. type: "reasoning",
  325. text: "first summary",
  326. providerOptions: { openai: { itemId: "rs_1" } },
  327. },
  328. {
  329. type: "reasoning",
  330. text: "second summary",
  331. providerOptions: { openai: { itemId: "rs_1", reasoningEncryptedContent: ENCRYPTED } },
  332. },
  333. ],
  334. toolCalls: [{ id: "call_1", name: "Read", input: { path: "README.md" } }],
  335. },
  336. { role: "tool", toolCallId: "call_1", toolName: "Read", content: "ok" },
  337. ];
  338. }
  339. function stubFetch(create: () => Response): Array<Record<string, unknown>> {
  340. const bodies: Array<Record<string, unknown>> = [];
  341. vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
  342. bodies.push(await new Request(url, init).json());
  343. return create();
  344. });
  345. return bodies;
  346. }
  347. function stubFetchSequence(responses: Array<() => Response>): Array<Record<string, unknown>> {
  348. const bodies: Array<Record<string, unknown>> = [];
  349. vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
  350. bodies.push(await new Request(url, init).json());
  351. const create = responses[bodies.length - 1];
  352. if (!create) throw new Error(`unexpected request #${bodies.length}`);
  353. return create();
  354. });
  355. return bodies;
  356. }
  357. function inputItems(body: Record<string, unknown> | undefined): Array<Record<string, unknown>> {
  358. return (body?.input ?? []) as Array<Record<string, unknown>>;
  359. }
  360. function reasoningItems(body: Record<string, unknown> | undefined): Array<Record<string, unknown>> {
  361. return inputItems(body).filter((item) => item.type === "reasoning");
  362. }
  363. function jsonResponse(): Response {
  364. return Response.json({
  365. id: "resp_2",
  366. object: "response",
  367. created_at: 1,
  368. status: "completed",
  369. model: MODEL_ID,
  370. output: [
  371. {
  372. id: "msg_2",
  373. type: "message",
  374. role: "assistant",
  375. status: "completed",
  376. content: [{ type: "output_text", text: "done", annotations: [] }],
  377. },
  378. ],
  379. usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
  380. });
  381. }
  382. function reasoningAndToolCallFrames(
  383. summaries = ["first summary", "second summary"],
  384. ): Array<Record<string, unknown>> {
  385. return [
  386. { type: "response.created", response: { id: "resp_1", created_at: 1, model: MODEL_ID } },
  387. {
  388. type: "response.output_item.added",
  389. output_index: 0,
  390. item: { type: "reasoning", id: "rs_1", encrypted_content: null },
  391. },
  392. ...summaries.flatMap((delta, summary_index) => [
  393. { type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index },
  394. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index, delta },
  395. { type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index },
  396. ]),
  397. {
  398. type: "response.output_item.done",
  399. output_index: 0,
  400. item: { type: "reasoning", id: "rs_1", encrypted_content: ENCRYPTED },
  401. },
  402. {
  403. type: "response.output_item.added",
  404. output_index: 1,
  405. item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "Read", arguments: "" },
  406. },
  407. {
  408. type: "response.function_call_arguments.delta",
  409. item_id: "fc_1",
  410. output_index: 1,
  411. delta: '{"path":"README.md"}',
  412. },
  413. {
  414. type: "response.output_item.done",
  415. output_index: 1,
  416. item: {
  417. type: "function_call",
  418. id: "fc_1",
  419. call_id: "call_1",
  420. name: "Read",
  421. arguments: '{"path":"README.md"}',
  422. status: "completed",
  423. },
  424. },
  425. {
  426. type: "response.completed",
  427. response: { usage: { input_tokens: 1, output_tokens: 1 } },
  428. },
  429. ];
  430. }
  431. function textFrames(): Array<Record<string, unknown>> {
  432. return [
  433. { type: "response.created", response: { id: "resp_3", created_at: 1, model: MODEL_ID } },
  434. { type: "response.output_item.added", output_index: 0, item: { type: "message", id: "msg_3" } },
  435. { type: "response.output_text.delta", item_id: "msg_3", delta: "done" },
  436. { type: "response.output_item.done", output_index: 0, item: { type: "message", id: "msg_3" } },
  437. { type: "response.completed", response: { usage: { input_tokens: 1, output_tokens: 1 } } },
  438. ];
  439. }
  440. function sseResponse(frames: Array<Record<string, unknown>>): Response {
  441. const body = frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join("");
  442. return new Response(body, { headers: { "content-type": "text/event-stream" } });
  443. }