empty-tool-name-projection.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import { createAnthropic } from "@ai-sdk/anthropic";
  2. import { createOpenAI } from "@ai-sdk/openai";
  3. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  4. import { ModelErrorCode } from "@zcode/contracts";
  5. import { generateText } from "ai";
  6. import { describe, expect, it } from "vitest";
  7. import { AiSdkModelAdapterError } from "../src/model/errors.js";
  8. import { toAiSdkMessages } from "../src/model/index.js";
  9. const TOOL_CALL_ID = "call_empty_name";
  10. const MODEL_CONTENT = "<tool_use_error>Error: No such tool available: </tool_use_error>";
  11. describe("empty tool name provider projection", () => {
  12. it("gives explicit apiFormat precedence over provider kind", () => {
  13. const messages = emptyToolMessages();
  14. const anthropic = toAiSdkMessages(messages, {
  15. apiFormat: "anthropic-messages",
  16. providerKind: "openai-compatible",
  17. });
  18. const chatCompletions = toAiSdkMessages(messages, {
  19. apiFormat: "openai-chat-completions",
  20. providerKind: "anthropic",
  21. });
  22. expect((anthropic[0] as any).content[0].toolName).toBe("");
  23. expect((anthropic[1] as any).content[0].toolName).toBe("");
  24. expect((chatCompletions[0] as any).content[0].toolName).toBe("empty_tool_name");
  25. expect((chatCompletions[1] as any).content[0].toolName).toBe("empty_tool_name");
  26. });
  27. it("reads apiFormat from provider options when the direct format is absent", () => {
  28. const messages = toAiSdkMessages(emptyToolMessages(), {
  29. providerKind: "openai-compatible",
  30. providerOptions: { apiFormat: "anthropic-messages" },
  31. });
  32. expect((messages[0] as any).content[0].toolName).toBe("");
  33. expect((messages[1] as any).content[0].toolName).toBe("");
  34. });
  35. it("falls back only to provider kind and does not infer the format from a URL", () => {
  36. const anthropic = toAiSdkMessages(emptyToolMessages(), {
  37. providerKind: "anthropic",
  38. providerOptions: { baseURL: "https://api.openai.example/v1" },
  39. });
  40. const openAiCompatible = toAiSdkMessages(emptyToolMessages(), {
  41. providerKind: "openai-compatible",
  42. providerOptions: { baseURL: "https://api.anthropic.example/v1/messages" },
  43. });
  44. expect((anthropic[0] as any).content[0].toolName).toBe("");
  45. expect((anthropic[1] as any).content[0].toolName).toBe("");
  46. expect((openAiCompatible[0] as any).content[0].toolName).toBe("empty_tool_name");
  47. expect((openAiCompatible[1] as any).content[0].toolName).toBe("empty_tool_name");
  48. });
  49. it.each([{ toolCallId: undefined, toolName: "Read" }])(
  50. "keeps rejecting incomplete tool-result identity %#",
  51. ({ toolCallId, toolName }) => {
  52. expect(() =>
  53. toAiSdkMessages([
  54. {
  55. role: "tool",
  56. content: MODEL_CONTENT,
  57. isError: true,
  58. toolCallId,
  59. toolName,
  60. } as never,
  61. ]),
  62. ).toThrow("Tool model messages require toolCallId and toolName");
  63. },
  64. );
  65. it.each([undefined, null, 42, { invalid: true }])(
  66. "rejects non-string tool name %j at both projection call sites",
  67. (toolName) => {
  68. const invalidMessages = [
  69. [
  70. {
  71. role: "assistant",
  72. content: "",
  73. toolCalls: [{ id: TOOL_CALL_ID, input: {}, name: toolName }],
  74. },
  75. ],
  76. [
  77. {
  78. role: "tool",
  79. content: MODEL_CONTENT,
  80. isError: true,
  81. toolCallId: TOOL_CALL_ID,
  82. toolName,
  83. },
  84. ],
  85. ];
  86. for (const messages of invalidMessages) {
  87. let error: unknown;
  88. try {
  89. toAiSdkMessages(messages as never);
  90. } catch (caught) {
  91. error = caught;
  92. }
  93. expect(error).toBeInstanceOf(AiSdkModelAdapterError);
  94. expect(error).toMatchObject({
  95. code: ModelErrorCode.InvalidModelRequest,
  96. message: "Tool model messages require toolCallId and toolName",
  97. });
  98. }
  99. },
  100. );
  101. it("keeps the raw empty name on Anthropic wire", async () => {
  102. let requestBody: any;
  103. const provider = createAnthropic({
  104. apiKey: "fake-key",
  105. baseURL: "https://api.example.test",
  106. fetch: captureRejectedRequest((body) => {
  107. requestBody = body;
  108. }),
  109. });
  110. const messages = toAiSdkMessages(emptyToolMessages(), {
  111. apiFormat: "anthropic-messages",
  112. providerKind: "anthropic",
  113. });
  114. await expect(
  115. generateText({ maxRetries: 0, messages, model: provider("anthropic-model") }),
  116. ).rejects.toBeDefined();
  117. expect(requestBody.messages).toEqual([
  118. {
  119. role: "assistant",
  120. content: [{ id: TOOL_CALL_ID, input: {}, name: "", type: "tool_use" }],
  121. },
  122. {
  123. role: "user",
  124. content: [
  125. {
  126. content: MODEL_CONTENT,
  127. is_error: true,
  128. tool_use_id: TOOL_CALL_ID,
  129. type: "tool_result",
  130. },
  131. ],
  132. },
  133. ]);
  134. });
  135. it("uses the placeholder only for Chat Completions assistant function name", async () => {
  136. let requestBody: any;
  137. const provider = createOpenAICompatible({
  138. apiKey: "fake-key",
  139. baseURL: "https://api.example.test/v1",
  140. name: "empty-name-chat",
  141. fetch: captureRejectedRequest((body) => {
  142. requestBody = body;
  143. }),
  144. });
  145. const messages = toAiSdkMessages(emptyToolMessages(), {
  146. apiFormat: "openai-chat-completions",
  147. providerKind: "openai-compatible",
  148. });
  149. await expect(
  150. generateText({ maxRetries: 0, messages, model: provider("chat-model") }),
  151. ).rejects.toBeDefined();
  152. const assistant = requestBody.messages.find((message: any) => message.role === "assistant");
  153. const toolResult = requestBody.messages.find((message: any) => message.role === "tool");
  154. expect(assistant.tool_calls[0]).toMatchObject({
  155. function: { arguments: "{}", name: "empty_tool_name" },
  156. id: TOOL_CALL_ID,
  157. type: "function",
  158. });
  159. expect(toolResult).toMatchObject({
  160. content: MODEL_CONTENT,
  161. role: "tool",
  162. tool_call_id: TOOL_CALL_ID,
  163. });
  164. expect(toolResult).not.toHaveProperty("name");
  165. });
  166. it("uses the placeholder only for Responses function_call name", async () => {
  167. let requestBody: any;
  168. const provider = createOpenAI({
  169. apiKey: "fake-key",
  170. baseURL: "https://api.example.test/v1",
  171. fetch: captureRejectedRequest((body) => {
  172. requestBody = body;
  173. }),
  174. });
  175. const messages = toAiSdkMessages(emptyToolMessages(), {
  176. apiFormat: "openai-responses",
  177. providerKind: "openai",
  178. });
  179. await expect(
  180. generateText({ maxRetries: 0, messages, model: provider.responses("responses-model") }),
  181. ).rejects.toBeDefined();
  182. const functionCall = requestBody.input.find((item: any) => item.type === "function_call");
  183. const functionOutput = requestBody.input.find(
  184. (item: any) => item.type === "function_call_output",
  185. );
  186. expect(functionCall).toMatchObject({
  187. arguments: "{}",
  188. call_id: TOOL_CALL_ID,
  189. name: "empty_tool_name",
  190. type: "function_call",
  191. });
  192. expect(functionOutput).toMatchObject({
  193. call_id: TOOL_CALL_ID,
  194. output: MODEL_CONTENT,
  195. type: "function_call_output",
  196. });
  197. expect(functionOutput).not.toHaveProperty("name");
  198. });
  199. });
  200. function emptyToolMessages() {
  201. return [
  202. {
  203. role: "assistant" as const,
  204. content: "",
  205. toolCalls: [{ id: TOOL_CALL_ID, input: {}, name: "" }],
  206. },
  207. {
  208. role: "tool" as const,
  209. content: MODEL_CONTENT,
  210. isError: true,
  211. toolCallId: TOOL_CALL_ID,
  212. toolName: "",
  213. },
  214. ];
  215. }
  216. function captureRejectedRequest(
  217. capture: (body: Record<string, unknown>) => void,
  218. ): typeof globalThis.fetch {
  219. return async (_input, init) => {
  220. capture(JSON.parse(String(init?.body)) as Record<string, unknown>);
  221. return new Response(
  222. JSON.stringify({ error: { message: "wire capture", type: "invalid_request_error" } }),
  223. {
  224. headers: { "content-type": "application/json" },
  225. status: 400,
  226. },
  227. );
  228. };
  229. }