anthropic-eager-tool-input-compat.test.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { Type } from "typebox";
  4. import { describe, expect, it } from "vitest";
  5. import { streamAnthropic } from "../src/providers/anthropic.ts";
  6. import type { Context, Model, Tool } from "../src/types.ts";
  7. interface CapturedRequest {
  8. headers: IncomingMessage["headers"];
  9. body: Record<string, unknown>;
  10. }
  11. function createModel(baseUrl: string, compat?: Model<"anthropic-messages">["compat"]): Model<"anthropic-messages"> {
  12. return {
  13. id: "claude-opus-4-8",
  14. name: "Claude Opus 4.8",
  15. api: "anthropic-messages",
  16. provider: "test-anthropic",
  17. baseUrl,
  18. reasoning: true,
  19. input: ["text"],
  20. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  21. contextWindow: 200000,
  22. maxTokens: 32000,
  23. compat: { forceAdaptiveThinking: true, ...compat },
  24. };
  25. }
  26. const tool: Tool = {
  27. name: "lookup",
  28. description: "Look up a value",
  29. parameters: Type.Object({ value: Type.String() }),
  30. };
  31. function createContext(tools: Tool[] = [tool]): Context {
  32. return {
  33. messages: [{ role: "user", content: "Use the tool", timestamp: Date.now() }],
  34. ...(tools.length > 0 ? { tools } : {}),
  35. };
  36. }
  37. async function readRequestBody(request: IncomingMessage): Promise<Record<string, unknown>> {
  38. const chunks: Buffer[] = [];
  39. for await (const chunk of request) {
  40. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  41. }
  42. return JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>;
  43. }
  44. function writeEmptySseResponse(response: ServerResponse): void {
  45. response.writeHead(200, { "content-type": "text/event-stream" });
  46. response.end();
  47. }
  48. async function captureAnthropicRequest(
  49. compat: Model<"anthropic-messages">["compat"],
  50. context: Context,
  51. ): Promise<CapturedRequest> {
  52. let capturedRequest: CapturedRequest | undefined;
  53. const server = createServer(async (request, response) => {
  54. capturedRequest = {
  55. headers: request.headers,
  56. body: await readRequestBody(request),
  57. };
  58. writeEmptySseResponse(response);
  59. });
  60. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  61. const address = server.address() as AddressInfo;
  62. try {
  63. const stream = streamAnthropic(createModel(`http://127.0.0.1:${address.port}`, compat), context, {
  64. apiKey: "test-key",
  65. cacheRetention: "none",
  66. });
  67. for await (const event of stream) {
  68. if (event.type === "done" || event.type === "error") break;
  69. }
  70. } finally {
  71. await new Promise<void>((resolve, reject) => {
  72. server.close((error) => (error ? reject(error) : resolve()));
  73. });
  74. }
  75. if (!capturedRequest) {
  76. throw new Error("Anthropic request was not captured");
  77. }
  78. return capturedRequest;
  79. }
  80. function getFirstTool(body: Record<string, unknown>): Record<string, unknown> {
  81. const tools = body.tools;
  82. if (!Array.isArray(tools) || typeof tools[0] !== "object" || tools[0] === null) {
  83. throw new Error("Expected first tool in request body");
  84. }
  85. return tools[0] as Record<string, unknown>;
  86. }
  87. describe("Anthropic eager tool input streaming compatibility", () => {
  88. it("preserves nested array constraints through object properties", async () => {
  89. const questionnaireTool: Tool = {
  90. name: "ask_user",
  91. description: "Ask structured questions",
  92. parameters: Type.Object(
  93. {
  94. steps: Type.Array(
  95. Type.Object({
  96. question: Type.String(),
  97. options: Type.Array(Type.Object({ label: Type.String() }), { minItems: 2, maxItems: 4 }),
  98. }),
  99. { minItems: 1, maxItems: 4 },
  100. ),
  101. },
  102. { additionalProperties: false },
  103. ),
  104. };
  105. const request = await captureAnthropicRequest(undefined, createContext([questionnaireTool]));
  106. const inputSchema = getFirstTool(request.body).input_schema;
  107. expect(inputSchema).toMatchObject({
  108. type: "object",
  109. required: ["steps"],
  110. properties: {
  111. steps: {
  112. type: "array",
  113. minItems: 1,
  114. maxItems: 4,
  115. items: {
  116. type: "object",
  117. required: ["question", "options"],
  118. properties: {
  119. options: { type: "array", minItems: 2, maxItems: 4 },
  120. },
  121. },
  122. },
  123. },
  124. });
  125. });
  126. it("sends per-tool eager_input_streaming by default", async () => {
  127. const request = await captureAnthropicRequest(undefined, createContext());
  128. expect(getFirstTool(request.body).eager_input_streaming).toBe(true);
  129. expect(request.headers["anthropic-beta"]).toBeUndefined();
  130. });
  131. it("uses the legacy fine-grained tool streaming beta when eager tool input streaming is disabled", async () => {
  132. const request = await captureAnthropicRequest({ supportsEagerToolInputStreaming: false }, createContext());
  133. expect(getFirstTool(request.body).eager_input_streaming).toBeUndefined();
  134. expect(request.headers["anthropic-beta"]).toBe("fine-grained-tool-streaming-2025-05-14");
  135. });
  136. it("does not send the legacy fine-grained tool streaming beta when there are no tools", async () => {
  137. const request = await captureAnthropicRequest({ supportsEagerToolInputStreaming: false }, createContext([]));
  138. expect(request.body.tools).toBeUndefined();
  139. expect(request.headers["anthropic-beta"]).toBeUndefined();
  140. });
  141. });