Elffuss BraidHub

kikocis/continue public

e31fcddb0dec · 7.4 KiBRawPermalink
1import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
2
3// Import core OpenAI-compatible providers
4import OpenAI from "./OpenAI.js";
5import Groq from "./Groq.js";
6import Fireworks from "./Fireworks.js";
7import Together from "./Together.js";
8import Deepseek from "./Deepseek.js";
9import OpenRouter from "./OpenRouter.js";
10import xAI from "./xAI.js";
11import Mistral from "./Mistral.js";
12import LMStudio from "./LMStudio.js";
13import Cerebras from "./Cerebras.js";
14import DeepInfra from "./DeepInfra.js";
15import Nvidia from "./Nvidia.js";
16
17// Base OpenAI tests
18import { afterEach, describe, expect, test, vi } from "vitest";
19import { ILLM } from "../../index.js";
20
21interface LlmTestCase {
22 llm: ILLM;
23 methodToTest: keyof ILLM;
24 params: any[];
25 expectedRequest: {
26 url: string;
27 method: string;
28 headers?: Record<string, string>;
29 body?: Record<string, any>;
30 };
31 mockResponse?: any;
32 mockStream?: any[];
33}
34
35function createMockStream(mockStream: any[]) {
36 const encoder = new TextEncoder();
37 return new ReadableStream({
38 start(controller) {
39 for (const chunk of mockStream) {
40 controller.enqueue(
41 encoder.encode(
42 `data: ${
43 typeof chunk === "string" ? chunk : JSON.stringify(chunk)
44 }\n\n`,
45 ),
46 );
47 }
48 controller.close();
49 },
50 });
51}
52
53function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
54 const mockFetch = vi.fn();
55
56 if (mockStream) {
57 const stream = createMockStream(mockStream);
58 mockFetch.mockResolvedValue(
59 new Response(stream, {
60 headers: {
61 "Content-Type": "text/event-stream",
62 },
63 }),
64 );
65 } else {
66 mockFetch.mockResolvedValue(
67 new Response(JSON.stringify(mockResponse), {
68 headers: { "Content-Type": "application/json" },
69 }),
70 );
71 }
72
73 return mockFetch;
74}
75
76function setupReadableStreamPolyfill() {
77 // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
78 // @ts-ignore
79 const originalFrom = ReadableStream.from;
80 // @ts-ignore
81 ReadableStream.from = (body) => {
82 if (body?.source) {
83 return body;
84 }
85 return originalFrom(body);
86 };
87}
88
89async function executeLlmMethod(
90 llm: ILLM,
91 methodToTest: keyof ILLM,
92 params: any[],
93) {
94 if (typeof (llm as any)[methodToTest] !== "function") {
95 throw new Error(
96 `Method ${String(methodToTest)} does not exist on the LLM instance.`,
97 );
98 }
99
100 const result = await (llm as any)[methodToTest](...params);
101 if (result?.next) {
102 for await (const _ of result) {
103 }
104 }
105}
106
107function assertFetchCall(mockFetch: any, expectedRequest: any) {
108 expect(mockFetch).toHaveBeenCalledTimes(1);
109 const [url, options] = mockFetch.mock.calls[0];
110
111 expect(url.toString()).toBe(expectedRequest.url);
112 expect(options.method).toBe(expectedRequest.method);
113
114 if (expectedRequest.headers) {
115 expect(options.headers).toEqual(
116 expect.objectContaining(expectedRequest.headers),
117 );
118 }
119
120 if (expectedRequest.body) {
121 const actualBody = JSON.parse(options.body as string);
122 expect(actualBody).toEqual(expectedRequest.body);
123 }
124}
125
126async function runLlmTest(testCase: LlmTestCase) {
127 const {
128 llm,
129 methodToTest,
130 params,
131 expectedRequest,
132 mockResponse,
133 mockStream,
134 } = testCase;
135
136 const mockFetch = setupMockFetch(mockResponse, mockStream);
137 setupReadableStreamPolyfill();
138
139 (llm as any).fetch = mockFetch;
140
141 // Disable OpenAI adapter to use our custom fetch mock
142 (llm as any).useOpenAIAdapterFor = [];
143
144 await executeLlmMethod(llm, methodToTest, params);
145 assertFetchCall(mockFetch, expectedRequest);
146}
147
148describe("OpenAI", () => {
149 afterEach(() => {
150 vi.clearAllMocks();
151 });
152
153 test("streamChat should send a valid request", async () => {
154 const openai = new OpenAI({
155 apiKey: "test-api-key",
156 model: "gpt-4",
157 apiBase: "https://api.openai.com/v1/",
158 });
159
160 await runLlmTest({
161 llm: openai,
162 methodToTest: "streamChat",
163 params: [
164 [{ role: "user", content: "hello" }],
165 new AbortController().signal,
166 ],
167 expectedRequest: {
168 url: "https://api.openai.com/v1/chat/completions",
169 method: "POST",
170 headers: {
171 "Content-Type": "application/json",
172 Authorization: "Bearer test-api-key",
173 "api-key": "test-api-key",
174 },
175 body: {
176 model: "gpt-4",
177 messages: [{ role: "user", content: "hello" }],
178 stream: true,
179 max_tokens: 2048,
180 },
181 },
182 mockStream: [
183 { choices: [{ delta: { content: "Hello" } }] },
184 { choices: [{ delta: { content: " world" } }] },
185 ],
186 });
187 });
188});
189
190// Core OpenAI-compatible providers
191createOpenAISubclassTests(Groq, {
192 providerName: "groq",
193 defaultApiBase: "https://api.groq.com/openai/v1/",
194 modelConversions: {
195 "mistral-8x7b": "mistral-8x7b",
196 "llama3-8b": "llama3-8b-8192",
197 },
198 modelConversionContent: "[INST] hello [/INST]",
199 modelConversionMaxTokens: 4096,
200});
201
202createOpenAISubclassTests(Fireworks, {
203 providerName: "fireworks",
204 defaultApiBase: "https://api.fireworks.ai/inference/v1/",
205 modelConversions: {
206 "starcoder-7b": "starcoder-7b",
207 },
208 modelConversionContent:
209 "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
210});
211
212createOpenAISubclassTests(Together, {
213 providerName: "together",
214 defaultApiBase: "https://api.together.xyz/v1/",
215 modelConversions: {
216 "codellama-7b": "codellama-7b",
217 "llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
218 },
219 modelConversionContent: "hello",
220 customStreamCompleteEndpoint: "completions",
221});
222
223createOpenAISubclassTests(Deepseek, {
224 providerName: "deepseek",
225 defaultApiBase: "https://api.deepseek.com/",
226});
227
228createOpenAISubclassTests(OpenRouter, {
229 providerName: "openrouter",
230 defaultApiBase: "https://openrouter.ai/api/v1/",
231});
232
233createOpenAISubclassTests(xAI, {
234 providerName: "xAI",
235 defaultApiBase: "https://api.x.ai/v1/",
236 modelConversions: {
237 "grok-beta": "grok-beta",
238 },
239 modelConversionContent: "hello",
240});
241
242createOpenAISubclassTests(Mistral, {
243 providerName: "mistral",
244 defaultApiBase: "https://api.mistral.ai/v1/",
245 modelConversions: {
246 "mistral-7b": "mistral-7b",
247 "mistral-8x7b": "open-mixtral-8x7b",
248 },
249 modelConversionContent: "hello",
250});
251
252createOpenAISubclassTests(LMStudio, {
253 providerName: "lmstudio",
254 defaultApiBase: "http://localhost:1234/v1/",
255});
256
257createOpenAISubclassTests(Cerebras, {
258 providerName: "cerebras",
259 defaultApiBase: "https://api.cerebras.ai/v1/",
260 modelConversions: {
261 "llama3.1-8b": "llama3.1-8b",
262 "llama3.1-70b": "llama3.1-70b",
263 },
264 modelConversionContent:
265 "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
266});
267
268createOpenAISubclassTests(DeepInfra, {
269 providerName: "deepinfra",
270 defaultApiBase: "https://api.deepinfra.com/v1/openai/",
271 customEmbeddingsUrl:
272 "https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
273 customEmbeddingsHeaders: {
274 Authorization: "bearer test-api-key",
275 },
276 customEmbeddingsBody: {
277 inputs: ["Hello", "World"],
278 },
279});
280
281createOpenAISubclassTests(Nvidia, {
282 providerName: "nvidia",
283 defaultApiBase: "https://integrate.api.nvidia.com/v1/",
284 customEmbeddingsHeaders: {
285 Authorization: "Bearer test-api-key",
286 "Content-Type": "application/json",
287 },
288 customEmbeddingsBody: {
289 input: ["Hello", "World"],
290 model: "text-embedding-ada-002",
291 input_type: "passage",
292 truncate: "END",
293 },
294});