| 1 | import { afterEach, describe, expect, test, vi } from "vitest"; |
| 2 | import { BaseLlmApi } from "../apis/base.js"; |
| 3 | import { LLMConfig } from "../types.js"; |
| 4 | import { constructLlmApi } from "../index.js"; |
| 5 | |
| 6 | interface AdapterTestCase { |
| 7 | config: LLMConfig; |
| 8 | methodToTest: keyof BaseLlmApi; |
| 9 | params: any[]; |
| 10 | expectedRequest: { |
| 11 | url: string; |
| 12 | method: string; |
| 13 | headers?: Record<string, string>; |
| 14 | body?: Record<string, any>; |
| 15 | }; |
| 16 | mockResponse?: any; |
| 17 | mockStream?: any[]; |
| 18 | } |
| 19 | |
| 20 | function createMockStream(mockStream: any[]) { |
| 21 | const encoder = new TextEncoder(); |
| 22 | return new ReadableStream({ |
| 23 | start(controller) { |
| 24 | for (const chunk of mockStream) { |
| 25 | controller.enqueue( |
| 26 | encoder.encode( |
| 27 | `data: ${ |
| 28 | typeof chunk === "string" ? chunk : JSON.stringify(chunk) |
| 29 | }\n\n`, |
| 30 | ), |
| 31 | ); |
| 32 | } |
| 33 | controller.close(); |
| 34 | }, |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | function setupMockFetch(mockResponse?: any, mockStream?: any[]) { |
| 39 | const mockFetch = vi.fn(); |
| 40 | |
| 41 | if (mockStream) { |
| 42 | const stream = createMockStream(mockStream); |
| 43 | mockFetch.mockResolvedValue( |
| 44 | new Response(stream, { |
| 45 | headers: { |
| 46 | "Content-Type": "text/event-stream", |
| 47 | }, |
| 48 | }), |
| 49 | ); |
| 50 | } else { |
| 51 | mockFetch.mockResolvedValue( |
| 52 | new Response(JSON.stringify(mockResponse), { |
| 53 | headers: { "Content-Type": "application/json" }, |
| 54 | }), |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | return mockFetch; |
| 59 | } |
| 60 | |
| 61 | function setupReadableStreamPolyfill() { |
| 62 | // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved |
| 63 | // @ts-ignore |
| 64 | const originalFrom = ReadableStream.from; |
| 65 | // @ts-ignore |
| 66 | ReadableStream.from = (body) => { |
| 67 | if (body?.source) { |
| 68 | return body; |
| 69 | } |
| 70 | return originalFrom(body); |
| 71 | }; |
| 72 | } |
| 73 | |
| 74 | async function executeAdapterMethod( |
| 75 | api: BaseLlmApi, |
| 76 | methodToTest: keyof BaseLlmApi, |
| 77 | params: any[], |
| 78 | ) { |
| 79 | if (typeof (api as any)[methodToTest] !== "function") { |
| 80 | throw new Error( |
| 81 | `Method ${String(methodToTest)} does not exist on the adapter instance.`, |
| 82 | ); |
| 83 | } |
| 84 | |
| 85 | const result = await (api as any)[methodToTest](...params); |
| 86 | |
| 87 | // If it's a generator/async iterator, consume it to trigger the HTTP request |
| 88 | if (result?.next) { |
| 89 | for await (const _ of result) { |
| 90 | // Just consume the generator to trigger the request |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | function assertFetchCall(mockFetch: any, expectedRequest: any) { |
| 96 | expect(mockFetch).toHaveBeenCalledTimes(1); |
| 97 | const [url, options] = mockFetch.mock.calls[0]; |
| 98 | |
| 99 | expect(url.toString()).toBe(expectedRequest.url); |
| 100 | expect(options.method).toBe(expectedRequest.method); |
| 101 | |
| 102 | if (expectedRequest.headers) { |
| 103 | expect(options.headers).toEqual( |
| 104 | expect.objectContaining(expectedRequest.headers), |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | if (expectedRequest.body) { |
| 109 | const actualBody = JSON.parse(options.body as string); |
| 110 | expect(actualBody).toEqual(expectedRequest.body); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | export async function runAdapterTest(testCase: AdapterTestCase) { |
| 115 | const { |
| 116 | config, |
| 117 | methodToTest, |
| 118 | params, |
| 119 | expectedRequest, |
| 120 | mockResponse, |
| 121 | mockStream, |
| 122 | } = testCase; |
| 123 | |
| 124 | const mockFetch = setupMockFetch(mockResponse, mockStream); |
| 125 | setupReadableStreamPolyfill(); |
| 126 | |
| 127 | // Mock fetch globally before constructing the API |
| 128 | vi.stubGlobal("fetch", mockFetch); |
| 129 | |
| 130 | // For non-OpenAI adapters, mock the fetch package |
| 131 | const fetchPackage = await import("@continuedev/fetch"); |
| 132 | if (fetchPackage.fetchwithRequestOptions) { |
| 133 | vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation( |
| 134 | mockFetch as any, |
| 135 | ); |
| 136 | } |
| 137 | |
| 138 | const api = constructLlmApi(config); |
| 139 | if (!api) { |
| 140 | throw new Error(`Failed to construct API for provider: ${config.provider}`); |
| 141 | } |
| 142 | |
| 143 | // For OpenAI adapters, we need to replace the fetch on the OpenAI client |
| 144 | if ((api as any).openai) { |
| 145 | (api as any).openai.fetch = mockFetch; |
| 146 | } |
| 147 | |
| 148 | await executeAdapterMethod(api, methodToTest, params); |
| 149 | assertFetchCall(mockFetch, expectedRequest); |
| 150 | } |
| 151 | |
| 152 | export interface AdapterTestConfig { |
| 153 | providerName: string; |
| 154 | config: LLMConfig; |
| 155 | expectedApiBase: string; |
| 156 | customHeaders?: Record<string, string>; |
| 157 | customBodyOptions?: any; |
| 158 | } |
| 159 | |
| 160 | export const createAdapterTests = (testConfig: AdapterTestConfig) => { |
| 161 | describe(testConfig.providerName, () => { |
| 162 | afterEach(() => { |
| 163 | vi.clearAllMocks(); |
| 164 | vi.unstubAllGlobals(); |
| 165 | }); |
| 166 | |
| 167 | test("should construct API correctly", () => { |
| 168 | const api = constructLlmApi(testConfig.config); |
| 169 | expect(api).toBeDefined(); |
| 170 | }); |
| 171 | |
| 172 | test("chatCompletionNonStream should send a valid request", async () => { |
| 173 | await runAdapterTest({ |
| 174 | config: testConfig.config, |
| 175 | methodToTest: "chatCompletionNonStream", |
| 176 | params: [ |
| 177 | { |
| 178 | model: "gpt-4", |
| 179 | messages: [{ role: "user", content: "hello" }], |
| 180 | }, |
| 181 | new AbortController().signal, |
| 182 | ], |
| 183 | expectedRequest: { |
| 184 | url: `${testConfig.expectedApiBase}chat/completions`, |
| 185 | method: "POST", |
| 186 | headers: { |
| 187 | ...testConfig.customHeaders, |
| 188 | }, |
| 189 | body: { |
| 190 | model: "gpt-4", |
| 191 | messages: [{ role: "user", content: "hello" }], |
| 192 | ...testConfig.customBodyOptions, |
| 193 | }, |
| 194 | }, |
| 195 | mockResponse: { |
| 196 | id: "test-id", |
| 197 | object: "chat.completion", |
| 198 | created: 1234567890, |
| 199 | model: "gpt-4", |
| 200 | choices: [ |
| 201 | { |
| 202 | index: 0, |
| 203 | message: { |
| 204 | role: "assistant", |
| 205 | content: "Hello! How can I help you today?", |
| 206 | }, |
| 207 | finish_reason: "stop", |
| 208 | }, |
| 209 | ], |
| 210 | usage: { |
| 211 | prompt_tokens: 10, |
| 212 | completion_tokens: 15, |
| 213 | total_tokens: 25, |
| 214 | }, |
| 215 | }, |
| 216 | }); |
| 217 | }); |
| 218 | |
| 219 | test("chatCompletionStream should send a valid request", async () => { |
| 220 | await runAdapterTest({ |
| 221 | config: testConfig.config, |
| 222 | methodToTest: "chatCompletionStream", |
| 223 | params: [ |
| 224 | { |
| 225 | model: "gpt-4", |
| 226 | messages: [{ role: "user", content: "hello" }], |
| 227 | stream: true, |
| 228 | }, |
| 229 | new AbortController().signal, |
| 230 | ], |
| 231 | expectedRequest: { |
| 232 | url: `${testConfig.expectedApiBase}chat/completions`, |
| 233 | method: "POST", |
| 234 | headers: { |
| 235 | ...testConfig.customHeaders, |
| 236 | }, |
| 237 | body: { |
| 238 | model: "gpt-4", |
| 239 | messages: [{ role: "user", content: "hello" }], |
| 240 | stream: true, |
| 241 | ...testConfig.customBodyOptions, |
| 242 | }, |
| 243 | }, |
| 244 | mockStream: [ |
| 245 | { |
| 246 | id: "test-id", |
| 247 | object: "chat.completion.chunk", |
| 248 | created: 1234567890, |
| 249 | model: "gpt-4", |
| 250 | choices: [ |
| 251 | { |
| 252 | index: 0, |
| 253 | delta: { content: "Hello" }, |
| 254 | finish_reason: null, |
| 255 | }, |
| 256 | ], |
| 257 | }, |
| 258 | { |
| 259 | id: "test-id", |
| 260 | object: "chat.completion.chunk", |
| 261 | created: 1234567890, |
| 262 | model: "gpt-4", |
| 263 | choices: [ |
| 264 | { |
| 265 | index: 0, |
| 266 | delta: { content: " world" }, |
| 267 | finish_reason: null, |
| 268 | }, |
| 269 | ], |
| 270 | }, |
| 271 | ], |
| 272 | }); |
| 273 | }); |
| 274 | |
| 275 | test("embed should send a valid request", async () => { |
| 276 | await runAdapterTest({ |
| 277 | config: testConfig.config, |
| 278 | methodToTest: "embed", |
| 279 | params: [ |
| 280 | { |
| 281 | model: "text-embedding-ada-002", |
| 282 | input: ["Hello", "World"], |
| 283 | }, |
| 284 | ], |
| 285 | expectedRequest: { |
| 286 | url: `${testConfig.expectedApiBase}embeddings`, |
| 287 | method: "POST", |
| 288 | headers: { |
| 289 | ...testConfig.customHeaders, |
| 290 | }, |
| 291 | body: { |
| 292 | model: "text-embedding-ada-002", |
| 293 | input: ["Hello", "World"], |
| 294 | encoding_format: "base64", |
| 295 | ...testConfig.customBodyOptions, |
| 296 | }, |
| 297 | }, |
| 298 | mockResponse: { |
| 299 | object: "list", |
| 300 | data: [ |
| 301 | { |
| 302 | object: "embedding", |
| 303 | embedding: [0.1, 0.2, 0.3], |
| 304 | index: 0, |
| 305 | }, |
| 306 | { |
| 307 | object: "embedding", |
| 308 | embedding: [0.4, 0.5, 0.6], |
| 309 | index: 1, |
| 310 | }, |
| 311 | ], |
| 312 | model: "text-embedding-ada-002", |
| 313 | usage: { |
| 314 | prompt_tokens: 6, |
| 315 | total_tokens: 6, |
| 316 | }, |
| 317 | }, |
| 318 | }); |
| 319 | }); |
| 320 | }); |
| 321 | }; |