| 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 | // Handle both plain objects and Headers objects |
| 104 | const actualHeaders = options.headers; |
| 105 | if ( |
| 106 | actualHeaders && |
| 107 | typeof actualHeaders === "object" && |
| 108 | "get" in actualHeaders |
| 109 | ) { |
| 110 | // This is a Headers-like object, convert to plain object for comparison |
| 111 | const headersObj: Record<string, string> = {}; |
| 112 | for (const key of Object.keys(expectedRequest.headers)) { |
| 113 | const value = actualHeaders.get(key); |
| 114 | if (value !== null && value !== undefined) { |
| 115 | headersObj[key] = value; |
| 116 | } |
| 117 | } |
| 118 | expect(headersObj).toEqual( |
| 119 | expect.objectContaining(expectedRequest.headers), |
| 120 | ); |
| 121 | } else { |
| 122 | expect(actualHeaders).toEqual( |
| 123 | expect.objectContaining(expectedRequest.headers), |
| 124 | ); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | if (expectedRequest.body) { |
| 129 | const actualBody = JSON.parse(options.body as string); |
| 130 | expect(actualBody).toEqual(expectedRequest.body); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | export async function runAdapterTest(testCase: AdapterTestCase) { |
| 135 | const { |
| 136 | config, |
| 137 | methodToTest, |
| 138 | params, |
| 139 | expectedRequest, |
| 140 | mockResponse, |
| 141 | mockStream, |
| 142 | } = testCase; |
| 143 | |
| 144 | const mockFetch = setupMockFetch(mockResponse, mockStream); |
| 145 | setupReadableStreamPolyfill(); |
| 146 | |
| 147 | // Mock fetch globally before constructing the API |
| 148 | vi.stubGlobal("fetch", mockFetch); |
| 149 | |
| 150 | // For non-OpenAI adapters, mock the fetch package |
| 151 | const fetchPackage = await import("@continuedev/fetch"); |
| 152 | if (fetchPackage.fetchwithRequestOptions) { |
| 153 | vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation( |
| 154 | mockFetch as any, |
| 155 | ); |
| 156 | } |
| 157 | |
| 158 | const api = constructLlmApi(config); |
| 159 | if (!api) { |
| 160 | throw new Error(`Failed to construct API for provider: ${config.provider}`); |
| 161 | } |
| 162 | |
| 163 | // For OpenAI adapters, we need to replace the fetch on the OpenAI client |
| 164 | if ((api as any).openai) { |
| 165 | (api as any).openai.fetch = mockFetch; |
| 166 | } |
| 167 | |
| 168 | await executeAdapterMethod(api, methodToTest, params); |
| 169 | assertFetchCall(mockFetch, expectedRequest); |
| 170 | } |
| 171 | |
| 172 | export interface AdapterTestConfig { |
| 173 | providerName: string; |
| 174 | config: LLMConfig; |
| 175 | expectedApiBase: string; |
| 176 | customHeaders?: Record<string, string>; |
| 177 | customBodyOptions?: any; |
| 178 | } |
| 179 | |
| 180 | export const createAdapterTests = (testConfig: AdapterTestConfig) => { |
| 181 | describe(testConfig.providerName, () => { |
| 182 | afterEach(() => { |
| 183 | vi.clearAllMocks(); |
| 184 | vi.unstubAllGlobals(); |
| 185 | }); |
| 186 | |
| 187 | test("should construct API correctly", () => { |
| 188 | const api = constructLlmApi(testConfig.config); |
| 189 | expect(api).toBeDefined(); |
| 190 | }); |
| 191 | |
| 192 | test("chatCompletionNonStream should send a valid request", async () => { |
| 193 | await runAdapterTest({ |
| 194 | config: testConfig.config, |
| 195 | methodToTest: "chatCompletionNonStream", |
| 196 | params: [ |
| 197 | { |
| 198 | model: "gpt-4", |
| 199 | messages: [{ role: "user", content: "hello" }], |
| 200 | }, |
| 201 | new AbortController().signal, |
| 202 | ], |
| 203 | expectedRequest: { |
| 204 | url: `${testConfig.expectedApiBase}chat/completions`, |
| 205 | method: "POST", |
| 206 | headers: { |
| 207 | ...testConfig.customHeaders, |
| 208 | }, |
| 209 | body: { |
| 210 | model: "gpt-4", |
| 211 | messages: [{ role: "user", content: "hello" }], |
| 212 | ...testConfig.customBodyOptions, |
| 213 | }, |
| 214 | }, |
| 215 | mockResponse: { |
| 216 | id: "test-id", |
| 217 | object: "chat.completion", |
| 218 | created: 1234567890, |
| 219 | model: "gpt-4", |
| 220 | choices: [ |
| 221 | { |
| 222 | index: 0, |
| 223 | message: { |
| 224 | role: "assistant", |
| 225 | content: "Hello! How can I help you today?", |
| 226 | }, |
| 227 | finish_reason: "stop", |
| 228 | }, |
| 229 | ], |
| 230 | usage: { |
| 231 | prompt_tokens: 10, |
| 232 | completion_tokens: 15, |
| 233 | total_tokens: 25, |
| 234 | }, |
| 235 | }, |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | test("chatCompletionStream should send a valid request", async () => { |
| 240 | await runAdapterTest({ |
| 241 | config: testConfig.config, |
| 242 | methodToTest: "chatCompletionStream", |
| 243 | params: [ |
| 244 | { |
| 245 | model: "gpt-4", |
| 246 | messages: [{ role: "user", content: "hello" }], |
| 247 | stream: true, |
| 248 | }, |
| 249 | new AbortController().signal, |
| 250 | ], |
| 251 | expectedRequest: { |
| 252 | url: `${testConfig.expectedApiBase}chat/completions`, |
| 253 | method: "POST", |
| 254 | headers: { |
| 255 | ...testConfig.customHeaders, |
| 256 | }, |
| 257 | body: { |
| 258 | model: "gpt-4", |
| 259 | messages: [{ role: "user", content: "hello" }], |
| 260 | stream: true, |
| 261 | stream_options: { include_usage: true }, |
| 262 | ...testConfig.customBodyOptions, |
| 263 | }, |
| 264 | }, |
| 265 | mockStream: [ |
| 266 | { |
| 267 | id: "test-id", |
| 268 | object: "chat.completion.chunk", |
| 269 | created: 1234567890, |
| 270 | model: "gpt-4", |
| 271 | choices: [ |
| 272 | { |
| 273 | index: 0, |
| 274 | delta: { content: "Hello" }, |
| 275 | finish_reason: null, |
| 276 | }, |
| 277 | ], |
| 278 | }, |
| 279 | { |
| 280 | id: "test-id", |
| 281 | object: "chat.completion.chunk", |
| 282 | created: 1234567890, |
| 283 | model: "gpt-4", |
| 284 | choices: [ |
| 285 | { |
| 286 | index: 0, |
| 287 | delta: { content: " world" }, |
| 288 | finish_reason: null, |
| 289 | }, |
| 290 | ], |
| 291 | }, |
| 292 | ], |
| 293 | }); |
| 294 | }); |
| 295 | |
| 296 | test("embed should send a valid request", async () => { |
| 297 | await runAdapterTest({ |
| 298 | config: testConfig.config, |
| 299 | methodToTest: "embed", |
| 300 | params: [ |
| 301 | { |
| 302 | model: "text-embedding-ada-002", |
| 303 | input: ["Hello", "World"], |
| 304 | }, |
| 305 | ], |
| 306 | expectedRequest: { |
| 307 | url: `${testConfig.expectedApiBase}embeddings`, |
| 308 | method: "POST", |
| 309 | headers: { |
| 310 | ...testConfig.customHeaders, |
| 311 | }, |
| 312 | body: { |
| 313 | model: "text-embedding-ada-002", |
| 314 | input: ["Hello", "World"], |
| 315 | encoding_format: "base64", |
| 316 | ...testConfig.customBodyOptions, |
| 317 | }, |
| 318 | }, |
| 319 | mockResponse: { |
| 320 | object: "list", |
| 321 | data: [ |
| 322 | { |
| 323 | object: "embedding", |
| 324 | embedding: [0.1, 0.2, 0.3], |
| 325 | index: 0, |
| 326 | }, |
| 327 | { |
| 328 | object: "embedding", |
| 329 | embedding: [0.4, 0.5, 0.6], |
| 330 | index: 1, |
| 331 | }, |
| 332 | ], |
| 333 | model: "text-embedding-ada-002", |
| 334 | usage: { |
| 335 | prompt_tokens: 6, |
| 336 | total_tokens: 6, |
| 337 | }, |
| 338 | }, |
| 339 | }); |
| 340 | }); |
| 341 | }); |
| 342 | }; |