fireworks-models.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { Type } from "typebox";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { findEnvKeys, getEnvApiKey } from "../src/env-api-keys.ts";
  6. import { getModel, getModels } from "../src/models.ts";
  7. import { streamAnthropic } from "../src/providers/anthropic.ts";
  8. import type { Context, Model, Tool } from "../src/types.ts";
  9. const originalFireworksApiKey = process.env.FIREWORKS_API_KEY;
  10. afterEach(() => {
  11. if (originalFireworksApiKey === undefined) {
  12. delete process.env.FIREWORKS_API_KEY;
  13. } else {
  14. process.env.FIREWORKS_API_KEY = originalFireworksApiKey;
  15. }
  16. });
  17. describe("Fireworks models", () => {
  18. it("registers the default Kimi K2.6 model via Anthropic-compatible Messages API", () => {
  19. const model = getModel("fireworks", "accounts/fireworks/models/kimi-k2p6");
  20. expect(model).toBeDefined();
  21. expect(model.api).toBe("anthropic-messages");
  22. expect(model.provider).toBe("fireworks");
  23. expect(model.baseUrl).toBe("https://api.fireworks.ai/inference");
  24. expect(model.reasoning).toBe(true);
  25. expect(model.input).toEqual(["text", "image"]);
  26. expect(model.contextWindow).toBe(262000);
  27. expect(model.maxTokens).toBe(262000);
  28. expect(model.cost).toEqual({
  29. input: 0.95,
  30. output: 4,
  31. cacheRead: 0.16,
  32. cacheWrite: 0,
  33. });
  34. });
  35. it("registers the Fire Pass turbo router model", () => {
  36. const model = getModels("fireworks").find(
  37. (candidate) => candidate.id.startsWith("accounts/fireworks/routers/") && candidate.id.endsWith("-turbo"),
  38. );
  39. expect(model).toBeDefined();
  40. expect(model?.api).toBe("anthropic-messages");
  41. expect(model?.baseUrl).toBe("https://api.fireworks.ai/inference");
  42. expect(model?.input).toEqual(["text", "image"]);
  43. });
  44. it("resolves FIREWORKS_API_KEY from the environment", () => {
  45. process.env.FIREWORKS_API_KEY = "test-fireworks-key";
  46. expect(findEnvKeys("fireworks")).toEqual(["FIREWORKS_API_KEY"]);
  47. expect(getEnvApiKey("fireworks")).toBe("test-fireworks-key");
  48. });
  49. it("sets Fireworks-specific compat for session affinity and unsupported tool fields", () => {
  50. const model = getModel("fireworks", "accounts/fireworks/models/kimi-k2p6");
  51. expect(model.compat).toBeDefined();
  52. expect(model.compat?.sendSessionAffinityHeaders).toBe(true);
  53. expect(model.compat?.supportsEagerToolInputStreaming).toBe(false);
  54. expect(model.compat?.supportsCacheControlOnTools).toBe(false);
  55. expect(model.compat?.supportsLongCacheRetention).toBe(false);
  56. });
  57. });
  58. // --- Integration tests for Fireworks Anthropic session affinity and tool compat ---
  59. interface CapturedRequest {
  60. headers: IncomingMessage["headers"];
  61. body: Record<string, unknown>;
  62. }
  63. const tool: Tool = {
  64. name: "lookup",
  65. description: "Look up a value",
  66. parameters: Type.Object({ value: Type.String() }),
  67. };
  68. function createFireworksModel(compat?: Model<"anthropic-messages">["compat"]): Model<"anthropic-messages"> {
  69. return {
  70. id: "accounts/fireworks/models/kimi-k2p6",
  71. name: "Kimi K2.6",
  72. api: "anthropic-messages",
  73. provider: "fireworks",
  74. baseUrl: "http://127.0.0.1:0", // overridden by captureAnthropicRequest
  75. reasoning: true,
  76. input: ["text", "image"],
  77. cost: { input: 0.95, output: 4, cacheRead: 0.16, cacheWrite: 0 },
  78. contextWindow: 262000,
  79. maxTokens: 262000,
  80. compat,
  81. };
  82. }
  83. function createAnthropicModel(): Model<"anthropic-messages"> {
  84. return {
  85. id: "claude-opus-4-8",
  86. name: "Claude Opus 4.8",
  87. api: "anthropic-messages",
  88. provider: "anthropic",
  89. baseUrl: "http://127.0.0.1:0", // overridden by captureAnthropicRequest
  90. reasoning: true,
  91. input: ["text"],
  92. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  93. contextWindow: 200000,
  94. maxTokens: 32000,
  95. };
  96. }
  97. function createContext(tools: Tool[] = [tool]): Context {
  98. return {
  99. messages: [{ role: "user", content: "Use the tool", timestamp: Date.now() }],
  100. ...(tools.length > 0 ? { tools } : {}),
  101. };
  102. }
  103. async function readRequestBody(request: IncomingMessage): Promise<Record<string, unknown>> {
  104. const chunks: Buffer[] = [];
  105. for await (const chunk of request) {
  106. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  107. }
  108. return JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>;
  109. }
  110. function writeEmptySseResponse(response: ServerResponse): void {
  111. response.writeHead(200, { "content-type": "text/event-stream" });
  112. response.end();
  113. }
  114. async function captureAnthropicRequest(
  115. model: Model<"anthropic-messages">,
  116. context: Context,
  117. options?: { sessionId?: string; cacheRetention?: string; fetch?: typeof globalThis.fetch },
  118. ): Promise<CapturedRequest> {
  119. let capturedRequest: CapturedRequest | undefined;
  120. const server = createServer(async (request, response) => {
  121. capturedRequest = {
  122. headers: request.headers,
  123. body: await readRequestBody(request),
  124. };
  125. writeEmptySseResponse(response);
  126. });
  127. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  128. const address = server.address() as AddressInfo;
  129. try {
  130. // Override the model's baseUrl to point to the local test server
  131. const localModel = { ...model, baseUrl: `http://127.0.0.1:${address.port}` };
  132. const stream = streamAnthropic(localModel, context, {
  133. apiKey: "test-key",
  134. cacheRetention: (options?.cacheRetention as "none" | "short" | "long") ?? "short",
  135. fetch: options?.fetch,
  136. sessionId: options?.sessionId,
  137. });
  138. for await (const event of stream) {
  139. if (event.type === "done" || event.type === "error") break;
  140. }
  141. } finally {
  142. await new Promise<void>((resolve, reject) => {
  143. server.close((error) => (error ? reject(error) : resolve()));
  144. });
  145. }
  146. if (!capturedRequest) {
  147. throw new Error("Anthropic request was not captured");
  148. }
  149. return capturedRequest;
  150. }
  151. function getTools(body: Record<string, unknown>): Record<string, unknown>[] {
  152. const tools = body.tools;
  153. if (!Array.isArray(tools)) {
  154. throw new Error("Expected tools in request body");
  155. }
  156. return tools as Record<string, unknown>[];
  157. }
  158. describe("Fireworks Anthropic session affinity and tool compat", () => {
  159. it("uses the custom fetch implementation for Anthropic-compatible requests", async () => {
  160. let customFetchCalled = false;
  161. const customFetch: typeof globalThis.fetch = async (input, init) => {
  162. customFetchCalled = true;
  163. return fetch(input, init);
  164. };
  165. const model = createFireworksModel();
  166. await captureAnthropicRequest(model, createContext(), { fetch: customFetch });
  167. expect(customFetchCalled).toBe(true);
  168. });
  169. it("sends x-session-affinity header for Fireworks models", async () => {
  170. const model = createFireworksModel();
  171. // Need a real port, capture will assign one
  172. const request = await captureAnthropicRequest(model, createContext(), {
  173. sessionId: "fireworks-session-1",
  174. });
  175. expect(request.headers["x-session-affinity"]).toBe("fireworks-session-1");
  176. });
  177. it("omits x-session-affinity header for native Anthropic models", async () => {
  178. const model = createAnthropicModel();
  179. const request = await captureAnthropicRequest(model, createContext(), {
  180. sessionId: "anthropic-session-1",
  181. });
  182. expect(request.headers["x-session-affinity"]).toBeUndefined();
  183. });
  184. it("omits x-session-affinity header when cacheRetention is none", async () => {
  185. const model = createFireworksModel();
  186. const request = await captureAnthropicRequest(model, createContext(), {
  187. sessionId: "fireworks-session-2",
  188. cacheRetention: "none",
  189. });
  190. expect(request.headers["x-session-affinity"]).toBeUndefined();
  191. });
  192. it("omits cache_control on tools for Fireworks models", async () => {
  193. const model = createFireworksModel();
  194. const request = await captureAnthropicRequest(model, createContext());
  195. const tools = getTools(request.body);
  196. const lastTool = tools[tools.length - 1];
  197. expect(lastTool.cache_control).toBeUndefined();
  198. });
  199. it("omits eager_input_streaming on tools for Fireworks models", async () => {
  200. const model = createFireworksModel();
  201. const request = await captureAnthropicRequest(model, createContext());
  202. const tools = getTools(request.body);
  203. for (const t of tools) {
  204. expect(t.eager_input_streaming).toBeUndefined();
  205. }
  206. });
  207. it("sends cache_control on tools for native Anthropic models", async () => {
  208. const model = createAnthropicModel();
  209. const request = await captureAnthropicRequest(model, createContext());
  210. const tools = getTools(request.body);
  211. const lastTool = tools[tools.length - 1];
  212. expect(lastTool.cache_control).toBeDefined();
  213. expect((lastTool.cache_control as { type: string }).type).toBe("ephemeral");
  214. });
  215. it("sends eager_input_streaming on tools for native Anthropic models", async () => {
  216. const model = createAnthropicModel();
  217. const request = await captureAnthropicRequest(model, createContext());
  218. const tools = getTools(request.body);
  219. expect(tools[0].eager_input_streaming).toBe(true);
  220. });
  221. });