tool-result-cache-wire.test.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { createAnthropic } from "@ai-sdk/anthropic";
  2. import { generateText } from "ai";
  3. import { describe, expect, it } from "vitest";
  4. import type { ModelInputMessage } from "@zcode/contracts";
  5. import { toAiSdkMessages } from "../src/model/index.js";
  6. const cases = [
  7. { count: 1, cachedIndex: 0, failed: false },
  8. { count: 2, cachedIndex: 1, failed: false },
  9. { count: 2, cachedIndex: 1, failed: true },
  10. { count: 2, cachedIndex: 0, failed: false },
  11. { count: 3, cachedIndex: 1, failed: true },
  12. { count: 3, cachedIndex: 2, failed: false },
  13. ];
  14. describe("tool result cache breakpoint on final provider wire", () => {
  15. it.each(cases)(
  16. "preserves $count result(s), marker $cachedIndex, failed=$failed",
  17. async ({ count, cachedIndex, failed }) => {
  18. const cache = { type: "ephemeral" as const, ttl: "1h" as const };
  19. let captured: { messages: Array<{ role: string; content: unknown }> } | undefined;
  20. const provider = createAnthropic({
  21. apiKey: "fixture-key",
  22. baseURL: "https://provider.test/v1",
  23. fetch: async (_input, init) => {
  24. captured = JSON.parse(String(init?.body));
  25. return Response.json({
  26. id: "cache-fixture",
  27. type: "message",
  28. role: "assistant",
  29. model: "fixture",
  30. content: [{ type: "text", text: "done" }],
  31. stop_reason: "end_turn",
  32. stop_sequence: null,
  33. usage: { input_tokens: 1, output_tokens: 1 },
  34. });
  35. },
  36. });
  37. const calls = Array.from({ length: count }, (_, index) => ({
  38. id: `call_${index}`,
  39. name: "Read",
  40. input: { file_path: `/fixture/${index}` },
  41. }));
  42. const messages: ModelInputMessage[] = [
  43. { role: "user", content: "Read the requested files" },
  44. { role: "assistant", content: "", toolCalls: calls },
  45. ...calls.map(
  46. (call, index): ModelInputMessage => ({
  47. role: "tool",
  48. toolCallId: call.id,
  49. toolName: call.name,
  50. content: `result ${index}`,
  51. isError: failed && index === 0,
  52. ...(index === cachedIndex ? { cacheControl: cache } : {}),
  53. }),
  54. ),
  55. ];
  56. await generateText({
  57. model: provider("fixture"),
  58. messages: toAiSdkMessages(messages),
  59. maxRetries: 0,
  60. });
  61. expect(captured?.messages.at(-1)).toEqual({
  62. role: "user",
  63. content: calls.map((call, index) => ({
  64. type: "tool_result",
  65. tool_use_id: call.id,
  66. content: `result ${index}`,
  67. ...(failed && index === 0 ? { is_error: true } : {}),
  68. ...(index === cachedIndex ? { cache_control: cache } : {}),
  69. })),
  70. });
  71. },
  72. );
  73. });