forked from Lilly-Protocol/agentlily-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai-compatible-provider.test.ts
More file actions
448 lines (396 loc) · 13.7 KB
/
Copy pathopenai-compatible-provider.test.ts
File metadata and controls
448 lines (396 loc) · 13.7 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import { afterEach, describe, expect, it, vi } from "vitest";
import {
OpenAICompatibleModelProvider,
type ModelPrompt
} from "../src/index.js";
describe("OpenAICompatibleModelProvider", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("validates configuration and throws on missing apiKey", () => {
expect(
() => new OpenAICompatibleModelProvider({ apiKey: "" })
).toThrowError("OpenAI-compatible provider requires a non-empty apiKey.");
expect(
() =>
new OpenAICompatibleModelProvider({
apiKey: " "
})
).toThrowError("OpenAI-compatible provider requires a non-empty apiKey.");
});
it("validates configuration and throws on invalid baseUrl", () => {
expect(
() =>
new OpenAICompatibleModelProvider({
apiKey: "valid-key",
baseUrl: "not-a-valid-url"
})
).toThrowError(
'Invalid baseUrl provided to OpenAICompatibleModelProvider: "not-a-valid-url".'
);
});
it("initializes with default options", () => {
const provider = new OpenAICompatibleModelProvider({
apiKey: "sk-test-key"
});
expect(provider.name).toBe("openai-compatible");
expect(provider.getBaseUrl()).toBe("https://api.openai.com/v1");
expect(provider.getModel()).toBe("gpt-4o-mini");
});
it("generates model response with mocked HTTP success", async () => {
const mockResponsePayload = {
id: "chatcmpl-test",
model: "gpt-4o-mini",
choices: [
{
index: 0,
message: {
role: "assistant",
content: "Autonomous payment prepared successfully."
},
finish_reason: "stop"
}
],
usage: {
prompt_tokens: 15,
completion_tokens: 8,
total_tokens: 23
}
};
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify(mockResponsePayload), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "sk-mock-key",
model: "gpt-4o-mini"
});
const prompt: ModelPrompt = {
instructions: "You are an autonomous Stellar agent.",
input: "Prepare 10 XLM payment to recipient."
};
const response = await provider.generate(prompt);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(fetchSpy).toHaveBeenCalledWith(
"https://api.openai.com/v1/chat/completions",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
"Content-Type": "application/json",
Authorization: "Bearer sk-mock-key"
}),
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: prompt.instructions },
{ role: "user", content: prompt.input }
]
})
})
);
expect(response.outputText).toBe(
"Autonomous payment prepared successfully."
);
expect(response.metadata).toEqual({
model: "gpt-4o-mini",
finishReason: "stop",
usage: {
prompt_tokens: 15,
completion_tokens: 8,
total_tokens: 23
}
});
});
it("supports custom baseUrl and custom headers", async () => {
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(
JSON.stringify({
model: "custom-llm",
choices: [{ message: { content: "Custom response" } }]
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "custom-token",
baseUrl: "https://custom-llm.example.com/v1/",
model: "custom-llm",
headers: { "X-Custom-Header": "custom-val" }
});
const response = await provider.generate({
instructions: "Instructions",
input: "Input"
});
expect(fetchSpy).toHaveBeenCalledWith(
"https://custom-llm.example.com/v1/chat/completions",
expect.objectContaining({
headers: expect.objectContaining({
"X-Custom-Header": "custom-val",
Authorization: "Bearer custom-token"
})
})
);
expect(response.outputText).toBe("Custom response");
});
it("passes AbortSignal timeout when timeoutMs is configured", async () => {
const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(
JSON.stringify({
choices: [{ message: { content: "Timed response" } }]
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "test-key",
timeoutMs: 5000
});
await provider.generate({
instructions: "Instructions",
input: "Input"
});
expect(fetchSpy).toHaveBeenCalledTimes(1);
const calledInit = fetchSpy.mock.calls[0][1] as RequestInit;
expect(calledInit.signal).toBeDefined();
expect(calledInit.signal).toBeInstanceOf(AbortSignal);
});
it("resolves with empty outputText when choices array is empty or missing content", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(
JSON.stringify({
model: "gpt-4o-mini",
choices: []
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "test-key"
});
const response1 = await provider.generate({
instructions: "test",
input: "test"
});
expect(response1.outputText).toBe("");
expect(response1.metadata.model).toBe("gpt-4o-mini");
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(
JSON.stringify({
model: "gpt-4o-mini",
choices: [{ message: {} }]
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
);
const response2 = await provider.generate({
instructions: "test",
input: "test"
});
expect(response2.outputText).toBe("");
expect(response2.metadata.model).toBe("gpt-4o-mini");
});
it("handles non-2xx HTTP responses with descriptive error", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ error: "Invalid API key" }), {
status: 401,
statusText: "Unauthorized"
})
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "invalid-key"
});
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrowError(
'OpenAI-compatible provider returned HTTP 401: {"error":"Invalid API key"}'
);
});
it("handles malformed non-JSON response body with descriptive error", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response("<html>Bad Gateway</html>", {
status: 200,
headers: { "Content-Type": "text/html" }
})
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "valid-key"
});
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrowError();
});
it("handles network failure gracefully", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(
new Error("ECONNREFUSED")
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "valid-key"
});
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrowError(
"OpenAI-compatible provider request failed: ECONNREFUSED"
);
});
it.each([null, [], {}, { choices: null }, { choices: {} }, { choices: [] }])(
"rejects a successful HTTP response without a non-empty choices array: %j",
async (payload) => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify(payload), { status: 200 })
);
const provider = new OpenAICompatibleModelProvider({
apiKey: "test-key"
});
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrowError(
"malformed response (HTTP 200): expected a non-empty choices array."
);
}
);
it.each([
null,
{},
{ message: null },
{ message: {} },
{ message: { content: null }, finish_reason: "tool_calls" },
{ message: { content: 123 } }
])("rejects a choice without string message content: %j", async (choice) => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [choice] }), { status: 200 })
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "test-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrowError(
"malformed response (HTTP 200): expected choices[0].message.content to be a string."
);
});
it("preserves an explicitly empty string and completion metadata", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(
JSON.stringify({
choices: [{ message: { content: "" }, finish_reason: "stop" }],
usage: { total_tokens: 1 }
}),
{ status: 200 }
)
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "test-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).resolves.toEqual({
outputText: "",
metadata: {
model: "gpt-4o-mini",
finishReason: "stop",
usage: { total_tokens: 1 }
}
});
});
it("wraps malformed JSON with HTTP context and a bounded body excerpt", async () => {
const body =
"<html>upstream error</html>\n" + "x".repeat(300) + "AFTER_LIMIT";
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(body, { status: 200 })
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "test-key" });
const failure = await provider
.generate({ instructions: "test", input: "test" })
.catch((error: unknown) => error);
expect(failure).toBeInstanceOf(Error);
expect((failure as Error).message).toBe(
`OpenAI-compatible provider returned invalid JSON (HTTP 200): ${JSON.stringify(body.slice(0, 200))}...`
);
expect((failure as Error).message).not.toContain("AFTER_LIMIT");
expect((failure as Error).cause).toBeInstanceOf(SyntaxError);
});
it("preserves HTTP context when reading the successful response body fails", async () => {
const bodyFailure = new Error("connection closed during response");
const response = new Response("", { status: 200 });
vi.spyOn(response, "text").mockRejectedValueOnce(bodyFailure);
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(response);
const provider = new OpenAICompatibleModelProvider({ apiKey: "test-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toMatchObject({
message:
"OpenAI-compatible provider could not read HTTP 200 response body.",
cause: bodyFailure
});
});
});
it("rejects empty choices array with descriptive error", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [] }), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow("empty choices");
});
it("rejects choice without message content", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [{ message: {} }] }), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow("without message content");
});
it("wraps non-JSON response in error with HTTP context", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response("not json at all", {
status: 200,
headers: { "Content-Type": "text/plain" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow();
});
it("rejects empty choices array with descriptive error", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [] }), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow("empty choices");
});
it("rejects choice without message content", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(JSON.stringify({ choices: [{ message: {} }] }), {
status: 200,
headers: { "Content-Type": "application/json" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow("without message content");
});
it("wraps non-JSON response in error with HTTP context", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response("not json at all", {
status: 200,
headers: { "Content-Type": "text/plain" }
})
);
const provider = new OpenAICompatibleModelProvider({ apiKey: "sk-key" });
await expect(
provider.generate({ instructions: "test", input: "test" })
).rejects.toThrow();
});