tool-call-without-result.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import { Type } from "typebox";
  2. import { describe, expect, it } from "vitest";
  3. import { getModel } from "../src/models.ts";
  4. import { complete } from "../src/stream.ts";
  5. import type { Api, Context, Model, StreamOptions, Tool } from "../src/types.ts";
  6. type StreamOptionsWithExtras = StreamOptions & Record<string, unknown>;
  7. import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-utils.ts";
  8. import { hasBedrockCredentials } from "./bedrock-utils.ts";
  9. import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.ts";
  10. import { resolveApiKey } from "./oauth.ts";
  11. // Resolve OAuth tokens at module level (async, runs before tests)
  12. const oauthTokens = await Promise.all([
  13. resolveApiKey("anthropic"),
  14. resolveApiKey("github-copilot"),
  15. resolveApiKey("openai-codex"),
  16. ]);
  17. const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
  18. // Simple calculate tool
  19. const calculateSchema = Type.Object({
  20. expression: Type.String({ description: "The mathematical expression to evaluate" }),
  21. });
  22. const calculateTool: Tool = {
  23. name: "calculate",
  24. description: "Evaluate mathematical expressions",
  25. parameters: calculateSchema,
  26. };
  27. async function testToolCallWithoutResult<TApi extends Api>(model: Model<TApi>, options: StreamOptionsWithExtras = {}) {
  28. // Step 1: Create context with the calculate tool
  29. const context: Context = {
  30. systemPrompt: "You are a helpful assistant. Use the calculate tool when asked to perform calculations.",
  31. messages: [],
  32. tools: [calculateTool],
  33. };
  34. // Step 2: Ask the LLM to make a tool call
  35. context.messages.push({
  36. role: "user",
  37. content: "Please calculate 25 * 18 using the calculate tool.",
  38. timestamp: Date.now(),
  39. });
  40. // Step 3: Get the assistant's response (should contain a tool call)
  41. const firstResponse = await complete(model, context, options);
  42. context.messages.push(firstResponse);
  43. console.log("First response:", JSON.stringify(firstResponse, null, 2));
  44. // Verify the response contains a tool call
  45. const hasToolCall = firstResponse.content.some((block) => block.type === "toolCall");
  46. expect(hasToolCall).toBe(true);
  47. if (!hasToolCall) {
  48. throw new Error("Expected assistant to make a tool call, but none was found");
  49. }
  50. // Step 4: Send a user message WITHOUT providing tool result
  51. // This simulates the scenario where a tool call was aborted/cancelled
  52. context.messages.push({
  53. role: "user",
  54. content: "Never mind, just tell me what is 2+2?",
  55. timestamp: Date.now(),
  56. });
  57. // Step 5: The fix should filter out the orphaned tool call, and the request should succeed
  58. const secondResponse = await complete(model, context, options);
  59. console.log("Second response:", JSON.stringify(secondResponse, null, 2));
  60. // The request should succeed (not error) - that's the main thing we're testing
  61. expect(secondResponse.stopReason).not.toBe("error");
  62. // Should have some content in the response
  63. expect(secondResponse.content.length).toBeGreaterThan(0);
  64. // The LLM may choose to answer directly or make a new tool call - either is fine
  65. // The important thing is it didn't fail with the orphaned tool call error
  66. const textContent = secondResponse.content
  67. .filter((block) => block.type === "text")
  68. .map((block) => (block.type === "text" ? block.text : ""))
  69. .join(" ");
  70. const toolCalls = secondResponse.content.filter((block) => block.type === "toolCall").length;
  71. expect(toolCalls || textContent.length).toBeGreaterThan(0);
  72. console.log("Answer:", textContent);
  73. // Verify the stop reason is either "stop" or "toolUse" (new tool call)
  74. expect(["stop", "toolUse"]).toContain(secondResponse.stopReason);
  75. }
  76. describe("Tool Call Without Result Tests", () => {
  77. // =========================================================================
  78. // API Key-based providers
  79. // =========================================================================
  80. describe.skipIf(!process.env.GEMINI_API_KEY)("Google Provider", () => {
  81. const model = getModel("google", "gemini-2.5-flash");
  82. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  83. await testToolCallWithoutResult(model);
  84. });
  85. });
  86. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions Provider", () => {
  87. const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
  88. void _compat;
  89. const model: Model<"openai-completions"> = {
  90. ...baseModel,
  91. api: "openai-completions",
  92. };
  93. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  94. await testToolCallWithoutResult(model);
  95. });
  96. });
  97. describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Responses Provider", () => {
  98. const model = getModel("openai", "gpt-5-mini");
  99. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  100. await testToolCallWithoutResult(model);
  101. });
  102. });
  103. describe.skipIf(!hasAzureOpenAICredentials())("Azure OpenAI Responses Provider", () => {
  104. const model = getModel("azure-openai-responses", "gpt-4o-mini");
  105. const azureDeploymentName = resolveAzureDeploymentName(model.id);
  106. const azureOptions = azureDeploymentName ? { azureDeploymentName } : {};
  107. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  108. await testToolCallWithoutResult(model, azureOptions);
  109. });
  110. });
  111. describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic Provider", () => {
  112. const model = getModel("anthropic", "claude-haiku-4-5");
  113. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  114. await testToolCallWithoutResult(model);
  115. });
  116. });
  117. describe.skipIf(!process.env.XAI_API_KEY)("xAI Provider", () => {
  118. const model = getModel("xai", "grok-3-fast");
  119. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  120. await testToolCallWithoutResult(model);
  121. });
  122. });
  123. describe.skipIf(!process.env.GROQ_API_KEY)("Groq Provider", () => {
  124. const model = getModel("groq", "openai/gpt-oss-20b");
  125. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  126. await testToolCallWithoutResult(model);
  127. });
  128. });
  129. describe.skipIf(!process.env.CEREBRAS_API_KEY)("Cerebras Provider", () => {
  130. const model = getModel("cerebras", "gpt-oss-120b");
  131. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  132. await testToolCallWithoutResult(model);
  133. });
  134. });
  135. describe.skipIf(!hasCloudflareWorkersAICredentials())("Cloudflare Workers AI Provider", () => {
  136. const model = getModel("cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.6");
  137. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  138. await testToolCallWithoutResult(model);
  139. });
  140. });
  141. describe.skipIf(!hasCloudflareAiGatewayCredentials())("Cloudflare AI Gateway Provider", () => {
  142. const model = getModel("cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.6");
  143. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  144. await testToolCallWithoutResult(model);
  145. });
  146. });
  147. describe.skipIf(!process.env.HF_TOKEN)("Hugging Face Provider", () => {
  148. const model = getModel("huggingface", "moonshotai/Kimi-K2.5");
  149. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  150. await testToolCallWithoutResult(model);
  151. });
  152. });
  153. describe.skipIf(!process.env.TOGETHER_API_KEY)("Together AI Provider", () => {
  154. const model = getModel("together", "moonshotai/Kimi-K2.6");
  155. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  156. await testToolCallWithoutResult(model, { reasoningEffort: "high" });
  157. });
  158. });
  159. describe.skipIf(!process.env.ZAI_API_KEY)("zAI Provider", () => {
  160. const model = getModel("zai", "glm-4.5-air");
  161. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  162. await testToolCallWithoutResult(model);
  163. });
  164. });
  165. describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral Provider", () => {
  166. const model = getModel("mistral", "devstral-medium-latest");
  167. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  168. await testToolCallWithoutResult(model);
  169. });
  170. });
  171. describe.skipIf(!process.env.MINIMAX_API_KEY)("MiniMax Provider", () => {
  172. const model = getModel("minimax", "MiniMax-M2.7");
  173. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  174. await testToolCallWithoutResult(model);
  175. });
  176. });
  177. describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing) Provider", () => {
  178. const model = getModel("xiaomi", "mimo-v2.5-pro");
  179. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  180. await testToolCallWithoutResult(model);
  181. });
  182. });
  183. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)("Xiaomi MiMo Token Plan (CN) Provider", () => {
  184. const model = getModel("xiaomi-token-plan-cn", "mimo-v2.5-pro");
  185. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  186. await testToolCallWithoutResult(model);
  187. });
  188. });
  189. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)("Xiaomi MiMo Token Plan (AMS) Provider", () => {
  190. const model = getModel("xiaomi-token-plan-ams", "mimo-v2.5-pro");
  191. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  192. await testToolCallWithoutResult(model);
  193. });
  194. });
  195. describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)("Xiaomi MiMo Token Plan (SGP) Provider", () => {
  196. const model = getModel("xiaomi-token-plan-sgp", "mimo-v2.5-pro");
  197. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  198. await testToolCallWithoutResult(model);
  199. });
  200. });
  201. describe.skipIf(!process.env.KIMI_API_KEY)("Kimi For Coding Provider", () => {
  202. const model = getModel("kimi-coding", "kimi-k2-thinking");
  203. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  204. await testToolCallWithoutResult(model);
  205. });
  206. });
  207. describe.skipIf(!process.env.AI_GATEWAY_API_KEY)("Vercel AI Gateway Provider", () => {
  208. const model = getModel("vercel-ai-gateway", "google/gemini-2.5-flash");
  209. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  210. await testToolCallWithoutResult(model);
  211. });
  212. });
  213. describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock Provider", () => {
  214. const model = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
  215. it("should filter out tool calls without corresponding tool results", { retry: 3, timeout: 30000 }, async () => {
  216. await testToolCallWithoutResult(model);
  217. });
  218. });
  219. // =========================================================================
  220. // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
  221. // =========================================================================
  222. describe("Anthropic OAuth Provider", () => {
  223. const model = getModel("anthropic", "claude-haiku-4-5");
  224. it.skipIf(!anthropicOAuthToken)(
  225. "should filter out tool calls without corresponding tool results",
  226. { retry: 3, timeout: 30000 },
  227. async () => {
  228. await testToolCallWithoutResult(model, { apiKey: anthropicOAuthToken });
  229. },
  230. );
  231. });
  232. describe("GitHub Copilot Provider", () => {
  233. it.skipIf(!githubCopilotToken)(
  234. "claude-haiku-4.5 - should filter out tool calls without corresponding tool results",
  235. { retry: 3, timeout: 30000 },
  236. async () => {
  237. const model = getModel("github-copilot", "claude-haiku-4.5");
  238. await testToolCallWithoutResult(model, { apiKey: githubCopilotToken });
  239. },
  240. );
  241. it.skipIf(!githubCopilotToken)(
  242. "claude-sonnet-4 - should filter out tool calls without corresponding tool results",
  243. { retry: 3, timeout: 30000 },
  244. async () => {
  245. const model = getModel("github-copilot", "claude-sonnet-4.6");
  246. await testToolCallWithoutResult(model, { apiKey: githubCopilotToken });
  247. },
  248. );
  249. });
  250. describe("OpenAI Codex Provider", () => {
  251. it.skipIf(!openaiCodexToken)(
  252. "gpt-5.5 - should filter out tool calls without corresponding tool results",
  253. { retry: 3, timeout: 30000 },
  254. async () => {
  255. const model = getModel("openai-codex", "gpt-5.5");
  256. await testToolCallWithoutResult(model, { apiKey: openaiCodexToken });
  257. },
  258. );
  259. });
  260. });