Skip to content

Testing

The best way to test agents is to pass a MockLanguageModel to the agent instead of a real language model.

agent.test.ts
/* eslint-disable @typescript-eslint/no-floating-promises */
import { MockLanguageModel } from "@hoangvvo/llm-sdk/test";
import test, { suite, type TestContext } from "node:test";
import { Agent } from "./agent.ts";
suite("Agent#run", () => {
test("creates session, runs, and closes", async (t: TestContext) => {
const model = new MockLanguageModel();
model.enqueueGenerateResult({
response: { content: [{ type: "text", text: "Mock response" }] },
});
const agent = new Agent({
name: "test-agent",
model,
});
const response = await agent.run({
context: {},
input: [
{
type: "message",
role: "user",
content: [{ type: "text", text: "Hello" }],
},
],
});
t.assert.deepStrictEqual(response, {
content: [{ type: "text", text: "Mock response" }],
output: [
{
type: "model",
content: [{ type: "text", text: "Mock response" }],
},
],
});
});
});
suite("Agent#runStream", () => {
test("creates session, streams, and closes", async (t: TestContext) => {
const model = new MockLanguageModel();
model.enqueueStreamResult({
partials: [
{
delta: { index: 0, part: { type: "text", text: "Mock" } },
},
],
});
const agent = new Agent({
name: "test-agent",
model,
});
const generator = agent.runStream({
context: {},
input: [
{
type: "message",
role: "user",
content: [{ type: "text", text: "Hello" }],
},
],
});
const events = [];
let current = await generator.next();
while (!current.done) {
events.push(current.value);
current = await generator.next();
}
t.assert.deepStrictEqual(events, [
{
event: "partial",
delta: { index: 0, part: { type: "text", text: "Mock" } },
},
{
event: "item",
index: 0,
item: {
type: "model",
content: [{ type: "text", text: "Mock" }],
},
},
{
event: "response",
content: [{ type: "text", text: "Mock" }],
output: [
{
type: "model",
content: [{ type: "text", text: "Mock" }],
},
],
},
]);
t.assert.deepStrictEqual(current.value, {
content: [{ type: "text", text: "Mock" }],
output: [
{
type: "model",
content: [{ type: "text", text: "Mock" }],
},
],
});
});
});