openai-responses-tool-result-images.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import { readFileSync } from "node:fs";
  2. import { dirname, join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import type { ResponseFunctionCallOutputItemList } from "openai/resources/responses/responses.js";
  5. import { Type } from "typebox";
  6. import { describe, expect, it } from "vitest";
  7. import type { Api, Context, Model, StreamOptions, Tool, ToolResultMessage } from "../src/index.ts";
  8. import { complete, getModel } from "../src/index.ts";
  9. import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
  10. import { resolveApiKey } from "./oauth.ts";
  11. type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
  12. const __filename = fileURLToPath(import.meta.url);
  13. const __dirname = dirname(__filename);
  14. const oauthTokens = await Promise.all([resolveApiKey("github-copilot"), resolveApiKey("openai-codex")]);
  15. const [githubCopilotToken, openaiCodexToken] = oauthTokens;
  16. const getImageSchema = Type.Object({});
  17. const getImageTool: Tool<typeof getImageSchema> = {
  18. name: "get_circle_with_description",
  19. description: "Returns a red circle image with a short text description.",
  20. parameters: getImageSchema,
  21. };
  22. function isRecord(value: unknown): value is Record<string, unknown> {
  23. return typeof value === "object" && value !== null;
  24. }
  25. function isResponsePayload(value: unknown): value is { input: unknown[] } {
  26. return isRecord(value) && Array.isArray(value.input);
  27. }
  28. function isFunctionCallOutputItem(
  29. value: unknown,
  30. ): value is { type: "function_call_output"; output: string | ResponseFunctionCallOutputItemList } {
  31. return isRecord(value) && value.type === "function_call_output" && "output" in value;
  32. }
  33. function isInputTextItem(value: unknown): value is { type: "input_text"; text: string } {
  34. return isRecord(value) && value.type === "input_text" && typeof value.text === "string";
  35. }
  36. function isInputImageItem(value: unknown): value is { type: "input_image"; image_url: string } {
  37. return isRecord(value) && value.type === "input_image" && typeof value.image_url === "string";
  38. }
  39. async function verifyToolResultImagesStayInFunctionCallOutput<TApi extends Api>(
  40. model: Model<TApi>,
  41. options?: StreamOptionsWithExtras,
  42. ) {
  43. if (!model.input.includes("image")) {
  44. console.log(`Skipping responses tool-result image test. Model ${model.id} does not support images.`);
  45. return;
  46. }
  47. const imagePath = join(__dirname, "data", "red-circle.png");
  48. const base64Image = readFileSync(imagePath).toString("base64");
  49. const toolText = "A red circle with a diameter of 100 pixels.";
  50. const context: Context = {
  51. systemPrompt: "You are a helpful assistant that always uses the provided tool when asked.",
  52. messages: [
  53. {
  54. role: "user",
  55. content:
  56. "Call get_circle_with_description, then describe both the tool text and the image. Mention the color and shape.",
  57. timestamp: Date.now(),
  58. },
  59. ],
  60. tools: [getImageTool],
  61. };
  62. const firstResponse = await complete(model, context, options);
  63. expect(firstResponse.stopReason, `Error: ${firstResponse.errorMessage}`).toBe("toolUse");
  64. const toolCall = firstResponse.content.find((block) => block.type === "toolCall");
  65. expect(toolCall).toBeTruthy();
  66. if (!toolCall || toolCall.type !== "toolCall") {
  67. throw new Error("Expected tool call");
  68. }
  69. context.messages.push(firstResponse);
  70. context.messages.push({
  71. role: "toolResult",
  72. toolCallId: toolCall.id,
  73. toolName: toolCall.name,
  74. content: [
  75. { type: "text", text: toolText },
  76. { type: "image", data: base64Image, mimeType: "image/png" },
  77. ],
  78. isError: false,
  79. timestamp: Date.now(),
  80. } satisfies ToolResultMessage);
  81. let capturedPayload: unknown;
  82. const secondResponse = await complete(model, context, {
  83. ...options,
  84. onPayload: (payload) => {
  85. capturedPayload = payload;
  86. },
  87. });
  88. expect(secondResponse.stopReason, `Error: ${secondResponse.errorMessage}`).toBe("stop");
  89. expect(secondResponse.errorMessage).toBeFalsy();
  90. expect(isResponsePayload(capturedPayload)).toBe(true);
  91. if (!isResponsePayload(capturedPayload)) {
  92. throw new Error("Expected payload with input array");
  93. }
  94. const functionCallOutputIndex = capturedPayload.input.findIndex((item) => isFunctionCallOutputItem(item));
  95. expect(functionCallOutputIndex).toBeGreaterThanOrEqual(0);
  96. const functionCallOutput = capturedPayload.input[functionCallOutputIndex];
  97. if (!isFunctionCallOutputItem(functionCallOutput)) {
  98. throw new Error("Expected function_call_output item");
  99. }
  100. expect(Array.isArray(functionCallOutput.output)).toBe(true);
  101. if (!Array.isArray(functionCallOutput.output)) {
  102. throw new Error("Expected function_call_output output to be a content array");
  103. }
  104. const outputItems = functionCallOutput.output;
  105. const textItem = outputItems.find((item) => isInputTextItem(item));
  106. const imageItem = outputItems.find((item) => isInputImageItem(item));
  107. expect(textItem).toBeTruthy();
  108. expect(imageItem).toBeTruthy();
  109. if (!textItem || !imageItem) {
  110. throw new Error("Expected both input_text and input_image in function_call_output");
  111. }
  112. expect(textItem.text).toContain(toolText);
  113. expect(imageItem.image_url.startsWith("data:image/png;base64,")).toBe(true);
  114. const laterUserMessages = capturedPayload.input
  115. .slice(functionCallOutputIndex + 1)
  116. .filter((item) => isRecord(item) && item.role === "user");
  117. expect(laterUserMessages).toHaveLength(0);
  118. const responseText = secondResponse.content
  119. .filter((block) => block.type === "text")
  120. .map((block) => block.text)
  121. .join(" ")
  122. .toLowerCase();
  123. expect(responseText).toContain("red");
  124. expect(responseText).toContain("circle");
  125. }
  126. describe("Responses API tool result images", () => {
  127. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Responses Provider (gpt-5-mini)", () => {
  128. const model = getModel("openai", "gpt-5-mini");
  129. it("should send tool result images in function_call_output", { retry: 3, timeout: 30000 }, async () => {
  130. await verifyToolResultImagesStayInFunctionCallOutput(model, { reasoningEffort: "low" });
  131. });
  132. });
  133. describe.skipIf(!hasAzureOpenAICredentials())("Azure OpenAI Responses Provider (gpt-4o-mini)", () => {
  134. const model = getModel("azure-openai-responses", "gpt-4o-mini");
  135. const azureDeploymentName = resolveAzureDeploymentName(model.id);
  136. const azureOptions = azureDeploymentName ? { azureDeploymentName } : {};
  137. it("should send tool result images in function_call_output", { retry: 3, timeout: 30000 }, async () => {
  138. await verifyToolResultImagesStayInFunctionCallOutput(model, azureOptions);
  139. });
  140. });
  141. describe("GitHub Copilot Responses Provider (gpt-5-mini)", () => {
  142. const model = getModel("github-copilot", "gpt-5-mini");
  143. it.skipIf(!githubCopilotToken)(
  144. "should send tool result images in function_call_output",
  145. { retry: 3, timeout: 30000 },
  146. async () => {
  147. await verifyToolResultImagesStayInFunctionCallOutput(model, {
  148. apiKey: githubCopilotToken,
  149. reasoningEffort: "low",
  150. });
  151. },
  152. );
  153. });
  154. describe("OpenAI Codex Responses Provider (gpt-5.5)", () => {
  155. const model = getModel("openai-codex", "gpt-5.5");
  156. it.skipIf(!openaiCodexToken)(
  157. "should send tool result images in function_call_output",
  158. { retry: 3, timeout: 30000 },
  159. async () => {
  160. await verifyToolResultImagesStayInFunctionCallOutput(model, {
  161. apiKey: openaiCodexToken,
  162. reasoningEffort: "low",
  163. });
  164. },
  165. );
  166. });
  167. });