Elffuss BraidHub

kikocis/continue public

main · 21.3 KiBRawPermalink
1import { afterEach, describe, expect, test, vi } from "vitest";
2import { ILLM } from "../../../index.js";
3import ContinueProxy from "./ContinueProxy.js";
4
5vi.mock("@continuedev/config-yaml", async (importOriginal) => {
6 const mod = (await importOriginal()) as any;
7 return {
8 ...mod,
9 parseProxyModelName: vi.fn(() => ({
10 provider: "test-provider",
11 model: "test-model",
12 ownerSlug: "test-owner",
13 packageSlug: "test-package",
14 })),
15 };
16});
17
18interface LlmTestCase {
19 llm: ILLM;
20 methodToTest: keyof ILLM;
21 params: any[];
22 expectedRequest: {
23 url: string;
24 method: string;
25 headers?: Record<string, string>;
26 body?: Record<string, any>;
27 };
28 mockResponse?: any;
29 mockStream?: any[];
30}
31
32function createMockStream(mockStream: any[]) {
33 const encoder = new TextEncoder();
34 return new ReadableStream({
35 start(controller) {
36 for (const chunk of mockStream) {
37 controller.enqueue(
38 encoder.encode(
39 `data: ${
40 typeof chunk === "string" ? chunk : JSON.stringify(chunk)
41 }\n\n`,
42 ),
43 );
44 }
45 controller.close();
46 },
47 });
48}
49
50function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
51 const mockFetch = vi.fn();
52
53 if (mockStream) {
54 const stream = createMockStream(mockStream);
55 mockFetch.mockResolvedValue(
56 new Response(stream, {
57 headers: {
58 "Content-Type": "text/event-stream",
59 },
60 }),
61 );
62 } else {
63 mockFetch.mockResolvedValue(
64 new Response(JSON.stringify(mockResponse), {
65 headers: { "Content-Type": "application/json" },
66 }),
67 );
68 }
69
70 return mockFetch;
71}
72
73function setupReadableStreamPolyfill() {
74 // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
75 // @ts-ignore
76 const originalFrom = ReadableStream.from;
77 // @ts-ignore
78 ReadableStream.from = (body) => {
79 if (body?.source) {
80 return body;
81 }
82 return originalFrom(body);
83 };
84}
85
86async function executeLlmMethod(
87 llm: ILLM,
88 methodToTest: keyof ILLM,
89 params: any[],
90) {
91 if (typeof (llm as any)[methodToTest] !== "function") {
92 throw new Error(
93 `Method ${String(methodToTest)} does not exist on the LLM instance.`,
94 );
95 }
96
97 const result = await (llm as any)[methodToTest](...params);
98 if (result?.next) {
99 for await (const _ of result) {
100 }
101 }
102}
103
104function assertFetchCall(mockFetch: any, expectedRequest: any) {
105 expect(mockFetch).toHaveBeenCalledTimes(1);
106 const [url, options] = mockFetch.mock.calls[0];
107
108 expect(url.toString()).toBe(expectedRequest.url);
109 expect(options.method).toBe(expectedRequest.method);
110
111 if (expectedRequest.headers) {
112 expect(options.headers).toEqual(
113 expect.objectContaining(expectedRequest.headers),
114 );
115 }
116
117 if (expectedRequest.body) {
118 const actualBody = JSON.parse(options.body as string);
119 expect(actualBody).toEqual(expectedRequest.body);
120 }
121}
122
123async function runLlmTest(testCase: LlmTestCase) {
124 const {
125 llm,
126 methodToTest,
127 params,
128 expectedRequest,
129 mockResponse,
130 mockStream,
131 } = testCase;
132
133 const mockFetch = setupMockFetch(mockResponse, mockStream);
134 setupReadableStreamPolyfill();
135
136 (llm as any).fetch = mockFetch;
137
138 await executeLlmMethod(llm, methodToTest, params);
139 assertFetchCall(mockFetch, expectedRequest);
140}
141
142describe("ContinueProxy", () => {
143 afterEach(() => {
144 vi.clearAllMocks();
145 });
146
147 test("rerank should send a valid request", async () => {
148 const proxy = new ContinueProxy({
149 apiKey: "test-api-key",
150 model: "test-model",
151 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
152 });
153
154 await runLlmTest({
155 llm: proxy,
156 methodToTest: "rerank",
157 params: [
158 "test query",
159 [{ content: "document1" }, { content: "document2" }],
160 ],
161 expectedRequest: {
162 url: "https://proxy.continue.dev/model-proxy/v1/rerank",
163 method: "POST",
164 headers: {
165 "Content-Type": "application/json",
166 Authorization: "Bearer test-api-key",
167 },
168 body: {
169 query: "test query",
170 documents: ["document1", "document2"],
171 model: "test-model",
172 continueProperties: {
173 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
174 orgScopeId: null,
175 },
176 },
177 },
178 mockResponse: {
179 data: [
180 { index: 0, relevance_score: 0.9 },
181 { index: 1, relevance_score: 0.1 },
182 ],
183 },
184 });
185 });
186
187 test("streamChat should send a valid request", async () => {
188 const proxy = new ContinueProxy({
189 apiKey: "test-api-key",
190 model: "test-model",
191 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
192 });
193
194 await runLlmTest({
195 llm: proxy,
196 methodToTest: "streamChat",
197 params: [[{ role: "user", content: "hello" }]],
198 expectedRequest: {
199 url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
200 method: "POST",
201 headers: {
202 "Content-Type": "application/json",
203 Authorization: "Bearer test-api-key",
204 "api-key": "test-api-key",
205 "x-continue-unique-id": "NOT_UNIQUE",
206 },
207 body: {
208 model: "test-model",
209 messages: [{ role: "user", content: "hello" }],
210 max_tokens: 4096,
211 stream: true,
212 continueProperties: {
213 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
214 orgScopeId: null,
215 },
216 },
217 },
218 mockStream: [
219 '{"choices": [{"delta": {"content": "response"}}]}',
220 "[DONE]",
221 ],
222 });
223 });
224
225 test("chat should send a valid request", async () => {
226 const proxy = new ContinueProxy({
227 apiKey: "test-api-key",
228 model: "test-model",
229 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
230 });
231
232 await runLlmTest({
233 llm: proxy,
234 methodToTest: "chat",
235 params: [[{ role: "user", content: "hello" }]],
236 expectedRequest: {
237 url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
238 method: "POST",
239 headers: {
240 "Content-Type": "application/json",
241 Authorization: "Bearer test-api-key",
242 "api-key": "test-api-key",
243 "x-continue-unique-id": "NOT_UNIQUE",
244 },
245 body: {
246 model: "test-model",
247 messages: [{ role: "user", content: "hello" }],
248 max_tokens: 4096,
249 stream: true,
250 continueProperties: {
251 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
252 orgScopeId: null,
253 },
254 },
255 },
256 mockStream: [
257 '{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
258 "[DONE]",
259 ],
260 });
261 });
262
263 test("streamComplete should send a valid request", async () => {
264 const proxy = new ContinueProxy({
265 apiKey: "test-api-key",
266 model: "test-model",
267 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
268 });
269
270 await runLlmTest({
271 llm: proxy,
272 methodToTest: "streamComplete",
273 params: ["Complete this: Hello"],
274 expectedRequest: {
275 url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
276 method: "POST",
277 headers: {
278 "Content-Type": "application/json",
279 Authorization: "Bearer test-api-key",
280 "api-key": "test-api-key",
281 "x-continue-unique-id": "NOT_UNIQUE",
282 },
283 body: {
284 model: "test-model",
285 messages: [{ role: "user", content: "Complete this: Hello" }],
286 max_tokens: 4096,
287 stream: true,
288 continueProperties: {
289 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
290 orgScopeId: null,
291 },
292 },
293 },
294 mockStream: [
295 '{"choices": [{"delta": {"content": " world!"}}]}',
296 "[DONE]",
297 ],
298 });
299 });
300
301 test("complete should send a valid request", async () => {
302 const proxy = new ContinueProxy({
303 apiKey: "test-api-key",
304 model: "test-model",
305 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
306 });
307
308 await runLlmTest({
309 llm: proxy,
310 methodToTest: "complete",
311 params: ["Complete this: Hello"],
312 expectedRequest: {
313 url: "https://proxy.continue.dev/model-proxy/v1/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 "x-continue-unique-id": "NOT_UNIQUE",
320 },
321 body: {
322 model: "test-model",
323 messages: [{ role: "user", content: "Complete this: Hello" }],
324 max_tokens: 4096,
325 stream: true,
326 continueProperties: {
327 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
328 orgScopeId: null,
329 },
330 },
331 },
332 mockStream: [
333 '{"choices": [{"delta": {"content": " world!"}}]}',
334 "[DONE]",
335 ],
336 });
337 });
338
339 test("streamFim should send a valid request", async () => {
340 const proxy = new ContinueProxy({
341 apiKey: "test-api-key",
342 model: "test-model",
343 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
344 });
345
346 await runLlmTest({
347 llm: proxy,
348 methodToTest: "streamFim",
349 params: ["function test() {\n ", "\n}"],
350 expectedRequest: {
351 url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
352 method: "POST",
353 headers: {
354 "Content-Type": "application/json",
355 Accept: "application/json",
356 "x-api-key": "test-api-key",
357 Authorization: "Bearer test-api-key",
358 },
359 body: {
360 model: "test-model",
361 prompt: "function test() {\n ",
362 suffix: "\n}",
363 max_tokens: 4096,
364 stream: true,
365 continueProperties: {
366 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
367 orgScopeId: null,
368 },
369 },
370 },
371 mockStream: [
372 '{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
373 "[DONE]",
374 ],
375 });
376 });
377
378 test("embed should send a valid request", async () => {
379 const proxy = new ContinueProxy({
380 apiKey: "test-api-key",
381 model: "test-model",
382 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
383 });
384
385 await runLlmTest({
386 llm: proxy,
387 methodToTest: "embed",
388 params: [["text to embed", "another text"]],
389 expectedRequest: {
390 url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
391 method: "POST",
392 headers: {
393 "Content-Type": "application/json",
394 Authorization: "Bearer test-api-key",
395 "api-key": "test-api-key",
396 },
397 body: {
398 input: ["text to embed", "another text"],
399 model: "test-model",
400 continueProperties: {
401 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
402 orgScopeId: null,
403 },
404 },
405 },
406 mockResponse: {
407 data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
408 },
409 });
410 });
411
412 test("listModels should send a valid request", async () => {
413 const proxy = new ContinueProxy({
414 apiKey: "test-api-key",
415 model: "test-model",
416 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
417 });
418
419 await runLlmTest({
420 llm: proxy,
421 methodToTest: "listModels",
422 params: [],
423 expectedRequest: {
424 url: "https://proxy.continue.dev/model-proxy/v1/models",
425 method: "GET",
426 headers: {
427 "Content-Type": "application/json",
428 Authorization: "Bearer test-api-key",
429 "api-key": "test-api-key",
430 },
431 },
432 mockResponse: {
433 data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
434 },
435 });
436 });
437
438 describe("Different provider configurations", () => {
439 test("should handle on-prem proxy URL", async () => {
440 const proxy = new ContinueProxy({
441 apiKey: "test-api-key",
442 model: "test-model",
443 onPremProxyUrl: "https://my-proxy.company.com/",
444 });
445
446 await runLlmTest({
447 llm: proxy,
448 methodToTest: "rerank",
449 params: [
450 "test query",
451 [{ content: "document1" }, { content: "document2" }],
452 ],
453 expectedRequest: {
454 url: "https://my-proxy.company.com/model-proxy/v1/rerank",
455 method: "POST",
456 headers: {
457 "Content-Type": "application/json",
458 Authorization: "Bearer test-api-key",
459 },
460 body: {
461 query: "test query",
462 documents: ["document1", "document2"],
463 model: "test-model",
464 continueProperties: {
465 apiBase: undefined,
466 apiKeyLocation: undefined,
467 env: undefined,
468 envSecretLocations: undefined,
469 orgScopeId: null,
470 },
471 },
472 },
473 mockResponse: {
474 data: [
475 { index: 0, relevance_score: 0.9 },
476 { index: 1, relevance_score: 0.1 },
477 ],
478 },
479 });
480 });
481
482 test("should handle environment variables", async () => {
483 const proxy = new ContinueProxy({
484 apiKey: "test-api-key",
485 model: "test-model",
486 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
487 env: {
488 CUSTOM_VAR: "custom-value",
489 ANOTHER_VAR: "another-value",
490 },
491 });
492
493 await runLlmTest({
494 llm: proxy,
495 methodToTest: "streamChat",
496 params: [[{ role: "user", content: "hello" }]],
497 expectedRequest: {
498 url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
499 method: "POST",
500 headers: {
501 "Content-Type": "application/json",
502 Authorization: "Bearer test-api-key",
503 "api-key": "test-api-key",
504 "x-continue-unique-id": "NOT_UNIQUE",
505 },
506 body: {
507 model: "test-model",
508 messages: [{ role: "user", content: "hello" }],
509 max_tokens: 4096,
510 stream: true,
511 continueProperties: {
512 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
513 env: {
514 CUSTOM_VAR: "custom-value",
515 ANOTHER_VAR: "another-value",
516 },
517 orgScopeId: null,
518 },
519 },
520 },
521 mockStream: [
522 '{"choices": [{"delta": {"content": "response"}}]}',
523 "[DONE]",
524 ],
525 });
526 });
527
528 test("should handle API key location", async () => {
529 const proxy = new ContinueProxy({
530 apiKey: "test-api-key",
531 model: "test-model",
532 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
533 apiKeyLocation: "env:OPENAI_API_KEY",
534 });
535
536 await runLlmTest({
537 llm: proxy,
538 methodToTest: "embed",
539 params: [["test text"]],
540 expectedRequest: {
541 url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
542 method: "POST",
543 headers: {
544 "Content-Type": "application/json",
545 Authorization: "Bearer test-api-key",
546 "api-key": "test-api-key",
547 },
548 body: {
549 input: ["test text"],
550 model: "test-model",
551 continueProperties: {
552 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
553 apiKeyLocation: "env:OPENAI_API_KEY",
554 env: undefined,
555 envSecretLocations: undefined,
556 orgScopeId: null,
557 },
558 },
559 },
560 mockResponse: {
561 data: [{ embedding: [0.1, 0.2, 0.3] }],
562 },
563 });
564 });
565
566 test("should handle env secret locations", async () => {
567 const proxy = new ContinueProxy({
568 apiKey: "test-api-key",
569 model: "test-model",
570 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
571 envSecretLocations: {
572 AZURE_API_KEY: "env:AZURE_API_KEY",
573 AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
574 },
575 });
576
577 await runLlmTest({
578 llm: proxy,
579 methodToTest: "streamFim",
580 params: ["const x = ", ";"],
581 expectedRequest: {
582 url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
583 method: "POST",
584 headers: {
585 "Content-Type": "application/json",
586 Accept: "application/json",
587 "x-api-key": "test-api-key",
588 Authorization: "Bearer test-api-key",
589 },
590 body: {
591 model: "test-model",
592 prompt: "const x = ",
593 suffix: ";",
594 max_tokens: 4096,
595 stream: true,
596 continueProperties: {
597 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
598 envSecretLocations: {
599 AZURE_API_KEY: "env:AZURE_API_KEY",
600 AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
601 },
602 orgScopeId: null,
603 },
604 },
605 },
606 mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
607 });
608 });
609
610 test("should handle organization scope ID", async () => {
611 const proxy = new ContinueProxy({
612 apiKey: "test-api-key",
613 model: "test-model",
614 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
615 orgScopeId: "org_12345",
616 });
617
618 await runLlmTest({
619 llm: proxy,
620 methodToTest: "listModels",
621 params: [],
622 expectedRequest: {
623 url: "https://proxy.continue.dev/model-proxy/v1/models",
624 method: "GET",
625 headers: {
626 "Content-Type": "application/json",
627 Authorization: "Bearer test-api-key",
628 "api-key": "test-api-key",
629 },
630 },
631 mockResponse: {
632 data: [{ id: "gpt-4" }],
633 },
634 });
635 });
636 });
637
638 describe("Edge cases", () => {
639 test("should handle empty chunks array for rerank", async () => {
640 const proxy = new ContinueProxy({
641 apiKey: "test-api-key",
642 model: "test-model",
643 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
644 });
645
646 await runLlmTest({
647 llm: proxy,
648 methodToTest: "rerank",
649 params: ["test query", []],
650 expectedRequest: {
651 url: "https://proxy.continue.dev/model-proxy/v1/rerank",
652 method: "POST",
653 headers: {
654 "Content-Type": "application/json",
655 Authorization: "Bearer test-api-key",
656 },
657 body: {
658 query: "test query",
659 documents: [],
660 model: "test-model",
661 continueProperties: {
662 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
663 apiKeyLocation: undefined,
664 env: undefined,
665 envSecretLocations: undefined,
666 orgScopeId: null,
667 },
668 },
669 },
670 mockResponse: {
671 data: [],
672 },
673 });
674 });
675
676 test("should handle complex chat messages", async () => {
677 const proxy = new ContinueProxy({
678 apiKey: "test-api-key",
679 model: "test-model",
680 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
681 });
682
683 const complexMessages = [
684 { role: "system", content: "You are a helpful assistant." },
685 { role: "user", content: "Hello!" },
686 { role: "assistant", content: "Hi there! How can I help you today?" },
687 { role: "user", content: "What's the weather like?" },
688 ];
689
690 await runLlmTest({
691 llm: proxy,
692 methodToTest: "streamChat",
693 params: [complexMessages],
694 expectedRequest: {
695 url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
696 method: "POST",
697 headers: {
698 "Content-Type": "application/json",
699 Authorization: "Bearer test-api-key",
700 "api-key": "test-api-key",
701 "x-continue-unique-id": "NOT_UNIQUE",
702 },
703 body: {
704 model: "test-model",
705 messages: complexMessages,
706 max_tokens: 4096,
707 stream: true,
708 continueProperties: {
709 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
710 orgScopeId: null,
711 },
712 },
713 },
714 mockStream: [
715 '{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
716 "[DONE]",
717 ],
718 });
719 });
720
721 test("should handle single embedding chunk", async () => {
722 const proxy = new ContinueProxy({
723 apiKey: "test-api-key",
724 model: "test-model",
725 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
726 });
727
728 await runLlmTest({
729 llm: proxy,
730 methodToTest: "embed",
731 params: [["single text"]],
732 expectedRequest: {
733 url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
734 method: "POST",
735 headers: {
736 "Content-Type": "application/json",
737 Authorization: "Bearer test-api-key",
738 "api-key": "test-api-key",
739 },
740 body: {
741 input: ["single text"],
742 model: "test-model",
743 continueProperties: {
744 apiBase: "https://proxy.continue.dev/model-proxy/v1/",
745 apiKeyLocation: undefined,
746 env: undefined,
747 envSecretLocations: undefined,
748 orgScopeId: null,
749 },
750 },
751 },
752 mockResponse: {
753 data: [{ embedding: [0.1, 0.2, 0.3] }],
754 },
755 });
756 });
757 });
758});