openai-responses-reasoning-replay-e2e.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { Type } from "typebox";
  2. import { describe, expect, it } from "vitest";
  3. import { getModel } from "../src/models.ts";
  4. import { complete, getEnvApiKey } from "../src/stream.ts";
  5. import type { AssistantMessage, Context, Message, Tool, ToolCall } from "../src/types.ts";
  6. const testToolSchema = Type.Object({
  7. value: Type.Number({ description: "A number to double" }),
  8. });
  9. const testTool: Tool<typeof testToolSchema> = {
  10. name: "double_number",
  11. description: "Doubles a number and returns the result",
  12. parameters: testToolSchema,
  13. };
  14. describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
  15. "OpenAI Responses reasoning replay e2e",
  16. () => {
  17. it("skips reasoning-only history after an aborted turn", { retry: 2 }, async () => {
  18. const model = getModel("openai", "gpt-5-mini");
  19. const apiKey = getEnvApiKey("openai");
  20. if (!apiKey) {
  21. throw new Error("Missing OPENAI_API_KEY");
  22. }
  23. const userMessage: Message = {
  24. role: "user",
  25. content: "Use the double_number tool to double 21.",
  26. timestamp: Date.now(),
  27. };
  28. const assistantResponse = await complete(
  29. model,
  30. {
  31. systemPrompt: "You are a helpful assistant. Use the tool.",
  32. messages: [userMessage],
  33. tools: [testTool],
  34. },
  35. {
  36. apiKey,
  37. reasoningEffort: "high",
  38. },
  39. );
  40. const thinkingBlock = assistantResponse.content.find(
  41. (block) => block.type === "thinking" && block.thinkingSignature,
  42. );
  43. if (!thinkingBlock || thinkingBlock.type !== "thinking") {
  44. throw new Error("Missing thinking signature from OpenAI Responses");
  45. }
  46. const corruptedAssistant: AssistantMessage = {
  47. ...assistantResponse,
  48. content: [thinkingBlock],
  49. stopReason: "aborted",
  50. };
  51. const followUp: Message = {
  52. role: "user",
  53. content: "Say hello to confirm you can continue.",
  54. timestamp: Date.now(),
  55. };
  56. const context: Context = {
  57. systemPrompt: "You are a helpful assistant.",
  58. messages: [userMessage, corruptedAssistant, followUp],
  59. tools: [testTool],
  60. };
  61. const response = await complete(model, context, {
  62. apiKey,
  63. reasoningEffort: "high",
  64. });
  65. // The key assertion: no 400 error from orphaned reasoning item
  66. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  67. expect(response.errorMessage).toBeFalsy();
  68. // Model should respond (text or tool call)
  69. expect(response.content.length).toBeGreaterThan(0);
  70. });
  71. it("handles same-provider different-model handoff with tool calls", { retry: 2 }, async () => {
  72. // This tests the scenario where:
  73. // 1. Model A (gpt-5-mini) generates reasoning + function_call
  74. // 2. User switches to Model B (gpt-5.2-codex) - same provider, different model
  75. // 3. transform-messages: isSameModel=false, thinking converted to text
  76. // 4. But tool call ID still has OpenAI pairing history (fc_xxx paired with rs_xxx)
  77. // 5. Without fix: OpenAI returns 400 "function_call without required reasoning item"
  78. // 6. With fix: tool calls/results converted to text, conversation continues
  79. const modelA = getModel("openai", "gpt-5-mini");
  80. const modelB = getModel("openai", "gpt-5.2-codex");
  81. const apiKey = getEnvApiKey("openai");
  82. if (!apiKey) {
  83. throw new Error("Missing OPENAI_API_KEY");
  84. }
  85. const userMessage: Message = {
  86. role: "user",
  87. content: "Use the double_number tool to double 21.",
  88. timestamp: Date.now(),
  89. };
  90. // Get a real response from Model A with reasoning + tool call
  91. const assistantResponse = await complete(
  92. modelA,
  93. {
  94. systemPrompt: "You are a helpful assistant. Always use the tool when asked.",
  95. messages: [userMessage],
  96. tools: [testTool],
  97. },
  98. {
  99. apiKey,
  100. reasoningEffort: "high",
  101. },
  102. );
  103. const toolCallBlock = assistantResponse.content.find((block) => block.type === "toolCall") as
  104. | ToolCall
  105. | undefined;
  106. if (!toolCallBlock) {
  107. throw new Error("Missing tool call from OpenAI Responses - model did not use the tool");
  108. }
  109. // Provide a tool result
  110. const toolResult: Message = {
  111. role: "toolResult",
  112. toolCallId: toolCallBlock.id,
  113. toolName: toolCallBlock.name,
  114. content: [{ type: "text", text: "42" }],
  115. isError: false,
  116. timestamp: Date.now(),
  117. };
  118. const followUp: Message = {
  119. role: "user",
  120. content: "What was the result? Answer with just the number.",
  121. timestamp: Date.now(),
  122. };
  123. // Now continue with Model B (different model, same provider)
  124. const context: Context = {
  125. systemPrompt: "You are a helpful assistant. Answer concisely.",
  126. messages: [userMessage, assistantResponse, toolResult, followUp],
  127. tools: [testTool],
  128. };
  129. let capturedPayload: any = null;
  130. const response = await complete(modelB, context, {
  131. apiKey,
  132. reasoningEffort: "high",
  133. onPayload: (payload) => {
  134. capturedPayload = payload;
  135. },
  136. });
  137. // The key assertion: no 400 error from orphaned function_call
  138. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  139. expect(response.errorMessage).toBeFalsy();
  140. expect(response.content.length).toBeGreaterThan(0);
  141. // Log what was sent for debugging
  142. const input = capturedPayload?.input as any[];
  143. const functionCalls = input?.filter((item: any) => item.type === "function_call") || [];
  144. const reasoningItems = input?.filter((item: any) => item.type === "reasoning") || [];
  145. console.log("Payload sent to API:");
  146. console.log("- function_calls:", functionCalls.length);
  147. console.log("- reasoning items:", reasoningItems.length);
  148. console.log("- full input:", JSON.stringify(input, null, 2));
  149. // Verify the model understood the context
  150. const responseText = response.content
  151. .filter((b) => b.type === "text")
  152. .map((b) => (b as any).text)
  153. .join("");
  154. expect(responseText).toContain("42");
  155. });
  156. it("handles cross-provider handoff from Anthropic to OpenAI Codex", { retry: 2 }, async () => {
  157. // This tests cross-provider handoff:
  158. // 1. Anthropic model generates thinking + function_call (toolu_xxx ID)
  159. // 2. User switches to OpenAI Codex
  160. // 3. transform-messages: isSameModel=false, thinking converted to text
  161. // 4. Tool call ID is Anthropic format (toolu_xxx), no OpenAI pairing history
  162. // 5. Should work because foreign IDs have no pairing expectation
  163. const anthropicModel = getModel("anthropic", "claude-sonnet-4-5");
  164. const codexModel = getModel("openai", "gpt-5.2-codex");
  165. const anthropicApiKey = getEnvApiKey("anthropic");
  166. const openaiApiKey = getEnvApiKey("openai");
  167. if (!anthropicApiKey || !openaiApiKey) {
  168. throw new Error("Missing API keys");
  169. }
  170. const userMessage: Message = {
  171. role: "user",
  172. content: "Use the double_number tool to double 21.",
  173. timestamp: Date.now(),
  174. };
  175. // Get a real response from Anthropic with thinking + tool call
  176. const assistantResponse = await complete(
  177. anthropicModel,
  178. {
  179. systemPrompt: "You are a helpful assistant. Always use the tool when asked.",
  180. messages: [userMessage],
  181. tools: [testTool],
  182. },
  183. {
  184. apiKey: anthropicApiKey,
  185. thinkingEnabled: true,
  186. thinkingBudgetTokens: 5000,
  187. },
  188. );
  189. const toolCallBlock = assistantResponse.content.find((block) => block.type === "toolCall") as
  190. | ToolCall
  191. | undefined;
  192. if (!toolCallBlock) {
  193. throw new Error("Missing tool call from Anthropic - model did not use the tool");
  194. }
  195. console.log("Anthropic tool call ID:", toolCallBlock.id);
  196. // Provide a tool result
  197. const toolResult: Message = {
  198. role: "toolResult",
  199. toolCallId: toolCallBlock.id,
  200. toolName: toolCallBlock.name,
  201. content: [{ type: "text", text: "42" }],
  202. isError: false,
  203. timestamp: Date.now(),
  204. };
  205. const followUp: Message = {
  206. role: "user",
  207. content: "What was the result? Answer with just the number.",
  208. timestamp: Date.now(),
  209. };
  210. // Now continue with Codex (different provider)
  211. const context: Context = {
  212. systemPrompt: "You are a helpful assistant. Answer concisely.",
  213. messages: [userMessage, assistantResponse, toolResult, followUp],
  214. tools: [testTool],
  215. };
  216. let capturedPayload: any = null;
  217. const response = await complete(codexModel, context, {
  218. apiKey: openaiApiKey,
  219. reasoningEffort: "high",
  220. onPayload: (payload) => {
  221. capturedPayload = payload;
  222. },
  223. });
  224. // Log what was sent
  225. const input = capturedPayload?.input as any[];
  226. const functionCalls = input?.filter((item: any) => item.type === "function_call") || [];
  227. const reasoningItems = input?.filter((item: any) => item.type === "reasoning") || [];
  228. console.log("Payload sent to Codex:");
  229. console.log("- function_calls:", functionCalls.length);
  230. console.log("- reasoning items:", reasoningItems.length);
  231. if (functionCalls.length > 0) {
  232. console.log(
  233. "- function_call IDs:",
  234. functionCalls.map((fc: any) => fc.id),
  235. );
  236. }
  237. // The key assertion: no 400 error
  238. expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
  239. expect(response.errorMessage).toBeFalsy();
  240. expect(response.content.length).toBeGreaterThan(0);
  241. // Verify the model understood the context
  242. const responseText = response.content
  243. .filter((b) => b.type === "text")
  244. .map((b) => (b as any).text)
  245. .join("");
  246. expect(responseText).toContain("42");
  247. });
  248. },
  249. );