| 1 | import { afterEach, describe, expect, test, vi } from "vitest"; |
| 2 | import { ILLM } from "../../../index.js"; |
| 3 | import OpenAI from "../OpenAI.js"; |
| 4 | |
| 5 | interface LlmTestCase { |
| 6 | llm: ILLM; |
| 7 | methodToTest: keyof ILLM; |
| 8 | params: any[]; |
| 9 | expectedRequest: { |
| 10 | url: string; |
| 11 | method: string; |
| 12 | headers?: Record<string, string>; |
| 13 | body?: Record<string, any>; |
| 14 | }; |
| 15 | mockResponse?: any; |
| 16 | mockStream?: any[]; |
| 17 | } |
| 18 | |
| 19 | function createMockStream(mockStream: any[]) { |
| 20 | const encoder = new TextEncoder(); |
| 21 | return new ReadableStream({ |
| 22 | start(controller) { |
| 23 | for (const chunk of mockStream) { |
| 24 | controller.enqueue( |
| 25 | encoder.encode( |
| 26 | `data: ${ |
| 27 | typeof chunk === "string" ? chunk : JSON.stringify(chunk) |
| 28 | }\n\n`, |
| 29 | ), |
| 30 | ); |
| 31 | } |
| 32 | controller.close(); |
| 33 | }, |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | function setupMockFetch(mockResponse?: any, mockStream?: any[]) { |
| 38 | const mockFetch = vi.fn(); |
| 39 | |
| 40 | if (mockStream) { |
| 41 | const stream = createMockStream(mockStream); |
| 42 | mockFetch.mockResolvedValue( |
| 43 | new Response(stream, { |
| 44 | headers: { |
| 45 | "Content-Type": "text/event-stream", |
| 46 | }, |
| 47 | }), |
| 48 | ); |
| 49 | } else { |
| 50 | mockFetch.mockResolvedValue( |
| 51 | new Response(JSON.stringify(mockResponse), { |
| 52 | headers: { "Content-Type": "application/json" }, |
| 53 | }), |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | return mockFetch; |
| 58 | } |
| 59 | |
| 60 | function setupReadableStreamPolyfill() { |
| 61 | // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved |
| 62 | // @ts-ignore |
| 63 | const originalFrom = ReadableStream.from; |
| 64 | // @ts-ignore |
| 65 | ReadableStream.from = (body) => { |
| 66 | if (body?.source) { |
| 67 | return body; |
| 68 | } |
| 69 | return originalFrom(body); |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | async function executeLlmMethod( |
| 74 | llm: ILLM, |
| 75 | methodToTest: keyof ILLM, |
| 76 | params: any[], |
| 77 | ) { |
| 78 | if (typeof (llm as any)[methodToTest] !== "function") { |
| 79 | throw new Error( |
| 80 | `Method ${String(methodToTest)} does not exist on the LLM instance.`, |
| 81 | ); |
| 82 | } |
| 83 | |
| 84 | const result = await (llm as any)[methodToTest](...params); |
| 85 | if (result?.next) { |
| 86 | for await (const _ of result) { |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | function assertFetchCall(mockFetch: any, expectedRequest: any) { |
| 92 | expect(mockFetch).toHaveBeenCalledTimes(1); |
| 93 | const [url, options] = mockFetch.mock.calls[0]; |
| 94 | |
| 95 | expect(url.toString()).toBe(expectedRequest.url); |
| 96 | expect(options.method).toBe(expectedRequest.method); |
| 97 | |
| 98 | if (expectedRequest.headers) { |
| 99 | expect(options.headers).toEqual( |
| 100 | expect.objectContaining(expectedRequest.headers), |
| 101 | ); |
| 102 | } |
| 103 | |
| 104 | if (expectedRequest.body) { |
| 105 | const actualBody = JSON.parse(options.body as string); |
| 106 | expect(actualBody).toEqual(expectedRequest.body); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | async function runLlmTest(testCase: LlmTestCase) { |
| 111 | const { |
| 112 | llm, |
| 113 | methodToTest, |
| 114 | params, |
| 115 | expectedRequest, |
| 116 | mockResponse, |
| 117 | mockStream, |
| 118 | } = testCase; |
| 119 | |
| 120 | const mockFetch = setupMockFetch(mockResponse, mockStream); |
| 121 | setupReadableStreamPolyfill(); |
| 122 | |
| 123 | (llm as any).fetch = mockFetch; |
| 124 | |
| 125 | // Disable OpenAI adapter to use our custom fetch mock |
| 126 | (llm as any).useOpenAIAdapterFor = []; |
| 127 | |
| 128 | await executeLlmMethod(llm, methodToTest, params); |
| 129 | assertFetchCall(mockFetch, expectedRequest); |
| 130 | } |
| 131 | |
| 132 | export interface OpenAISubclassConfig { |
| 133 | providerName: string; |
| 134 | defaultApiBase?: string; |
| 135 | modelConversions?: { [key: string]: string }; |
| 136 | customOptions?: any; |
| 137 | modelConversionContent?: string; |
| 138 | modelConversionMaxTokens?: number; |
| 139 | customStreamCompleteEndpoint?: string; |
| 140 | customEmbeddingsUrl?: string; |
| 141 | customEmbeddingsHeaders?: { [key: string]: string }; |
| 142 | customEmbeddingsBody?: any; |
| 143 | customBodyOptions?: any; |
| 144 | } |
| 145 | |
| 146 | function getExpectedUrl( |
| 147 | config: OpenAISubclassConfig, |
| 148 | endpoint: string, |
| 149 | model: string = "gpt-4", |
| 150 | ) { |
| 151 | let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/"; |
| 152 | if (config.providerName === "azure") { |
| 153 | return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`; |
| 154 | } else if (config.providerName === "ncompass") { |
| 155 | return `${baseUrl}${endpoint}`; |
| 156 | } |
| 157 | return `${baseUrl}${endpoint}`; |
| 158 | } |
| 159 | |
| 160 | export const createOpenAISubclassTests = ( |
| 161 | ProviderClass: typeof OpenAI, |
| 162 | config: OpenAISubclassConfig, |
| 163 | ) => { |
| 164 | describe(config.providerName, () => { |
| 165 | afterEach(() => { |
| 166 | vi.clearAllMocks(); |
| 167 | }); |
| 168 | |
| 169 | test("should have correct provider name", () => { |
| 170 | expect(ProviderClass.providerName).toBe(config.providerName); |
| 171 | }); |
| 172 | |
| 173 | if (config.defaultApiBase) { |
| 174 | test("should have correct default API base", () => { |
| 175 | expect(ProviderClass.defaultOptions?.apiBase).toBe( |
| 176 | config.defaultApiBase, |
| 177 | ); |
| 178 | }); |
| 179 | } |
| 180 | |
| 181 | test("streamChat should send a valid request", async () => { |
| 182 | const provider = new ProviderClass({ |
| 183 | apiKey: "test-api-key", |
| 184 | model: "gpt-4", |
| 185 | apiBase: config.defaultApiBase || "https://api.openai.com/v1/", |
| 186 | }); |
| 187 | |
| 188 | await runLlmTest({ |
| 189 | llm: provider, |
| 190 | methodToTest: "streamChat", |
| 191 | params: [ |
| 192 | [{ role: "user", content: "hello" }], |
| 193 | new AbortController().signal, |
| 194 | ], |
| 195 | expectedRequest: { |
| 196 | url: getExpectedUrl(config, "chat/completions"), |
| 197 | method: "POST", |
| 198 | headers: { |
| 199 | "Content-Type": "application/json", |
| 200 | Authorization: "Bearer test-api-key", |
| 201 | "api-key": "test-api-key", |
| 202 | }, |
| 203 | body: { |
| 204 | model: "gpt-4", |
| 205 | messages: [{ role: "user", content: "hello" }], |
| 206 | stream: true, |
| 207 | max_tokens: 2048, |
| 208 | ...config.customBodyOptions, |
| 209 | }, |
| 210 | }, |
| 211 | mockStream: [ |
| 212 | { choices: [{ delta: { content: "Hello" } }] }, |
| 213 | { choices: [{ delta: { content: " world" } }] }, |
| 214 | ], |
| 215 | }); |
| 216 | }); |
| 217 | |
| 218 | test("chat should send a valid request", async () => { |
| 219 | const provider = new ProviderClass({ |
| 220 | apiKey: "test-api-key", |
| 221 | model: "gpt-4", |
| 222 | apiBase: config.defaultApiBase || "https://api.openai.com/v1/", |
| 223 | }); |
| 224 | |
| 225 | await runLlmTest({ |
| 226 | llm: provider, |
| 227 | methodToTest: "chat", |
| 228 | params: [ |
| 229 | [{ role: "user", content: "hello" }], |
| 230 | new AbortController().signal, |
| 231 | ], |
| 232 | expectedRequest: { |
| 233 | url: getExpectedUrl(config, "chat/completions"), |
| 234 | method: "POST", |
| 235 | headers: { |
| 236 | "Content-Type": "application/json", |
| 237 | Authorization: "Bearer test-api-key", |
| 238 | "api-key": "test-api-key", |
| 239 | }, |
| 240 | body: { |
| 241 | model: "gpt-4", |
| 242 | messages: [{ role: "user", content: "hello" }], |
| 243 | stream: true, |
| 244 | max_tokens: 2048, |
| 245 | ...config.customBodyOptions, |
| 246 | }, |
| 247 | }, |
| 248 | mockStream: [ |
| 249 | { choices: [{ delta: { content: "Hello" } }] }, |
| 250 | { choices: [{ delta: { content: " world" } }] }, |
| 251 | ], |
| 252 | }); |
| 253 | }); |
| 254 | |
| 255 | test("streamComplete should send a valid request", async () => { |
| 256 | const provider = new ProviderClass({ |
| 257 | apiKey: "test-api-key", |
| 258 | model: "gpt-4", |
| 259 | apiBase: config.defaultApiBase || "https://api.openai.com/v1/", |
| 260 | }); |
| 261 | |
| 262 | await runLlmTest({ |
| 263 | llm: provider, |
| 264 | methodToTest: "streamComplete", |
| 265 | params: ["Hello", new AbortController().signal], |
| 266 | expectedRequest: { |
| 267 | url: getExpectedUrl( |
| 268 | config, |
| 269 | config.customStreamCompleteEndpoint || "chat/completions", |
| 270 | ), |
| 271 | method: "POST", |
| 272 | headers: { |
| 273 | "Content-Type": "application/json", |
| 274 | Authorization: "Bearer test-api-key", |
| 275 | "api-key": "test-api-key", |
| 276 | }, |
| 277 | body: |
| 278 | config.customStreamCompleteEndpoint === "completions" |
| 279 | ? { |
| 280 | model: "gpt-4", |
| 281 | prompt: "Hello", |
| 282 | stream: true, |
| 283 | max_tokens: 2048, |
| 284 | ...config.customBodyOptions, |
| 285 | } |
| 286 | : { |
| 287 | model: "gpt-4", |
| 288 | messages: [{ role: "user", content: "Hello" }], |
| 289 | stream: true, |
| 290 | max_tokens: 2048, |
| 291 | ...config.customBodyOptions, |
| 292 | }, |
| 293 | }, |
| 294 | mockStream: [ |
| 295 | { choices: [{ delta: { content: "Hello" } }] }, |
| 296 | { choices: [{ delta: { content: " world" } }] }, |
| 297 | ], |
| 298 | }); |
| 299 | }); |
| 300 | |
| 301 | test("complete should send a valid request", async () => { |
| 302 | const provider = new ProviderClass({ |
| 303 | apiKey: "test-api-key", |
| 304 | model: "gpt-4", |
| 305 | apiBase: config.defaultApiBase || "https://api.openai.com/v1/", |
| 306 | }); |
| 307 | |
| 308 | await runLlmTest({ |
| 309 | llm: provider, |
| 310 | methodToTest: "complete", |
| 311 | params: ["Hello", new AbortController().signal], |
| 312 | expectedRequest: { |
| 313 | url: getExpectedUrl(config, "chat/completions"), |
| 314 | method: "POST", |
| 315 | headers: { |
| 316 | "Content-Type": "application/json", |
| 317 | Authorization: "Bearer test-api-key", |
| 318 | "api-key": "test-api-key", |
| 319 | }, |
| 320 | body: { |
| 321 | model: "gpt-4", |
| 322 | messages: [{ role: "user", content: "Hello" }], |
| 323 | stream: true, |
| 324 | max_tokens: 2048, |
| 325 | ...config.customBodyOptions, |
| 326 | }, |
| 327 | }, |
| 328 | mockStream: [ |
| 329 | { choices: [{ delta: { content: "Hello" } }] }, |
| 330 | { choices: [{ delta: { content: " world" } }] }, |
| 331 | ], |
| 332 | }); |
| 333 | }); |
| 334 | |
| 335 | test("should handle embeddings", async () => { |
| 336 | const provider = new ProviderClass({ |
| 337 | apiKey: "test-api-key", |
| 338 | model: "text-embedding-ada-002", |
| 339 | apiBase: config.defaultApiBase || "https://api.openai.com/v1/", |
| 340 | }); |
| 341 | |
| 342 | // Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint) |
| 343 | if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) { |
| 344 | return; |
| 345 | } |
| 346 | |
| 347 | await runLlmTest({ |
| 348 | llm: provider, |
| 349 | methodToTest: "embed", |
| 350 | params: [["Hello", "World"]], |
| 351 | expectedRequest: { |
| 352 | url: |
| 353 | config.customEmbeddingsUrl || |
| 354 | `${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`, |
| 355 | method: "POST", |
| 356 | headers: config.customEmbeddingsHeaders || { |
| 357 | Authorization: "Bearer test-api-key", |
| 358 | "Content-Type": "application/json", |
| 359 | "api-key": "test-api-key", |
| 360 | }, |
| 361 | body: config.customEmbeddingsBody || { |
| 362 | input: ["Hello", "World"], |
| 363 | model: "text-embedding-ada-002", |
| 364 | }, |
| 365 | }, |
| 366 | mockResponse: { |
| 367 | data: [ |
| 368 | { embedding: [0.1, 0.2, 0.3] }, |
| 369 | { embedding: [0.4, 0.5, 0.6] }, |
| 370 | ], |
| 371 | }, |
| 372 | }); |
| 373 | }); |
| 374 | }); |
| 375 | }; |