model-tool-error-transform.test.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { createAnthropic } from "@ai-sdk/anthropic";
  2. import { generateText } from "ai";
  3. import { describe, expect, it } from "vitest";
  4. import { toAiSdkMessages } from "../src/model/index.js";
  5. describe("AI SDK model tool result error transform", () => {
  6. it("maps provider-neutral failed tool results to AI SDK error output", () => {
  7. const toolCallId = "call_failed_tool";
  8. const messages = toAiSdkMessages([
  9. {
  10. role: "tool",
  11. content: "Command was aborted before completion",
  12. isError: true,
  13. toolCallId,
  14. toolName: "Bash",
  15. },
  16. ]);
  17. expect((messages[0] as any).content[0]).toEqual({
  18. type: "tool-result",
  19. toolCallId,
  20. toolName: "Bash",
  21. output: {
  22. type: "error-text",
  23. value: "Command was aborted before completion",
  24. },
  25. });
  26. });
  27. it("serializes failed tool results as Anthropic is_error tool_result blocks", async () => {
  28. let requestBody: any;
  29. const provider = createAnthropic({
  30. apiKey: "fake-key",
  31. baseURL: "https://api.example.test",
  32. fetch: async (_input, init) => {
  33. requestBody = JSON.parse(String(init?.body));
  34. return new Response(
  35. JSON.stringify({ error: { message: "wire capture", type: "invalid_request_error" } }),
  36. {
  37. headers: { "content-type": "application/json" },
  38. status: 400,
  39. },
  40. );
  41. },
  42. });
  43. const toolCallId = "call_malformed_ask";
  44. const validationContent = [
  45. "<tool_use_error>InputValidationError: AskUserQuestion failed due to the following issue:",
  46. "The required parameter `questions` is missing</tool_use_error>",
  47. ].join("\n");
  48. const messages = toAiSdkMessages([
  49. {
  50. role: "assistant",
  51. content: "",
  52. toolCalls: [
  53. {
  54. id: toolCallId,
  55. input: {},
  56. name: "AskUserQuestion",
  57. },
  58. ],
  59. },
  60. {
  61. role: "tool",
  62. content: validationContent,
  63. isError: true,
  64. toolCallId,
  65. toolName: "AskUserQuestion",
  66. },
  67. ]);
  68. await expect(
  69. generateText({
  70. messages,
  71. model: provider("anthropic-model"),
  72. }),
  73. ).rejects.toBeDefined();
  74. expect(requestBody.messages).toEqual([
  75. {
  76. role: "assistant",
  77. content: [
  78. {
  79. id: toolCallId,
  80. input: {},
  81. name: "AskUserQuestion",
  82. type: "tool_use",
  83. },
  84. ],
  85. },
  86. {
  87. role: "user",
  88. content: [
  89. {
  90. content: validationContent,
  91. is_error: true,
  92. tool_use_id: toolCallId,
  93. type: "tool_result",
  94. },
  95. ],
  96. },
  97. ]);
  98. });
  99. });