Merge pull request #6686 from continuedev/openai-adapters-tests
openai adapters tests
This commit is contained in:
commit
b26dcb5cae
25 changed files with 5019 additions and 24 deletions
3
.github/workflows/pr_checks.yaml
vendored
3
.github/workflows/pr_checks.yaml
vendored
|
|
@ -613,6 +613,9 @@ jobs:
|
|||
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$FILES" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
|
||||
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
|
||||
- name: Debug Outputs
|
||||
run: |
|
||||
|
|
|
|||
|
|
@ -19,5 +19,13 @@
|
|||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.vitest.ts"],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ describe("DocsCrawler", () => {
|
|||
};
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
describe.skip("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
|
|
|
|||
495
core/llm/llms/Anthropic.vitest.ts
Normal file
495
core/llm/llms/Anthropic.vitest.ts
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
import Anthropic from "./Anthropic.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;
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("Anthropic", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Complete this: Hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Complete this: Hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different configurations", () => {
|
||||
test("should handle system message", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Hello!" }],
|
||||
},
|
||||
],
|
||||
system: "You are a helpful assistant.",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tool calls", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
const tools = [
|
||||
{
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "What's the weather in New York?" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "What's the weather in New York?" },
|
||||
],
|
||||
},
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}',
|
||||
'{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle custom max tokens", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 1000 },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 1000,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error handling", () => {
|
||||
test("should throw error when API key is missing", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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:12434/engines/v1/",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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 } = {
|
||||
|
|
|
|||
12
core/llm/llms/Fireworks.vitest.ts
Normal file
12
core/llm/llms/Fireworks.vitest.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
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",
|
||||
},
|
||||
});
|
||||
|
|
@ -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.kindo.ai/v1/",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE",
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ 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";
|
||||
static embeddingsApiEndpoint = "https://api.gcp.ncompass.tech/v1/embeddings";
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
|
||||
|
|
|
|||
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
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": "mistral-8x7b",
|
||||
"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": "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": "codellama-7b",
|
||||
"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": "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",
|
||||
},
|
||||
});
|
||||
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
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": "codellama-7b",
|
||||
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
|
||||
"mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
},
|
||||
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": "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",
|
||||
},
|
||||
});
|
||||
|
||||
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/",
|
||||
customStreamCompleteEndpoint: "completions",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(SiliconFlow, {
|
||||
providerName: "siliconflow",
|
||||
defaultApiBase: "https://api.siliconflow.cn/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Kindo, {
|
||||
providerName: "kindo",
|
||||
defaultApiBase: "https://llm.kindo.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Azure, {
|
||||
providerName: "azure",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Inception, {
|
||||
providerName: "inception",
|
||||
defaultApiBase: "https://api.inceptionlabs.ai/v1/",
|
||||
customBodyOptions: {
|
||||
temperature: 0.0,
|
||||
presence_penalty: 1.5,
|
||||
stop: ["<|endoftext|>"],
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Docker, {
|
||||
providerName: "docker",
|
||||
defaultApiBase: "http://localhost:12434/engines/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/",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(NCompass, {
|
||||
providerName: "ncompass",
|
||||
defaultApiBase: "https://api.ncompass.tech/v1/",
|
||||
customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
});
|
||||
|
||||
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/v1/",
|
||||
});
|
||||
427
core/llm/llms/OpenAI.vitest.ts
Normal file
427
core/llm/llms/OpenAI.vitest.ts
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
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,
|
||||
max_completion_tokens: 100,
|
||||
},
|
||||
},
|
||||
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: {} },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
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(
|
||||
|
|
|
|||
93
core/llm/llms/llmTestHarness.ts
Normal file
93
core/llm/llms/llmTestHarness.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { expect, jest } from "@jest/globals";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
export 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?: string[]; // array of string chunks for SSE
|
||||
}
|
||||
|
||||
export async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = jest.fn<any>();
|
||||
|
||||
if (mockStream) {
|
||||
const encoder = new TextEncoder();
|
||||
let streamIndex = 0;
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
mockStream.forEach((chunk) => {
|
||||
controller.enqueue(new TextEncoder().encode(chunk));
|
||||
});
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
llm.fetch = mockFetch;
|
||||
|
||||
// @ts-ignore
|
||||
if (typeof llm[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const result = await llm[methodToTest](...params);
|
||||
|
||||
if (mockStream) {
|
||||
// Consume the stream to ensure it's processed correctly
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(expectedRequest.headers);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal file
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal file
|
|
@ -0,0 +1,758 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../../index.js";
|
||||
import ContinueProxy from "./ContinueProxy.js";
|
||||
|
||||
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
|
||||
const mod = (await importOriginal()) as any;
|
||||
return {
|
||||
...mod,
|
||||
parseProxyModelName: vi.fn(() => ({
|
||||
provider: "test-provider",
|
||||
model: "test-model",
|
||||
ownerSlug: "test-owner",
|
||||
packageSlug: "test-package",
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("ContinueProxy", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("rerank should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamFim should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["function test() {\n ", "\n}"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "function test() {\n ",
|
||||
suffix: "\n}",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["text to embed", "another text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["text to embed", "another text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("listModels should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different provider configurations", () => {
|
||||
test("should handle on-prem proxy URL", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
onPremProxyUrl: "https://my-proxy.company.com/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: undefined,
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle environment variables", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle API key location", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["test text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["test text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle env secret locations", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["const x = ", ";"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "const x = ",
|
||||
suffix: ";",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle organization scope ID", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: "org_12345",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
test("should handle empty chunks array for rerank", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: ["test query", []],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: [],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle complex chat messages", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
const complexMessages = [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
{ role: "assistant", content: "Hi there! How can I help you today?" },
|
||||
{ role: "user", content: "What's the weather like?" },
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [complexMessages],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: complexMessages,
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle single embedding chunk", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["single text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["single text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
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;
|
||||
customBodyOptions?: any;
|
||||
}
|
||||
|
||||
function getExpectedUrl(
|
||||
config: OpenAISubclassConfig,
|
||||
endpoint: string,
|
||||
model: string = "gpt-4",
|
||||
) {
|
||||
let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/";
|
||||
if (config.providerName === "azure") {
|
||||
return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`;
|
||||
} else if (config.providerName === "ncompass") {
|
||||
return `${baseUrl}${endpoint}`;
|
||||
}
|
||||
return `${baseUrl}${endpoint}`;
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
if (config.defaultApiBase) {
|
||||
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 || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "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,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
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 || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "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,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
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 || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(
|
||||
config,
|
||||
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,
|
||||
...config.customBodyOptions,
|
||||
}
|
||||
: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
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 || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "complete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "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,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
// Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint)
|
||||
if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url:
|
||||
config.customEmbeddingsUrl ||
|
||||
`${config.defaultApiBase || "https://api.openai.com/v1/"}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] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
3
core/package-lock.json
generated
3
core/package-lock.json
generated
|
|
@ -190,7 +190,8 @@
|
|||
"@types/json-schema": "^7.0.15",
|
||||
"cross-env": "^7.0.3",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
"ts-node": "^10.9.2",
|
||||
"vitest": "^1.6.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
|
|
|
|||
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"name": "wt-openai-adapters-tests",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
1522
packages/openai-adapters/package-lock.json
generated
1522
packages/openai-adapters/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -6,7 +6,7 @@
|
|||
"types": "dist/index.d.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
||||
"test": "vitest",
|
||||
"build": "tsc"
|
||||
},
|
||||
"author": "Nate Sesti and Ty Dunn",
|
||||
|
|
@ -30,6 +30,7 @@
|
|||
"@types/json-schema": "^7.0.15",
|
||||
"cross-env": "^7.0.3",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
"ts-node": "^10.9.2",
|
||||
"vitest": "^1.6.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
321
packages/openai-adapters/src/test/adapter-test-utils.ts
Normal file
321
packages/openai-adapters/src/test/adapter-test-utils.ts
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { BaseLlmApi } from "../apis/base.js";
|
||||
import { LLMConfig } from "../types.js";
|
||||
import { constructLlmApi } from "../index.js";
|
||||
|
||||
interface AdapterTestCase {
|
||||
config: LLMConfig;
|
||||
methodToTest: keyof BaseLlmApi;
|
||||
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 executeAdapterMethod(
|
||||
api: BaseLlmApi,
|
||||
methodToTest: keyof BaseLlmApi,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (api as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the adapter instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (api as any)[methodToTest](...params);
|
||||
|
||||
// If it's a generator/async iterator, consume it to trigger the HTTP request
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
// Just consume the generator to trigger the request
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
export async function runAdapterTest(testCase: AdapterTestCase) {
|
||||
const {
|
||||
config,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
// Mock fetch globally before constructing the API
|
||||
vi.stubGlobal("fetch", mockFetch);
|
||||
|
||||
// For non-OpenAI adapters, mock the fetch package
|
||||
const fetchPackage = await import("@continuedev/fetch");
|
||||
if (fetchPackage.fetchwithRequestOptions) {
|
||||
vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation(
|
||||
mockFetch as any,
|
||||
);
|
||||
}
|
||||
|
||||
const api = constructLlmApi(config);
|
||||
if (!api) {
|
||||
throw new Error(`Failed to construct API for provider: ${config.provider}`);
|
||||
}
|
||||
|
||||
// For OpenAI adapters, we need to replace the fetch on the OpenAI client
|
||||
if ((api as any).openai) {
|
||||
(api as any).openai.fetch = mockFetch;
|
||||
}
|
||||
|
||||
await executeAdapterMethod(api, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
export interface AdapterTestConfig {
|
||||
providerName: string;
|
||||
config: LLMConfig;
|
||||
expectedApiBase: string;
|
||||
customHeaders?: Record<string, string>;
|
||||
customBodyOptions?: any;
|
||||
}
|
||||
|
||||
export const createAdapterTests = (testConfig: AdapterTestConfig) => {
|
||||
describe(testConfig.providerName, () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("should construct API correctly", () => {
|
||||
const api = constructLlmApi(testConfig.config);
|
||||
expect(api).toBeDefined();
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: testConfig.config,
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${testConfig.expectedApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
...testConfig.customHeaders,
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
...testConfig.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
id: "test-id",
|
||||
object: "chat.completion",
|
||||
created: 1234567890,
|
||||
model: "gpt-4",
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello! How can I help you today?",
|
||||
},
|
||||
finish_reason: "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: 10,
|
||||
completion_tokens: 15,
|
||||
total_tokens: 25,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: testConfig.config,
|
||||
methodToTest: "chatCompletionStream",
|
||||
params: [
|
||||
{
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${testConfig.expectedApiBase}chat/completions`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
...testConfig.customHeaders,
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
...testConfig.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{
|
||||
id: "test-id",
|
||||
object: "chat.completion.chunk",
|
||||
created: 1234567890,
|
||||
model: "gpt-4",
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: { content: "Hello" },
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "test-id",
|
||||
object: "chat.completion.chunk",
|
||||
created: 1234567890,
|
||||
model: "gpt-4",
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: { content: " world" },
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: testConfig.config,
|
||||
methodToTest: "embed",
|
||||
params: [
|
||||
{
|
||||
model: "text-embedding-ada-002",
|
||||
input: ["Hello", "World"],
|
||||
},
|
||||
],
|
||||
expectedRequest: {
|
||||
url: `${testConfig.expectedApiBase}embeddings`,
|
||||
method: "POST",
|
||||
headers: {
|
||||
...testConfig.customHeaders,
|
||||
},
|
||||
body: {
|
||||
model: "text-embedding-ada-002",
|
||||
input: ["Hello", "World"],
|
||||
encoding_format: "base64",
|
||||
...testConfig.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
object: "list",
|
||||
data: [
|
||||
{
|
||||
object: "embedding",
|
||||
embedding: [0.1, 0.2, 0.3],
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
object: "embedding",
|
||||
embedding: [0.4, 0.5, 0.6],
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
model: "text-embedding-ada-002",
|
||||
usage: {
|
||||
prompt_tokens: 6,
|
||||
total_tokens: 6,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
201
packages/openai-adapters/src/test/anthropic-adapter.vitest.ts
Normal file
201
packages/openai-adapters/src/test/anthropic-adapter.vitest.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { describe, test, vi, expect, afterEach } from "vitest";
|
||||
import { runAdapterTest } from "./adapter-test-utils.js";
|
||||
|
||||
// Mock the fetch package
|
||||
vi.mock("@continuedev/fetch", async () => {
|
||||
const actual = await vi.importActual("@continuedev/fetch");
|
||||
return {
|
||||
...actual,
|
||||
fetchwithRequestOptions: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("Anthropic Adapter Tests", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("should construct API correctly", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "anthropic",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
expect(api).toBeDefined();
|
||||
});
|
||||
|
||||
test("chatCompletionNonStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "anthropic",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
},
|
||||
methodToTest: "chatCompletionNonStream",
|
||||
params: [
|
||||
{
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
system: undefined,
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
max_tokens: 4096,
|
||||
stream: undefined,
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
id: "msg_test",
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Hello! How can I help you today?",
|
||||
},
|
||||
],
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
stop_reason: "end_turn",
|
||||
stop_sequence: null,
|
||||
usage: {
|
||||
input_tokens: 10,
|
||||
output_tokens: 15,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionStream should send a valid request", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "anthropic",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
},
|
||||
methodToTest: "chatCompletionStream",
|
||||
params: [
|
||||
{
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
system: undefined,
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{
|
||||
type: "content_block_delta",
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "Hello",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content_block_delta",
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: " world",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chatCompletionStream with system message should convert correctly", async () => {
|
||||
await runAdapterTest({
|
||||
config: {
|
||||
provider: "anthropic",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
},
|
||||
methodToTest: "chatCompletionStream",
|
||||
params: [
|
||||
{
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
messages: [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "hello" },
|
||||
],
|
||||
stream: true,
|
||||
},
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
system: [
|
||||
{
|
||||
type: "text",
|
||||
text: "You are a helpful assistant.",
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
],
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{
|
||||
type: "content_block_delta",
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "Hello",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should throw not implemented error", async () => {
|
||||
const { constructLlmApi } = await import("../index.js");
|
||||
const api = constructLlmApi({
|
||||
provider: "anthropic",
|
||||
apiKey: "test-api-key",
|
||||
});
|
||||
|
||||
await expect(
|
||||
api!.embed({
|
||||
model: "text-embedding-ada-002",
|
||||
input: ["Hello", "World"],
|
||||
}),
|
||||
).rejects.toThrow("Method not implemented.");
|
||||
});
|
||||
});
|
||||
28
packages/openai-adapters/src/test/openai-adapter.vitest.ts
Normal file
28
packages/openai-adapters/src/test/openai-adapter.vitest.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, vi } from "vitest";
|
||||
import { createAdapterTests } from "./adapter-test-utils.js";
|
||||
|
||||
// Mock the fetch package (not needed for OpenAI but required by the shared test utils)
|
||||
vi.mock("@continuedev/fetch", async () => {
|
||||
const actual = await vi.importActual("@continuedev/fetch");
|
||||
return {
|
||||
...actual,
|
||||
fetchwithRequestOptions: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("OpenAI Adapter Tests", () => {
|
||||
createAdapterTests({
|
||||
providerName: "openai",
|
||||
config: {
|
||||
provider: "openai",
|
||||
apiKey: "test-api-key",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
},
|
||||
expectedApiBase: "https://api.openai.com/v1/",
|
||||
customHeaders: {
|
||||
authorization: "Bearer test-api-key",
|
||||
"content-type": "application/json",
|
||||
accept: "application/json",
|
||||
},
|
||||
});
|
||||
});
|
||||
15
packages/openai-adapters/vitest.config.ts
Normal file
15
packages/openai-adapters/vitest.config.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "node",
|
||||
globals: true,
|
||||
testTimeout: 10000,
|
||||
include: ["src/**/*.test.{ts,tsx}", "src/**/*.vitest.{ts,tsx}"],
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"(.+)\\.js": "$1",
|
||||
},
|
||||
},
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue