Elffuss BraidHub

kikocis/continue public

8eb3ae7b8d16 · 8.9 KiBRawPermalink
1import { afterEach, describe, expect, test, vi } from "vitest";
2import { BaseLlmApi } from "../apis/base.js";
3import { LLMConfig } from "../types.js";
4import { constructLlmApi } from "../index.js";
5
6interface 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
20function 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
38function 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
61function 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
74async 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
95function 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
134export 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
172export interface AdapterTestConfig {
173 providerName: string;
174 config: LLMConfig;
175 expectedApiBase: string;
176 customHeaders?: Record<string, string>;
177 customBodyOptions?: any;
178}
179
180export 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 ...testConfig.customBodyOptions,
262 },
263 },
264 mockStream: [
265 {
266 id: "test-id",
267 object: "chat.completion.chunk",
268 created: 1234567890,
269 model: "gpt-4",
270 choices: [
271 {
272 index: 0,
273 delta: { content: "Hello" },
274 finish_reason: null,
275 },
276 ],
277 },
278 {
279 id: "test-id",
280 object: "chat.completion.chunk",
281 created: 1234567890,
282 model: "gpt-4",
283 choices: [
284 {
285 index: 0,
286 delta: { content: " world" },
287 finish_reason: null,
288 },
289 ],
290 },
291 ],
292 });
293 });
294
295 test("embed should send a valid request", async () => {
296 await runAdapterTest({
297 config: testConfig.config,
298 methodToTest: "embed",
299 params: [
300 {
301 model: "text-embedding-ada-002",
302 input: ["Hello", "World"],
303 },
304 ],
305 expectedRequest: {
306 url: `${testConfig.expectedApiBase}embeddings`,
307 method: "POST",
308 headers: {
309 ...testConfig.customHeaders,
310 },
311 body: {
312 model: "text-embedding-ada-002",
313 input: ["Hello", "World"],
314 encoding_format: "base64",
315 ...testConfig.customBodyOptions,
316 },
317 },
318 mockResponse: {
319 object: "list",
320 data: [
321 {
322 object: "embedding",
323 embedding: [0.1, 0.2, 0.3],
324 index: 0,
325 },
326 {
327 object: "embedding",
328 embedding: [0.4, 0.5, 0.6],
329 index: 1,
330 },
331 ],
332 model: "text-embedding-ada-002",
333 usage: {
334 prompt_tokens: 6,
335 total_tokens: 6,
336 },
337 },
338 });
339 });
340 });
341};