90 lines
2.3 KiB
TypeScript
90 lines
2.3 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { LlmClient } from "./llm-client.js";
|
|
import type { ChatCompletionResponse } from "./types.js";
|
|
|
|
function okResponse(content = "ok"): Response {
|
|
const payload: ChatCompletionResponse = {
|
|
choices: [
|
|
{
|
|
finish_reason: "stop",
|
|
message: {
|
|
content,
|
|
role: "assistant",
|
|
},
|
|
},
|
|
],
|
|
model: "test-model",
|
|
};
|
|
|
|
return new Response(JSON.stringify(payload), {
|
|
headers: { "content-type": "application/json" },
|
|
status: 200,
|
|
});
|
|
}
|
|
|
|
function stringifyFetchUrl(input: string | URL | Request): string {
|
|
if (typeof input === "string") {
|
|
return input;
|
|
}
|
|
if (input instanceof URL) {
|
|
return input.toString();
|
|
}
|
|
return input.url;
|
|
}
|
|
|
|
describe("LlmClient endpoint normalization", () => {
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
it("normalizes OpenRouter API base URLs to chat completions", async () => {
|
|
const urls: string[] = [];
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn((url: string | URL | Request) => {
|
|
urls.push(stringifyFetchUrl(url));
|
|
return Promise.resolve(okResponse());
|
|
}),
|
|
);
|
|
const client = new LlmClient({
|
|
endpoints: [{ provider: "openrouter", url: "https://openrouter.ai/api/v1" }],
|
|
providerApiKeys: { openrouter: "test-key" },
|
|
});
|
|
|
|
const result = await client.chatCompletion([
|
|
{ content: "hi", role: "user" },
|
|
]);
|
|
|
|
expect(result?.content).toBe("ok");
|
|
expect(urls).toEqual(["https://openrouter.ai/api/v1/chat/completions"]);
|
|
});
|
|
|
|
it("preserves explicit chat completions URLs", async () => {
|
|
const urls: string[] = [];
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn((url: string | URL | Request) => {
|
|
urls.push(stringifyFetchUrl(url));
|
|
return Promise.resolve(okResponse());
|
|
}),
|
|
);
|
|
const client = new LlmClient({
|
|
endpoints: [
|
|
{
|
|
provider: "openrouter",
|
|
url: "https://openrouter.ai/api/v1/chat/completions",
|
|
},
|
|
],
|
|
providerApiKeys: { openrouter: "test-key" },
|
|
});
|
|
|
|
const result = await client.chatCompletion([
|
|
{ content: "hi", role: "user" },
|
|
]);
|
|
|
|
expect(result?.content).toBe("ok");
|
|
expect(urls).toEqual(["https://openrouter.ai/api/v1/chat/completions"]);
|
|
});
|
|
});
|