06b91c2e63
Cover non-ok HTTP response (500) and network failure (ECONNREFUSED). Per review feedback from 星月 🌙 on PR #278.
79 lines
2.4 KiB
TypeScript
79 lines
2.4 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { START, type ThreadContext } from "@uncaged/nerve-core";
|
|
|
|
import { createLlmAdapter } from "../create-llm-adapter.js";
|
|
|
|
function makeCtx(threadId: string, userContent: string): ThreadContext {
|
|
return {
|
|
threadId,
|
|
start: {
|
|
role: START,
|
|
content: userContent,
|
|
meta: { maxRounds: 10, threadId },
|
|
timestamp: 1,
|
|
},
|
|
steps: [],
|
|
};
|
|
}
|
|
|
|
describe("createLlmAdapter", () => {
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("posts system + user (start.content) and returns assistant text", async () => {
|
|
const fetchMock = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
status: 200,
|
|
text: async () =>
|
|
JSON.stringify({
|
|
choices: [{ message: { content: "model reply" } }],
|
|
}),
|
|
});
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
const provider = { baseUrl: "https://api.example/v1", apiKey: "k", model: "m" };
|
|
const adapter = createLlmAdapter(provider);
|
|
const out = await adapter(makeCtx("t1", "trigger text"), "system instructions");
|
|
|
|
expect(out).toBe("model reply");
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
const body = JSON.parse(init.body as string) as {
|
|
model: string;
|
|
messages: Array<{ role: string; content: string }>;
|
|
};
|
|
expect(body.model).toBe("m");
|
|
expect(body.messages).toEqual([
|
|
{ role: "system", content: "system instructions" },
|
|
{ role: "user", content: "trigger text" },
|
|
]);
|
|
});
|
|
|
|
it("throws on non-ok fetch response", async () => {
|
|
const fetchMock = vi.fn().mockResolvedValue({
|
|
ok: false,
|
|
status: 500,
|
|
text: async () => "Internal Server Error",
|
|
});
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
const provider = { baseUrl: "https://api.example/v1", apiKey: "k", model: "m" };
|
|
const adapter = createLlmAdapter(provider);
|
|
|
|
await expect(adapter(makeCtx("t1", "hi"), "sys")).rejects.toThrow("llm:");
|
|
});
|
|
|
|
it("throws on fetch network failure", async () => {
|
|
const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
const provider = { baseUrl: "https://api.example/v1", apiKey: "k", model: "m" };
|
|
const adapter = createLlmAdapter(provider);
|
|
|
|
await expect(adapter(makeCtx("t1", "hi"), "sys")).rejects.toThrow();
|
|
});
|
|
});
|