more openai-compatible tests
This commit is contained in:
parent
9a5dde6619
commit
74c1b10c33
15 changed files with 1540 additions and 18 deletions
|
|
@ -13,6 +13,7 @@ class Azure extends OpenAI {
|
|||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
apiVersion: "2024-02-15-preview",
|
||||
apiType: "azure-openai",
|
||||
};
|
||||
|
|
@ -23,4 +24,4 @@ class Azure extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
export default Azure;
|
||||
export default Azure;
|
||||
|
|
@ -17,7 +17,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Docker extends OpenAI implements ModelInstaller {
|
||||
static providerName = "docker";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:12434/engines/v1",
|
||||
apiBase: "http://localhost:11434/v1/",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
|
|
@ -70,7 +70,7 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
private async ensureModelRunnerEnabled(): Promise<void> {
|
||||
try {
|
||||
// Check if the Model Runner service is running on the expected port
|
||||
const isRunning = await this.isPortBound(12434);
|
||||
const isRunning = await this.isPortBound(11434);
|
||||
|
||||
if (!isRunning) {
|
||||
console.log(
|
||||
|
|
@ -81,9 +81,9 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
"enable",
|
||||
"model-runner",
|
||||
"--tcp",
|
||||
"12434",
|
||||
"11434",
|
||||
]);
|
||||
console.log("Docker Model Runner has been enabled on port 12434");
|
||||
console.log("Docker Model Runner has been enabled on port 11434");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to enable Docker Model Runner:", error);
|
||||
|
|
@ -224,4 +224,4 @@ class Docker extends OpenAI implements ModelInstaller {
|
|||
}
|
||||
}
|
||||
|
||||
export default Docker;
|
||||
export default Docker;
|
||||
|
|
@ -5,7 +5,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Fireworks extends OpenAI {
|
||||
static providerName = "fireworks";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.fireworks.ai/inference/v1",
|
||||
apiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
};
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
|
|
|
|||
11
core/llm/llms/Fireworks.vitest.ts
Normal file
11
core/llm/llms/Fireworks.vitest.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import Fireworks from "./Fireworks.js";
|
||||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
|
||||
},
|
||||
modelConversionContent: "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
12
core/llm/llms/Groq.vitest.ts
Normal file
12
core/llm/llms/Groq.vitest.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
import Groq from "./Groq.js";
|
||||
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
"llama3-70b": "llama3-70b-8192",
|
||||
},
|
||||
});
|
||||
|
|
@ -18,7 +18,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Inception extends OpenAI {
|
||||
static providerName = "inception";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.inceptionlabs.ai/v1/",
|
||||
apiBase: "https://api.inception.ai/v1/",
|
||||
model: "mercury-coder-small",
|
||||
completionOptions: {
|
||||
temperature: 0.0,
|
||||
|
|
@ -69,4 +69,4 @@ class Inception extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
export default Inception;
|
||||
export default Inception;
|
||||
|
|
@ -5,7 +5,7 @@ import OpenAI from "./OpenAI";
|
|||
class Kindo extends OpenAI {
|
||||
static providerName = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
apiBase: "https://llm-router.kindo.ai/",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE",
|
||||
|
|
@ -14,4 +14,4 @@ class Kindo extends OpenAI {
|
|||
};
|
||||
}
|
||||
|
||||
export default Kindo;
|
||||
export default Kindo;
|
||||
|
|
@ -6,7 +6,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class NCompass extends OpenAI {
|
||||
static providerName = "ncompass";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.ncompass.tech/v1",
|
||||
apiBase: "https://api.ncompass.tech/v1/",
|
||||
};
|
||||
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
|
||||
|
||||
|
|
@ -63,4 +63,4 @@ class NCompass extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
export default NCompass;
|
||||
export default NCompass;
|
||||
|
|
@ -6,7 +6,7 @@ export class OVHcloud extends OpenAI {
|
|||
static providerName = "ovhcloud";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
|
||||
apiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/api/openai_compat/v1/",
|
||||
model: "Qwen2.5-Coder-32B-Instruct",
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
|
|
@ -39,4 +39,4 @@ export class OVHcloud extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
export default OVHcloud;
|
||||
export default OVHcloud;
|
||||
288
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
288
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
// Import core OpenAI-compatible providers
|
||||
import OpenAI from "./OpenAI.js";
|
||||
import Groq from "./Groq.js";
|
||||
import Fireworks from "./Fireworks.js";
|
||||
import Together from "./Together.js";
|
||||
import Deepseek from "./Deepseek.js";
|
||||
import OpenRouter from "./OpenRouter.js";
|
||||
import xAI from "./xAI.js";
|
||||
import Mistral from "./Mistral.js";
|
||||
import LMStudio from "./LMStudio.js";
|
||||
import Cerebras from "./Cerebras.js";
|
||||
import DeepInfra from "./DeepInfra.js";
|
||||
import Nvidia from "./Nvidia.js";
|
||||
|
||||
// Base OpenAI tests
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Core OpenAI-compatible providers
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
},
|
||||
modelConversionContent: "[INST] hello [/INST]",
|
||||
modelConversionMaxTokens: 4096,
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
|
||||
},
|
||||
modelConversionContent: "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Together, {
|
||||
providerName: "together",
|
||||
defaultApiBase: "https://api.together.xyz/v1/",
|
||||
modelConversions: {
|
||||
"codellama-7b": "togethercomputer/CodeLlama-7b-Instruct",
|
||||
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
customStreamCompleteEndpoint: "completions",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Deepseek, {
|
||||
providerName: "deepseek",
|
||||
defaultApiBase: "https://api.deepseek.com/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OpenRouter, {
|
||||
providerName: "openrouter",
|
||||
defaultApiBase: "https://openrouter.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(xAI, {
|
||||
providerName: "xAI",
|
||||
defaultApiBase: "https://api.x.ai/v1/",
|
||||
modelConversions: {
|
||||
"grok-beta": "grok-beta",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Mistral, {
|
||||
providerName: "mistral",
|
||||
defaultApiBase: "https://api.mistral.ai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-7b": "open-mistral-7b",
|
||||
"mistral-8x7b": "open-mixtral-8x7b",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LMStudio, {
|
||||
providerName: "lmstudio",
|
||||
defaultApiBase: "http://localhost:1234/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Cerebras, {
|
||||
providerName: "cerebras",
|
||||
defaultApiBase: "https://api.cerebras.ai/v1/",
|
||||
modelConversions: {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
},
|
||||
modelConversionContent: "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(DeepInfra, {
|
||||
providerName: "deepinfra",
|
||||
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
customEmbeddingsUrl: "https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "bearer test-api-key",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
inputs: ["Hello", "World"],
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nvidia, {
|
||||
providerName: "nvidia",
|
||||
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
input_type: "passage",
|
||||
truncate: "END",
|
||||
},
|
||||
});
|
||||
414
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
414
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
|
|
@ -0,0 +1,414 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
// Import all OpenAI-compatible providers
|
||||
import OpenAI from "./OpenAI.js";
|
||||
import Groq from "./Groq.js";
|
||||
import Fireworks from "./Fireworks.js";
|
||||
import Together from "./Together.js";
|
||||
import Deepseek from "./Deepseek.js";
|
||||
import OpenRouter from "./OpenRouter.js";
|
||||
import xAI from "./xAI.js";
|
||||
import Mistral from "./Mistral.js";
|
||||
import LMStudio from "./LMStudio.js";
|
||||
import Cerebras from "./Cerebras.js";
|
||||
import DeepInfra from "./DeepInfra.js";
|
||||
import Nvidia from "./Nvidia.js";
|
||||
import SambaNova from "./SambaNova.js";
|
||||
import Scaleway from "./Scaleway.js";
|
||||
import Venice from "./Venice.js";
|
||||
import Moonshot from "./Moonshot.js";
|
||||
import Novita from "./Novita.js";
|
||||
import SiliconFlow from "./SiliconFlow.js";
|
||||
import Kindo from "./Kindo.js";
|
||||
import Azure from "./Azure.js";
|
||||
import Inception from "./Inception.js";
|
||||
import Docker from "./Docker.js";
|
||||
import Voyage from "./Voyage.js";
|
||||
import Vllm from "./Vllm.js";
|
||||
import TextGenWebUI from "./TextGenWebUI.js";
|
||||
// import Relace from "./Relace.js"; // Skip - causing import issues
|
||||
import FunctionNetwork from "./FunctionNetwork.js";
|
||||
import NCompass from "./NCompass.js";
|
||||
import LlamaStack from "./LlamaStack.js";
|
||||
import Nebius from "./Nebius.js";
|
||||
import OVHcloud from "./OVHcloud.js";
|
||||
|
||||
// Base OpenAI tests
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ embedding: [0.1, 0.2, 0.3] },
|
||||
{ embedding: [0.4, 0.5, 0.6] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// OpenAI-compatible providers
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
"llama3-70b": "llama3-70b-8192",
|
||||
},
|
||||
modelConversionContent: "[INST] hello [/INST]",
|
||||
modelConversionMaxTokens: 4096,
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
|
||||
},
|
||||
modelConversionContent: "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Together, {
|
||||
providerName: "together",
|
||||
defaultApiBase: "https://api.together.xyz/v1/",
|
||||
modelConversions: {
|
||||
"codellama-7b": "togethercomputer/CodeLlama-7b-Instruct",
|
||||
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
|
||||
"mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Deepseek, {
|
||||
providerName: "deepseek",
|
||||
defaultApiBase: "https://api.deepseek.com/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OpenRouter, {
|
||||
providerName: "openrouter",
|
||||
defaultApiBase: "https://openrouter.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(xAI, {
|
||||
providerName: "xAI",
|
||||
defaultApiBase: "https://api.x.ai/v1/",
|
||||
modelConversions: {
|
||||
"grok-beta": "grok-beta",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Mistral, {
|
||||
providerName: "mistral",
|
||||
defaultApiBase: "https://api.mistral.ai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-7b": "open-mistral-7b",
|
||||
"mistral-8x7b": "open-mixtral-8x7b",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LMStudio, {
|
||||
providerName: "lmstudio",
|
||||
defaultApiBase: "http://localhost:1234/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Cerebras, {
|
||||
providerName: "cerebras",
|
||||
defaultApiBase: "https://api.cerebras.ai/v1/",
|
||||
modelConversions: {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
},
|
||||
modelConversionContent: "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(DeepInfra, {
|
||||
providerName: "deepinfra",
|
||||
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nvidia, {
|
||||
providerName: "nvidia",
|
||||
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(SambaNova, {
|
||||
providerName: "sambanova",
|
||||
defaultApiBase: "https://api.sambanova.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Scaleway, {
|
||||
providerName: "scaleway",
|
||||
defaultApiBase: "https://api.scaleway.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Venice, {
|
||||
providerName: "venice",
|
||||
defaultApiBase: "https://api.venice.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Moonshot, {
|
||||
providerName: "moonshot",
|
||||
defaultApiBase: "https://api.moonshot.cn/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Novita, {
|
||||
providerName: "novita",
|
||||
defaultApiBase: "https://api.novita.ai/v3/openai/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(SiliconFlow, {
|
||||
providerName: "siliconflow",
|
||||
defaultApiBase: "https://api.siliconflow.cn/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Kindo, {
|
||||
providerName: "kindo",
|
||||
defaultApiBase: "https://llm-router.kindo.ai/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Azure, {
|
||||
providerName: "azure",
|
||||
defaultApiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Inception, {
|
||||
providerName: "inception",
|
||||
defaultApiBase: "https://api.inception.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Docker, {
|
||||
providerName: "docker",
|
||||
defaultApiBase: "http://localhost:11434/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Voyage, {
|
||||
providerName: "voyage",
|
||||
defaultApiBase: "https://api.voyageai.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Vllm, {
|
||||
providerName: "vllm",
|
||||
defaultApiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(TextGenWebUI, {
|
||||
providerName: "text-gen-webui",
|
||||
defaultApiBase: "http://localhost:5000/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(FunctionNetwork, {
|
||||
providerName: "function-network",
|
||||
defaultApiBase: "https://api.function.network/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(NCompass, {
|
||||
providerName: "ncompass",
|
||||
defaultApiBase: "https://api.ncompass.tech/v1",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LlamaStack, {
|
||||
providerName: "llamastack",
|
||||
defaultApiBase: "http://localhost:8321/v1/openai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nebius, {
|
||||
providerName: "nebius",
|
||||
defaultApiBase: "https://api.studio.nebius.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OVHcloud, {
|
||||
providerName: "ovhcloud",
|
||||
defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/api/openai_compat/v1/",
|
||||
});
|
||||
|
|
@ -136,6 +136,7 @@ class OpenAI extends BaseLLM {
|
|||
): ChatCompletionCreateParams {
|
||||
const finalOptions = toChatBody(messages, options);
|
||||
|
||||
finalOptions.model = this._convertModelName(finalOptions.model);
|
||||
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini or o3-mini:
|
||||
|
|
@ -338,7 +339,7 @@ class OpenAI extends BaseLLM {
|
|||
return;
|
||||
}
|
||||
|
||||
const body = this._convertArgs(options, messages);
|
||||
const body = this.modifyChatBody(this._convertArgs(options, messages));
|
||||
|
||||
const response = await this.fetch(this._getEndpoint("chat/completions"), {
|
||||
method: "POST",
|
||||
|
|
|
|||
418
core/llm/llms/OpenAI.vitest.ts
Normal file
418
core/llm/llms/OpenAI.vitest.ts
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "complete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle O1 models correctly", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "o1-preview",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal, { maxTokens: 100 }],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "o1-preview",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tools", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
const tools = [
|
||||
{
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_function",
|
||||
description: "Test function",
|
||||
parameters: { type: "object", properties: {} },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal, { tools }],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_function",
|
||||
description: "Test function",
|
||||
parameters: { type: "object", properties: {} },
|
||||
},
|
||||
},
|
||||
],
|
||||
parallel_tool_calls: false,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "I'll help you" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle custom max tokens", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }], new AbortController().signal, { maxTokens: 500 }],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 500,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ embedding: [0.1, 0.2, 0.3] },
|
||||
{ embedding: [0.4, 0.5, 0.6] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -6,7 +6,7 @@ import OpenAI from "./OpenAI";
|
|||
class Venice extends OpenAI {
|
||||
static providerName = "venice";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.venice.ai/api/v1",
|
||||
apiBase: "https://api.venice.ai/api/v1/",
|
||||
};
|
||||
|
||||
protected _convertArgs(
|
||||
|
|
@ -27,4 +27,4 @@ class Venice extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
export default Venice;
|
||||
export default Venice;
|
||||
377
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
377
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../../index.js";
|
||||
import OpenAI from "../OpenAI.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
export interface OpenAISubclassConfig {
|
||||
providerName: string;
|
||||
defaultApiBase: string;
|
||||
modelConversions?: { [key: string]: string };
|
||||
customOptions?: any;
|
||||
modelConversionContent?: string;
|
||||
modelConversionMaxTokens?: number;
|
||||
customStreamCompleteEndpoint?: string;
|
||||
customEmbeddingsUrl?: string;
|
||||
customEmbeddingsHeaders?: { [key: string]: string };
|
||||
customEmbeddingsBody?: any;
|
||||
}
|
||||
|
||||
export const createOpenAISubclassTests = (
|
||||
ProviderClass: typeof OpenAI,
|
||||
config: OpenAISubclassConfig,
|
||||
) => {
|
||||
describe(config.providerName, () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("should have correct provider name", () => {
|
||||
expect(ProviderClass.providerName).toBe(config.providerName);
|
||||
});
|
||||
|
||||
test("should have correct default API base", () => {
|
||||
expect(ProviderClass.defaultOptions?.apiBase).toBe(config.defaultApiBase);
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${config.defaultApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${config.defaultApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: `${config.defaultApiBase}${config.customStreamCompleteEndpoint || "chat/completions"}`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: config.customStreamCompleteEndpoint === "completions" ? {
|
||||
model: "gpt-4",
|
||||
prompt: "Hello",
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
} : {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "complete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: `${config.defaultApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// Test model conversions if provided
|
||||
if (config.modelConversions) {
|
||||
test("should convert model names correctly", async () => {
|
||||
const testModel = Object.keys(config.modelConversions!)[0];
|
||||
const expectedModel = config.modelConversions![testModel];
|
||||
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: testModel,
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${config.defaultApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: expectedModel,
|
||||
messages: [{ role: "user", content: config.modelConversionContent || "[INST] hello [/INST]" }],
|
||||
stream: true,
|
||||
max_tokens: config.modelConversionMaxTokens || 4096,
|
||||
},
|
||||
},
|
||||
mockStream: [{ choices: [{ delta: { content: "Hello" } }] }],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: config.defaultApiBase,
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url: config.customEmbeddingsUrl || `${config.defaultApiBase}embeddings`,
|
||||
method: "POST",
|
||||
headers: config.customEmbeddingsHeaders || {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: config.customEmbeddingsBody || {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ embedding: [0.1, 0.2, 0.3] },
|
||||
{ embedding: [0.4, 0.5, 0.6] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
Loading…
Add table
Reference in a new issue