image-tool-result.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import { readFileSync } from "node:fs";
  2. import { join } from "node:path";
  3. import { Type } from "typebox";
  4. import { describe, expect, it } from "vitest";
  5. import type { Api, Context, Model, Tool, ToolResultMessage } from "../src/index.ts";
  6. import { complete, getModel } from "../src/index.ts";
  7. import type { StreamOptions } from "../src/types.ts";
  8. type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
  9. import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
  10. import { hasBedrockCredentials } from "./bedrock-utils.ts";
  11. import { resolveApiKey } from "./oauth.ts";
  12. // Resolve OAuth tokens at module level (async, runs before tests)
  13. const oauthTokens = await Promise.all([
  14. resolveApiKey("anthropic"),
  15. resolveApiKey("github-copilot"),
  16. resolveApiKey("openai-codex"),
  17. ]);
  18. const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
  19. /**
  20. * Test that tool results containing only images work correctly across all providers.
  21. * This verifies that:
  22. * 1. Tool results can contain image content blocks
  23. * 2. Providers correctly pass images from tool results to the LLM
  24. * 3. The LLM can see and describe images returned by tools
  25. */
  26. async function handleToolWithImageResult<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
  27. // Check if the model supports images
  28. if (!model.input.includes("image")) {
  29. console.log(`Skipping tool image result test - model ${model.id} doesn't support images`);
  30. return;
  31. }
  32. // Read the test image
  33. const imagePath = join(__dirname, "data", "red-circle.png");
  34. const imageBuffer = readFileSync(imagePath);
  35. const base64Image = imageBuffer.toString("base64");
  36. // Define a tool that returns only an image (no text)
  37. const getImageSchema = Type.Object({});
  38. const getImageTool: Tool<typeof getImageSchema> = {
  39. name: "get_circle",
  40. description: "Returns a circle image for visualization",
  41. parameters: getImageSchema,
  42. };
  43. const context: Context = {
  44. systemPrompt: "You are a helpful assistant that uses tools when asked.",
  45. messages: [
  46. {
  47. role: "user",
  48. content: "Call the get_circle tool to get an image, and describe what you see, shapes, colors, etc.",
  49. timestamp: Date.now(),
  50. },
  51. ],
  52. tools: [getImageTool],
  53. };
  54. // First request - LLM should call the tool
  55. const firstResponse = await complete(model, context, options);
  56. expect(firstResponse.stopReason).toBe("toolUse");
  57. // Find the tool call
  58. const toolCall = firstResponse.content.find((b) => b.type === "toolCall");
  59. expect(toolCall).toBeTruthy();
  60. if (!toolCall || toolCall.type !== "toolCall") {
  61. throw new Error("Expected tool call");
  62. }
  63. expect(toolCall.name).toBe("get_circle");
  64. // Add the tool call to context
  65. context.messages.push(firstResponse);
  66. // Create tool result with ONLY an image (no text)
  67. const toolResult: ToolResultMessage = {
  68. role: "toolResult",
  69. toolCallId: toolCall.id,
  70. toolName: toolCall.name,
  71. content: [
  72. {
  73. type: "image",
  74. data: base64Image,
  75. mimeType: "image/png",
  76. },
  77. ],
  78. isError: false,
  79. timestamp: Date.now(),
  80. };
  81. context.messages.push(toolResult);
  82. // Second request - LLM should describe the image from the tool result
  83. const secondResponse = await complete(model, context, options);
  84. expect(secondResponse.stopReason).toBe("stop");
  85. expect(secondResponse.errorMessage).toBeFalsy();
  86. // Verify the LLM can see and describe the image
  87. const textContent = secondResponse.content.find((b) => b.type === "text");
  88. expect(textContent).toBeTruthy();
  89. if (textContent && textContent.type === "text") {
  90. const lowerContent = textContent.text.toLowerCase();
  91. // Should mention red and circle since that's what the image shows
  92. expect(lowerContent).toContain("red");
  93. expect(lowerContent).toContain("circle");
  94. }
  95. }
  96. /**
  97. * Test that tool results containing both text and images work correctly across all providers.
  98. * This verifies that:
  99. * 1. Tool results can contain mixed content blocks (text + images)
  100. * 2. Providers correctly pass both text and images from tool results to the LLM
  101. * 3. The LLM can see both the text and images in tool results
  102. */
  103. async function handleToolWithTextAndImageResult<TApi extends Api>(
  104. model: Model<TApi>,
  105. options?: StreamOptionsWithExtras,
  106. ) {
  107. // Check if the model supports images
  108. if (!model.input.includes("image")) {
  109. console.log(`Skipping tool text+image result test - model ${model.id} doesn't support images`);
  110. return;
  111. }
  112. // Read the test image
  113. const imagePath = join(__dirname, "data", "red-circle.png");
  114. const imageBuffer = readFileSync(imagePath);
  115. const base64Image = imageBuffer.toString("base64");
  116. // Define a tool that returns both text and an image
  117. const getImageSchema = Type.Object({});
  118. const getImageTool: Tool<typeof getImageSchema> = {
  119. name: "get_circle_with_description",
  120. description: "Returns a circle image with a text description",
  121. parameters: getImageSchema,
  122. };
  123. const context: Context = {
  124. systemPrompt: "You are a helpful assistant that uses tools when asked.",
  125. messages: [
  126. {
  127. role: "user",
  128. content:
  129. "Use the get_circle_with_description tool and tell me what you learned. Also say what color the shape is.",
  130. timestamp: Date.now(),
  131. },
  132. ],
  133. tools: [getImageTool],
  134. };
  135. // First request - LLM should call the tool
  136. const firstResponse = await complete(model, context, options);
  137. expect(firstResponse.stopReason).toBe("toolUse");
  138. // Find the tool call
  139. const toolCall = firstResponse.content.find((b) => b.type === "toolCall");
  140. expect(toolCall).toBeTruthy();
  141. if (!toolCall || toolCall.type !== "toolCall") {
  142. throw new Error("Expected tool call");
  143. }
  144. expect(toolCall.name).toBe("get_circle_with_description");
  145. // Add the tool call to context
  146. context.messages.push(firstResponse);
  147. // Create tool result with BOTH text and image
  148. const toolResult: ToolResultMessage = {
  149. role: "toolResult",
  150. toolCallId: toolCall.id,
  151. toolName: toolCall.name,
  152. content: [
  153. {
  154. type: "text",
  155. text: "This is a geometric shape with specific properties: it has a diameter of 100 pixels.",
  156. },
  157. {
  158. type: "image",
  159. data: base64Image,
  160. mimeType: "image/png",
  161. },
  162. ],
  163. isError: false,
  164. timestamp: Date.now(),
  165. };
  166. context.messages.push(toolResult);
  167. // Second request - LLM should describe both the text and image from the tool result
  168. const secondResponse = await complete(model, context, options);
  169. expect(secondResponse.stopReason).toBe("stop");
  170. expect(secondResponse.errorMessage).toBeFalsy();
  171. // Verify the LLM can see both text and image
  172. const textContent = secondResponse.content.find((b) => b.type === "text");
  173. expect(textContent).toBeTruthy();
  174. if (textContent && textContent.type === "text") {
  175. const lowerContent = textContent.text.toLowerCase();
  176. // Should mention details from the text (diameter/pixels)
  177. expect(lowerContent.match(/diameter|100|pixel/)).toBeTruthy();
  178. // Should also mention the visual properties (red and circle)
  179. expect(lowerContent).toContain("red");
  180. expect(lowerContent).toContain("circle");
  181. }
  182. }
  183. describe("Tool Results with Images", () => {
  184. describe.skipIf(!process.env.GEMINI_API_KEY)("Google Provider (gemini-2.5-flash)", () => {
  185. const llm = getModel("google", "gemini-2.5-flash");
  186. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  187. await handleToolWithImageResult(llm);
  188. });
  189. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  190. await handleToolWithTextAndImageResult(llm);
  191. });
  192. });
  193. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions Provider (gpt-4o-mini)", () => {
  194. const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini");
  195. void _compat;
  196. const llm: Model<"openai-completions"> = {
  197. ...baseModel,
  198. api: "openai-completions",
  199. };
  200. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  201. await handleToolWithImageResult(llm);
  202. });
  203. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  204. await handleToolWithTextAndImageResult(llm);
  205. });
  206. });
  207. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Responses Provider (gpt-5-mini)", () => {
  208. const llm = getModel("openai", "gpt-5-mini");
  209. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  210. await handleToolWithImageResult(llm);
  211. });
  212. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  213. await handleToolWithTextAndImageResult(llm);
  214. });
  215. });
  216. describe.skipIf(!hasAzureOpenAICredentials())("Azure OpenAI Responses Provider (gpt-4o-mini)", () => {
  217. const llm = getModel("azure-openai-responses", "gpt-4o-mini");
  218. const azureDeploymentName = resolveAzureDeploymentName(llm.id);
  219. const azureOptions = azureDeploymentName ? { azureDeploymentName } : {};
  220. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  221. await handleToolWithImageResult(llm, azureOptions);
  222. });
  223. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  224. await handleToolWithTextAndImageResult(llm, azureOptions);
  225. });
  226. });
  227. describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic Provider (claude-haiku-4-5)", () => {
  228. const model = getModel("anthropic", "claude-haiku-4-5");
  229. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  230. await handleToolWithImageResult(model);
  231. });
  232. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  233. await handleToolWithTextAndImageResult(model);
  234. });
  235. });
  236. describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter Provider (glm-4.5v)", () => {
  237. const llm = getModel("openrouter", "z-ai/glm-4.5v");
  238. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  239. await handleToolWithImageResult(llm);
  240. });
  241. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  242. await handleToolWithTextAndImageResult(llm);
  243. });
  244. });
  245. describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral Provider (pixtral-12b)", () => {
  246. const llm = getModel("mistral", "pixtral-12b");
  247. it("should handle tool result with only image", { retry: 5, timeout: 30000 }, async () => {
  248. await handleToolWithImageResult(llm);
  249. });
  250. it("should handle tool result with text and image", { retry: 5, timeout: 30000 }, async () => {
  251. await handleToolWithTextAndImageResult(llm);
  252. });
  253. });
  254. describe.skipIf(!process.env.TOGETHER_API_KEY)("Together AI Provider (Kimi-K2.6)", () => {
  255. const llm = getModel("together", "moonshotai/Kimi-K2.6");
  256. const options = { reasoningEffort: "high" } satisfies StreamOptionsWithExtras;
  257. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  258. await handleToolWithImageResult(llm, options);
  259. });
  260. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  261. await handleToolWithTextAndImageResult(llm, options);
  262. });
  263. });
  264. describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing) Provider (mimo-v2.5-pro)", () => {
  265. const llm = getModel("xiaomi", "mimo-v2.5-pro");
  266. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  267. await handleToolWithImageResult(llm);
  268. });
  269. // FIXME(xiaomi): when a tool_result contains both a descriptive text block
  270. // and an image block, MiMo locks onto the text and ignores the image (it
  271. // reports the text-derived diameter but never mentions the image's color).
  272. // The image-only case above proves the image reaches the model, and the
  273. // text-only path obviously works, so this is a multimodal-fusion quality
  274. // issue in the model, not a transport bug. Re-enable when upstream model
  275. // quality improves.
  276. it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  277. await handleToolWithTextAndImageResult(llm);
  278. });
  279. });
  280. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)(
  281. "Xiaomi MiMo Token Plan (CN) Provider (mimo-v2.5-pro)",
  282. () => {
  283. const llm = getModel("xiaomi-token-plan-cn", "mimo-v2.5-pro");
  284. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  285. await handleToolWithImageResult(llm);
  286. });
  287. // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
  288. // limitation applies to Token Plan endpoints (same model behind both).
  289. it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  290. await handleToolWithTextAndImageResult(llm);
  291. });
  292. },
  293. );
  294. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)(
  295. "Xiaomi MiMo Token Plan (AMS) Provider (mimo-v2.5-pro)",
  296. () => {
  297. const llm = getModel("xiaomi-token-plan-ams", "mimo-v2.5-pro");
  298. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  299. await handleToolWithImageResult(llm);
  300. });
  301. // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
  302. // limitation applies to Token Plan endpoints (same model behind both).
  303. it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  304. await handleToolWithTextAndImageResult(llm);
  305. });
  306. },
  307. );
  308. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)(
  309. "Xiaomi MiMo Token Plan (SGP) Provider (mimo-v2.5-pro)",
  310. () => {
  311. const llm = getModel("xiaomi-token-plan-sgp", "mimo-v2.5-pro");
  312. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  313. await handleToolWithImageResult(llm);
  314. });
  315. // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
  316. // limitation applies to Token Plan endpoints (same model behind both).
  317. it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  318. await handleToolWithTextAndImageResult(llm);
  319. });
  320. },
  321. );
  322. describe.skipIf(!process.env.KIMI_API_KEY)("Kimi For Coding Provider (kimi-for-coding)", () => {
  323. const llm = getModel("kimi-coding", "kimi-for-coding");
  324. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  325. await handleToolWithImageResult(llm);
  326. });
  327. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  328. await handleToolWithTextAndImageResult(llm);
  329. });
  330. });
  331. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)("Vercel AI Gateway Provider (google/gemini-2.5-flash)", () => {
  332. const llm = getModel("vercel-ai-gateway", "google/gemini-2.5-flash");
  333. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  334. await handleToolWithImageResult(llm);
  335. });
  336. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  337. await handleToolWithTextAndImageResult(llm);
  338. });
  339. });
  340. describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock Provider (claude-sonnet-4-5)", () => {
  341. const llm = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  342. it("should handle tool result with only image", { retry: 3, timeout: 30000 }, async () => {
  343. await handleToolWithImageResult(llm);
  344. });
  345. it("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
  346. await handleToolWithTextAndImageResult(llm);
  347. });
  348. });
  349. // =========================================================================
  350. // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
  351. // =========================================================================
  352. describe("Anthropic OAuth Provider (claude-sonnet-4-5)", () => {
  353. const model = getModel("anthropic", "claude-sonnet-4-5");
  354. it.skipIf(!anthropicOAuthToken)(
  355. "should handle tool result with only image",
  356. { retry: 3, timeout: 30000 },
  357. async () => {
  358. await handleToolWithImageResult(model, { apiKey: anthropicOAuthToken });
  359. },
  360. );
  361. it.skipIf(!anthropicOAuthToken)(
  362. "should handle tool result with text and image",
  363. { retry: 3, timeout: 30000 },
  364. async () => {
  365. await handleToolWithTextAndImageResult(model, { apiKey: anthropicOAuthToken });
  366. },
  367. );
  368. });
  369. describe("GitHub Copilot Provider", () => {
  370. it.skipIf(!githubCopilotToken)(
  371. "claude-haiku-4.5 - should handle tool result with only image",
  372. { retry: 3, timeout: 30000 },
  373. async () => {
  374. const llm = getModel("github-copilot", "claude-haiku-4.5");
  375. await handleToolWithImageResult(llm, { apiKey: githubCopilotToken });
  376. },
  377. );
  378. it.skipIf(!githubCopilotToken)(
  379. "claude-haiku-4.5 - should handle tool result with text and image",
  380. { retry: 3, timeout: 30000 },
  381. async () => {
  382. const llm = getModel("github-copilot", "claude-haiku-4.5");
  383. await handleToolWithTextAndImageResult(llm, { apiKey: githubCopilotToken });
  384. },
  385. );
  386. it.skipIf(!githubCopilotToken)(
  387. "claude-sonnet-4 - should handle tool result with only image",
  388. { retry: 3, timeout: 30000 },
  389. async () => {
  390. const llm = getModel("github-copilot", "claude-sonnet-4.6");
  391. await handleToolWithImageResult(llm, { apiKey: githubCopilotToken });
  392. },
  393. );
  394. it.skipIf(!githubCopilotToken)(
  395. "claude-sonnet-4 - should handle tool result with text and image",
  396. { retry: 3, timeout: 30000 },
  397. async () => {
  398. const llm = getModel("github-copilot", "claude-sonnet-4.6");
  399. await handleToolWithTextAndImageResult(llm, { apiKey: githubCopilotToken });
  400. },
  401. );
  402. });
  403. describe("OpenAI Codex Provider", () => {
  404. it.skipIf(!openaiCodexToken)(
  405. "gpt-5.5 - should handle tool result with only image",
  406. { retry: 3, timeout: 30000 },
  407. async () => {
  408. const llm = getModel("openai-codex", "gpt-5.5");
  409. await handleToolWithImageResult(llm, { apiKey: openaiCodexToken });
  410. },
  411. );
  412. it.skipIf(!openaiCodexToken)(
  413. "gpt-5.5 - should handle tool result with text and image",
  414. { retry: 3, timeout: 30000 },
  415. async () => {
  416. const llm = getModel("openai-codex", "gpt-5.5");
  417. await handleToolWithTextAndImageResult(llm, { apiKey: openaiCodexToken });
  418. },
  419. );
  420. });
  421. });