File size: 9,312 Bytes
92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 ff49634 92a1d83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | import { describe, expect, it, beforeAll, afterAll } from "bun:test";
import { OpenAICompatibleClient } from "../client";
const BASE_URL = "https://api.openai.com/v1";
const API_KEY = "sk-test-key-12345";
const MODEL = "gpt-4";
type FetchFn = typeof globalThis.fetch;
/** Bun/TS types fetch as an object with static helpers (e.g. preconnect), not just a function. */
function asFetchMock(fn: (...args: Parameters<FetchFn>) => ReturnType<FetchFn>): FetchFn {
return fn as FetchFn;
}
function setMockFetch(fn: (...args: Parameters<FetchFn>) => ReturnType<FetchFn>): void {
globalThis.fetch = asFetchMock(fn);
}
function parseRequestBody(opts?: RequestInit): Record<string, unknown> {
if (opts?.body == null) {
throw new Error("Expected request body in mock fetch");
}
return JSON.parse(String(opts.body));
}
function makeMockStream(chunks: string[]): ReadableStream {
const encoder = new TextEncoder();
return new ReadableStream({
async start(controller) {
for (const chunk of chunks) {
controller.enqueue(encoder.encode(chunk));
}
controller.close();
},
});
}
function makeFetchMock(streamChunks: string[], status = 200): FetchFn {
return asFetchMock(async () =>
new Response(makeMockStream(streamChunks), {
status,
headers: { "content-type": "text/event-stream" },
}),
);
}
describe("OpenAICompatibleClient", () => {
let originalFetch: FetchFn;
beforeAll(() => {
originalFetch = globalThis.fetch;
});
afterAll(() => {
globalThis.fetch = originalFetch;
});
it("sends correct request and parses SSE response", async () => {
globalThis.fetch = makeFetchMock([
`data: ${JSON.stringify({ choices: [{ delta: { content: "Hello" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: { content: " World" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: {} }], usage: { total_tokens: 10 } })}\n`,
"data: [DONE]\n",
]);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
});
expect(result.content).toBe("Hello World");
});
it("calls onToken callback for each token", async () => {
globalThis.fetch = makeFetchMock([
`data: ${JSON.stringify({ choices: [{ delta: { content: "A" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: { content: "B" } }] })}\n`,
"data: [DONE]\n",
]);
const tokens: string[] = [];
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
await client.chatCompletion(
{ model: MODEL, messages: [{ role: "user", content: "Test" }] },
{ onToken: (t) => tokens.push(t) },
);
expect(tokens).toEqual(["A", "B"]);
});
it("returns usage from the last chunk", async () => {
globalThis.fetch = makeFetchMock([
`data: ${JSON.stringify({ choices: [{ delta: { content: "Hi" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: {} }], usage: { total_tokens: 5 } })}\n`,
"data: [DONE]\n",
]);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
});
expect(result.usage?.total_tokens).toBe(5);
});
it("throws on non-OK response", async () => {
setMockFetch(async () =>
new Response("Bad Request", { status: 400, headers: { "content-type": "text/plain" } }),
);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
expect(
client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
}),
).rejects.toThrow("400");
});
it("throws on empty response body", async () => {
setMockFetch(async () => new Response(null, { status: 200 }));
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
expect(
client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
}),
).rejects.toThrow("Empty response body");
});
it("throws on invalid base URL", async () => {
const client = new OpenAICompatibleClient("not-a-url", API_KEY);
expect(
client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
}),
).rejects.toThrow("Invalid base URL");
});
it("throws on metadata host (169.254.169.254)", async () => {
const client = new OpenAICompatibleClient("https://169.254.169.254/v1", API_KEY);
expect(
client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
}),
).rejects.toThrow("metadata/private network");
});
it("retries without response_format on 400 with response_format error", async () => {
let callCount = 0;
setMockFetch(async (_input, opts) => {
callCount++;
if (callCount === 1) {
const body = parseRequestBody(opts);
expect(body.response_format).toBeDefined();
return new Response("response_format is not supported", {
status: 400,
headers: { "content-type": "text/plain" },
});
}
const body = parseRequestBody(opts);
expect(body.response_format).toBeUndefined();
return new Response(makeMockStream([
`data: ${JSON.stringify({ choices: [{ delta: { content: "retried" } }] })}\n`,
"data: [DONE]\n",
]), {
status: 200,
headers: { "content-type": "text/event-stream" },
});
});
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
response_format: { type: "json_object" },
});
expect(callCount).toBe(2);
expect(result.content).toBe("retried");
});
it("retries with more tokens on truncated response", async () => {
let callCount = 0;
setMockFetch(async (_input, _opts) => {
callCount++;
const responseContent = callCount === 1
? `data: ${JSON.stringify({ choices: [{ delta: { content: '{"incomplete":' } }] })}\n` + "data: [DONE]\n"
: `data: ${JSON.stringify({ choices: [{ delta: { content: '{"complete": true}' } }] })}\n` + "data: [DONE]\n";
return new Response(makeMockStream([responseContent]), {
status: 200,
headers: { "content-type": "text/event-stream" },
});
});
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
max_tokens: 100,
});
expect(callCount).toBe(2);
expect(result.content).toBe('{"complete": true}');
});
it("strips reasoning blocks and returns JSON from GLM-style streams", async () => {
const json = '{"questions":[{"format":"mcq"}]}';
globalThis.fetch = makeFetchMock([
`data: ${JSON.stringify({ choices: [{ delta: { content: "<think>\nPlanning questions...\n</think>" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: { content: json } }] })}\n`,
"data: [DONE]\n",
]);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
});
expect(result.content).toBe(json);
});
it("ignores reasoning_content delta and keeps final content", async () => {
globalThis.fetch = makeFetchMock([
`data: ${JSON.stringify({ choices: [{ delta: { reasoning_content: "internal reasoning only" } }] })}\n`,
`data: ${JSON.stringify({ choices: [{ delta: { content: '{"ok":true}' } }] })}\n`,
"data: [DONE]\n",
]);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
});
expect(result.content).toBe('{"ok":true}');
});
it("throws on HTML error page in stream", async () => {
setMockFetch(async () =>
new Response(makeMockStream([
`data: ${JSON.stringify({ choices: [{ delta: { content: "<!DOCTYPE html><html><body>502 Bad Gateway</body></html>" } }] })}\n`,
"data: [DONE]\n",
]), {
status: 200,
headers: { "content-type": "text/event-stream" },
}),
);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
expect(
client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
}),
).rejects.toThrow("HTML");
});
it("falls back to non-stream JSON body when SSE yields no tokens", async () => {
const body = JSON.stringify({
choices: [{ message: { content: '{"questions":[]}' } }],
});
setMockFetch(async () =>
new Response(body, {
status: 200,
headers: { "content-type": "application/json" },
}),
);
const client = new OpenAICompatibleClient(BASE_URL, API_KEY);
const result = await client.chatCompletion({
model: MODEL,
messages: [{ role: "user", content: "Test" }],
});
expect(result.content).toBe('{"questions":[]}');
});
});
|