Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): evals - add deterministic mock models (#342)

Andrew Barba5b3162752aa4
diff --git a/.changeset/nice-mock-models.md b/.changeset/nice-mock-models.md
new file mode 100644
index 000000000..0b155d902
--- /dev/null
+++ b/.changeset/nice-mock-models.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add a deterministic `mockModel` eval helper with static, prompt-aware, and tool-calling responses.
diff --git a/docs/evals/overview.mdx b/docs/evals/overview.mdx
index 4c38bbdf1..6fe6691a9 100644
--- a/docs/evals/overview.mdx
+++ b/docs/evals/overview.mdx
@@ -58,6 +58,44 @@ export default defineEvalConfig({
Everything is optional. `judge` sets the default model for [LLM-as-judge](./judge) assertions (`t.judge.*`); a tree of fully deterministic evals can omit it. `reporters`, `maxConcurrency`, and `timeoutMs` round out the defaults. Config `reporters` observe every eval in the run, so set one `Braintrust()` here instead of adding it to each eval. CLI flags (`--max-concurrency`, `--timeout`) and per-eval values take precedence over the config defaults.
+## Deterministic fixture models
+
+Use `mockModel` when an eval fixture needs to exercise eve's runtime without calling a model provider. A static fixture can be one line:
+
+```ts title="agent/agent.ts"
+import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+export default defineAgent({
+ model: mockModel("A deterministic reply"),
+});
+```
+
+Pass a callback when the reply depends on the conversation. The callback receives an eve-owned view of the prompt, including `lastUserMessage`, `userMessages`, `userMessageCount`, available `tools`, and prior `toolResults`:
+
+```ts title="agent/agent.ts"
+export default defineAgent({
+ model: mockModel(
+ ({ lastUserMessage, userMessageCount }) => `Turn ${userMessageCount}: ${lastUserMessage}`,
+ ),
+});
+```
+
+The callback may return `{ text, toolCalls, usage }` for deterministic tool loops or explicit token counts. Use the options form only when a fixture also needs a custom model identity:
+
+```ts title="agent/agent.ts"
+model: mockModel({
+ modelId: "weather-script",
+ provider: "my-fixtures",
+ respond: ({ toolResults }) =>
+ toolResults.length === 0
+ ? { toolCalls: [{ name: "get_weather", input: { city: "Brooklyn" } }] }
+ : `Weather: ${JSON.stringify(toolResults[0]?.output)}`,
+});
+```
+
+`mockModel()` uses `"Mock response"` when no response is supplied. It handles both generated and streamed responses, derives deterministic response metadata, and estimates token usage. Because the model is part of the agent definition, use it for a dedicated fixture agent; it remains mocked whether that fixture runs locally or as a deployed eval target.
+
## The `t` context
`t` is both the driver and the assertion surface. There are no separate `input`, `run`, `checks`, or `scores` fields. You write ordinary control flow, sending turns and asserting inline.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 1e5ccade7..ebcc49a1d 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -49,6 +49,7 @@ export default defineTool({
| `defineRemoteAgent` | `eve` | `agent/subagents/<id>/agent.ts` | [Remote agents](../guides/remote-agents) |
| `defineEval` | `eve/evals` | `evals/*.eval.ts` | [Evals](../evals/overview) |
| `defineEvalConfig` | `eve/evals` | `evals/evals.config.ts` | [Evals](../evals/overview) |
+| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |
| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |
A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWorkflow` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.
@@ -85,7 +86,7 @@ A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWo
| `eve/context` | `defineState`, session and state types |
| `eve/sandbox` | `defineSandbox`, backends |
| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
-| `eve/evals` | `defineEval`, `defineEvalConfig`, eval types |
+| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
| `eve/evals/loaders` | `loadJson`, `loadYaml` |
diff --git a/e2e/README.md b/e2e/README.md
index 56a621c3e..e77c1720a 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -61,9 +61,9 @@ identically at build and runtime, and Vercel has no team variable at runtime.
Most local and deployed evals run the fixture agents and judges against real
models (`openai/gpt-5.5`), so the environment must provide the corresponding
-model-provider credentials. `agent-workflow-stress` uses an authored AI SDK
-mock model so its 100-turn runs stay fast and deterministic. Its concurrent and
-sequential evals cover high-volume session execution and repeated session
+model-provider credentials. `agent-workflow-stress` uses eve's `mockModel`
+fixture helper so its 100-turn runs stay fast and deterministic. Its concurrent
+and sequential evals cover high-volume session execution and repeated session
resumption respectively.
## Fixtures
diff --git a/e2e/fixtures/agent-workflow-stress/agent/agent.ts b/e2e/fixtures/agent-workflow-stress/agent/agent.ts
index ce1d11121..aee410f61 100644
--- a/e2e/fixtures/agent-workflow-stress/agent/agent.ts
+++ b/e2e/fixtures/agent-workflow-stress/agent/agent.ts
@@ -1,92 +1,10 @@
import { defineAgent } from "eve";
-import { MockLanguageModelV3 } from "ai/test";
-
-type GenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];
-type GenerateResult = Awaited<ReturnType<MockLanguageModelV3["doGenerate"]>>;
-type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;
-
-const RESPONSE_TIMESTAMP = new Date("2026-06-26T00:00:00.000Z");
-
-const model = new MockLanguageModelV3({
- provider: "eve-stress",
- modelId: "workflow-turns",
- doGenerate: async (options) => createGenerateResult(options),
- doStream: async (options) => createStreamResult(createGenerateResult(options)),
-});
+import { mockModel } from "eve/evals";
export default defineAgent({
- model,
+ model: mockModel(
+ ({ lastUserMessage, userMessageCount }) =>
+ `stress-ack:${userMessageCount}:${lastUserMessage ?? ""}`,
+ ),
modelContextWindowTokens: 1_000_000,
});
-
-function createGenerateResult(options: GenerateOptions): GenerateResult {
- const userMessages = options.prompt.filter((message) => message.role === "user");
- const latestMessage = userMessages.at(-1);
- const latestText = latestMessage === undefined ? "" : contentText(latestMessage.content);
- const text = `stress-ack:${userMessages.length}:${latestText}`;
- const inputTokens = estimateTokens(
- options.prompt.map((message) => contentText(message.content)).join(" "),
- );
- const outputTokens = estimateTokens(text);
-
- return {
- content: [{ text, type: "text" }],
- finishReason: { raw: undefined, unified: "stop" },
- response: {
- id: `stress-response-${userMessages.length}`,
- modelId: model.modelId,
- timestamp: RESPONSE_TIMESTAMP,
- },
- usage: {
- inputTokens: {
- cacheRead: 0,
- cacheWrite: 0,
- noCache: inputTokens,
- total: inputTokens,
- },
- outputTokens: {
- reasoning: 0,
- text: outputTokens,
- total: outputTokens,
- },
- },
- warnings: [],
- };
-}
-
-function createStreamResult(result: GenerateResult): StreamResult {
- const text = result.content.find((part) => part.type === "text")?.text ?? "";
-
- return {
- stream: new ReadableStream({
- start(controller) {
- controller.enqueue({ type: "stream-start", warnings: result.warnings });
- controller.enqueue({ ...result.response, type: "response-metadata" });
- controller.enqueue({ id: "stress-text", type: "text-start" });
- controller.enqueue({ delta: text, id: "stress-text", type: "text-delta" });
- controller.enqueue({ id: "stress-text", type: "text-end" });
- controller.enqueue({
- finishReason: result.finishReason,
- type: "finish",
- usage: result.usage,
- });
- controller.close();
- },
- }),
- };
-}
-
-function contentText(content: GenerateOptions["prompt"][number]["content"]): string {
- if (typeof content === "string") {
- return content;
- }
-
- return content
- .flatMap((part) => (part.type === "text" ? [part.text] : []))
- .join("")
- .trim();
-}
-
-function estimateTokens(value: string): number {
- return Math.max(1, Math.ceil(value.length / 4));
-}
diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.ts
index 6f9892f02..a27fd0ee7 100644
--- a/packages/eve/src/evals/index.ts
+++ b/packages/eve/src/evals/index.ts
@@ -5,6 +5,7 @@
export { defineEval } from "#evals/define-eval.js";
export { defineEvalConfig } from "#evals/define-eval-config.js";
export { EveEvalTurnFailedError } from "#evals/session.js";
+export { mockModel } from "#evals/mock-model.js";
// ---------------------------------------------------------------------------
// Types
@@ -54,3 +55,15 @@ export type {
JudgeContext,
JudgeOpts,
} from "#evals/types.js";
+
+export type {
+ MockModelMessage,
+ MockModelOptions,
+ MockModelRequest,
+ MockModelResponder,
+ MockModelResponse,
+ MockModelTool,
+ MockModelToolCall,
+ MockModelToolResult,
+ MockModelUsage,
+} from "#evals/mock-model.js";
diff --git a/packages/eve/src/evals/mock-model.test.ts b/packages/eve/src/evals/mock-model.test.ts
new file mode 100644
index 000000000..a6922572b
--- /dev/null
+++ b/packages/eve/src/evals/mock-model.test.ts
@@ -0,0 +1,127 @@
+import { generateText, jsonSchema, stepCountIs, streamText, tool } from "ai";
+import { describe, expect, it, vi } from "vitest";
+
+import { mockModel, type MockModelRequest } from "#evals/mock-model.js";
+
+describe("mockModel", () => {
+ it("returns a deterministic default response", async () => {
+ const result = await generateText({
+ model: mockModel(),
+ prompt: "Hello",
+ });
+
+ expect(result.text).toBe("Mock response");
+ expect(result.response.modelId).toBe("model");
+ expect(result.usage.inputTokens).toBe(2);
+ expect(result.usage.outputTokens).toBe(4);
+ });
+
+ it("accepts a static response and streams it", async () => {
+ const result = streamText({
+ model: mockModel("Always the same"),
+ prompt: "Hello",
+ });
+
+ await expect(result.text).resolves.toBe("Always the same");
+ });
+
+ it("gives responders a normalized prompt and supports identity and usage overrides", async () => {
+ const requests: MockModelRequest[] = [];
+ const model = mockModel({
+ modelId: "scripted",
+ provider: "test-provider",
+ respond(request) {
+ requests.push(request);
+ return {
+ text: `${request.userMessageCount}:${request.lastUserMessage}`,
+ usage: { inputTokens: 10, outputTokens: 20 },
+ };
+ },
+ });
+
+ const result = await generateText({
+ messages: [
+ { content: "First", role: "user" },
+ { content: "Previous", role: "assistant" },
+ { content: "Second", role: "user" },
+ ],
+ model,
+ });
+
+ expect(result.text).toBe("2:Second");
+ expect(result.response.modelId).toBe("scripted");
+ expect(result.usage.inputTokens).toBe(10);
+ expect(result.usage.outputTokens).toBe(20);
+ expect(requests).toEqual([
+ expect.objectContaining({
+ lastUserMessage: "Second",
+ messages: [
+ { role: "user", text: "First" },
+ { role: "assistant", text: "Previous" },
+ { role: "user", text: "Second" },
+ ],
+ userMessageCount: 2,
+ userMessages: ["First", "Second"],
+ }),
+ ]);
+ });
+
+ it("supports deterministic tool-call loops", async () => {
+ const execute = vi.fn(async ({ city }: { city: string }) => ({ city, condition: "sunny" }));
+ const requests: MockModelRequest[] = [];
+ const model = mockModel((request) => {
+ requests.push(request);
+
+ if (request.toolResults.length === 0) {
+ return {
+ toolCalls: [{ input: { city: "Brooklyn" }, name: "get_weather" }],
+ };
+ }
+
+ return `Weather: ${JSON.stringify(request.toolResults[0]!.output)}`;
+ });
+
+ const result = await generateText({
+ model,
+ prompt: "What is the weather?",
+ stopWhen: stepCountIs(2),
+ tools: {
+ get_weather: tool({
+ description: "Get the weather for a city.",
+ execute,
+ inputSchema: jsonSchema({
+ additionalProperties: false,
+ properties: { city: { type: "string" } },
+ required: ["city"],
+ type: "object",
+ }),
+ }),
+ },
+ });
+
+ expect(execute).toHaveBeenCalledExactlyOnceWith({ city: "Brooklyn" }, expect.any(Object));
+ expect(result.text).toBe('Weather: {"city":"Brooklyn","condition":"sunny"}');
+ expect(requests[0]!.tools).toEqual([
+ expect.objectContaining({
+ description: "Get the weather for a city.",
+ name: "get_weather",
+ }),
+ ]);
+ expect(requests[1]!.toolResults).toEqual([
+ expect.objectContaining({
+ isError: false,
+ name: "get_weather",
+ output: { city: "Brooklyn", condition: "sunny" },
+ }),
+ ]);
+ });
+
+ it("rejects empty advanced responses", async () => {
+ await expect(
+ generateText({
+ model: mockModel(() => ({})),
+ prompt: "Hello",
+ }),
+ ).rejects.toThrow(/must return text or at least one item/);
+ });
+});
diff --git a/packages/eve/src/evals/mock-model.ts b/packages/eve/src/evals/mock-model.ts
new file mode 100644
index 000000000..ade554b9d
--- /dev/null
+++ b/packages/eve/src/evals/mock-model.ts
@@ -0,0 +1,380 @@
+import type { LanguageModel } from "ai";
+import { MockLanguageModelV3 } from "ai/test";
+
+type GenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];
+type GenerateResult = Awaited<ReturnType<MockLanguageModelV3["doGenerate"]>>;
+type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;
+type StreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;
+type PromptPart = Exclude<GenerateOptions["prompt"][number]["content"], string>[number];
+type ToolResultOutput = Extract<PromptPart, { type: "tool-result" }>["output"];
+
+const DEFAULT_MODEL_ID = "model";
+const DEFAULT_PROVIDER = "eve-mock";
+const DEFAULT_RESPONSE = "Mock response";
+const RESPONSE_TIMESTAMP = Date.parse("2026-01-01T00:00:00.000Z");
+
+/** A text-only view of one message passed to a mock model. */
+export interface MockModelMessage {
+ /** The message author. */
+ readonly role: "assistant" | "system" | "tool" | "user";
+ /** Text extracted from the message's content parts. */
+ readonly text: string;
+}
+
+/** A tool available to a mock model call. */
+export interface MockModelTool {
+ /** Tool name exposed to the model. */
+ readonly name: string;
+ /** Authored tool description, when present. */
+ readonly description?: string;
+ /** JSON Schema describing the tool input, when present. */
+ readonly inputSchema?: unknown;
+}
+
+/** A completed tool call present in the model prompt. */
+export interface MockModelToolResult {
+ /** Tool-call identifier. */
+ readonly id: string;
+ /** Name of the tool that produced the result. */
+ readonly name: string;
+ /** Normalized tool output. */
+ readonly output: unknown;
+ /** Whether the tool execution failed or was denied. */
+ readonly isError: boolean;
+}
+
+/** Normalized input supplied to a {@link MockModelResponder}. */
+export interface MockModelRequest {
+ /** Every prompt message in order, with text content extracted. */
+ readonly messages: readonly MockModelMessage[];
+ /** All user-message text in order. */
+ readonly userMessages: readonly string[];
+ /** The latest user-message text, or `null` before the first user message. */
+ readonly lastUserMessage: string | null;
+ /** Number of user messages in the prompt. */
+ readonly userMessageCount: number;
+ /** Tools available for this model call. */
+ readonly tools: readonly MockModelTool[];
+ /** Tool results already present in the prompt. */
+ readonly toolResults: readonly MockModelToolResult[];
+}
+
+/** One tool call emitted by a mock model response. */
+export interface MockModelToolCall {
+ /** Name of the tool to call. */
+ readonly name: string;
+ /** JSON-serializable tool input. Defaults to an empty object. */
+ readonly input?: unknown;
+ /** Stable call id. eve derives one when omitted. */
+ readonly id?: string;
+}
+
+/** Optional token counts reported by a mock response. */
+export interface MockModelUsage {
+ /** Prompt tokens. eve estimates this value when omitted. */
+ readonly inputTokens?: number;
+ /** Generated tokens. eve estimates this value when omitted. */
+ readonly outputTokens?: number;
+}
+
+/** Advanced response shape for text, tool calls, and explicit token usage. */
+export interface MockModelResponse {
+ /** Assistant text. May be combined with tool calls. */
+ readonly text?: string;
+ /** Tool calls emitted by the model. */
+ readonly toolCalls?: readonly MockModelToolCall[];
+ /** Token counts to report instead of eve's deterministic estimates. */
+ readonly usage?: MockModelUsage;
+}
+
+/** Produces the next deterministic mock-model response. */
+export type MockModelResponder = (
+ request: MockModelRequest,
+) => MockModelResponse | Promise<MockModelResponse | string> | string;
+
+/** Advanced configuration for {@link mockModel}. */
+export interface MockModelOptions {
+ /** Model id exposed to the agent runtime. Defaults to `"model"`. */
+ readonly modelId?: string;
+ /** Provider id exposed to the agent runtime. Defaults to `"eve-mock"`. */
+ readonly provider?: string;
+ /** Static response or callback used for each model call. */
+ readonly respond?: MockModelResponder | string;
+}
+
+/**
+ * Creates a deterministic local language model for an eve eval fixture.
+ *
+ * Pass a string for a static reply, a callback for prompt-aware behavior, or
+ * an options object when the model identity or advanced responses need to be
+ * customized. Calling `mockModel()` returns `"Mock response"`.
+ *
+ * @example
+ * ```ts
+ * mockModel("Hello from the test agent");
+ * mockModel(({ lastUserMessage }) => `Echo: ${lastUserMessage}`);
+ * ```
+ */
+export function mockModel(
+ input: MockModelOptions | MockModelResponder | string = {},
+): LanguageModel {
+ const options = normalizeOptions(input);
+ const respond = normalizeResponder(options.respond);
+ const modelId = options.modelId ?? DEFAULT_MODEL_ID;
+
+ return new MockLanguageModelV3({
+ modelId,
+ provider: options.provider ?? DEFAULT_PROVIDER,
+ doGenerate: async (callOptions) =>
+ createGenerateResult(await respond(createRequest(callOptions)), callOptions, modelId),
+ doStream: async (callOptions) =>
+ createStreamResult(
+ createGenerateResult(await respond(createRequest(callOptions)), callOptions, modelId),
+ ),
+ });
+}
+
+function normalizeOptions(input: MockModelOptions | MockModelResponder | string): MockModelOptions {
+ if (typeof input === "string" || typeof input === "function") {
+ return { respond: input };
+ }
+
+ return input;
+}
+
+function normalizeResponder(respond: MockModelOptions["respond"]): MockModelResponder {
+ if (typeof respond === "function") {
+ return respond;
+ }
+
+ const text = respond ?? DEFAULT_RESPONSE;
+ return () => text;
+}
+
+function createRequest(options: GenerateOptions): MockModelRequest {
+ const messages = options.prompt.map((message) => ({
+ role: message.role,
+ text: extractMessageText(message),
+ }));
+ const userMessages = messages
+ .filter((message) => message.role === "user")
+ .map((message) => message.text);
+
+ return {
+ lastUserMessage: userMessages.at(-1) ?? null,
+ messages,
+ toolResults: extractToolResults(options),
+ tools: extractTools(options),
+ userMessageCount: userMessages.length,
+ userMessages,
+ };
+}
+
+function extractMessageText(message: GenerateOptions["prompt"][number]): string {
+ if (typeof message.content === "string") {
+ return message.content;
+ }
+
+ return message.content
+ .flatMap((part) => {
+ switch (part.type) {
+ case "reasoning":
+ case "text":
+ return [part.text];
+ case "tool-result":
+ return [formatValue(normalizeToolOutput(part.output))];
+ default:
+ return [];
+ }
+ })
+ .join("");
+}
+
+function extractTools(options: GenerateOptions): readonly MockModelTool[] {
+ return (options.tools ?? []).map((tool) => {
+ if (tool.type === "function") {
+ return {
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ name: tool.name,
+ };
+ }
+
+ return { name: tool.name };
+ });
+}
+
+function extractToolResults(options: GenerateOptions): readonly MockModelToolResult[] {
+ return options.prompt.flatMap((message) => {
+ if (typeof message.content === "string") {
+ return [];
+ }
+
+ return message.content.flatMap((part) => {
+ if (part.type !== "tool-result") {
+ return [];
+ }
+
+ return [
+ {
+ id: part.toolCallId,
+ isError:
+ part.output.type === "error-json" ||
+ part.output.type === "error-text" ||
+ part.output.type === "execution-denied",
+ name: part.toolName,
+ output: normalizeToolOutput(part.output),
+ },
+ ];
+ });
+ });
+}
+
+function normalizeToolOutput(output: ToolResultOutput): unknown {
+ switch (output.type) {
+ case "error-json":
+ case "error-text":
+ case "json":
+ case "text":
+ return output.value;
+ case "execution-denied":
+ return output.reason ?? "Tool execution denied";
+ case "content":
+ return output.value;
+ }
+}
+
+function createGenerateResult(
+ response: MockModelResponse | string,
+ options: GenerateOptions,
+ modelId: string,
+): GenerateResult {
+ const normalized = typeof response === "string" ? { text: response } : response;
+ const toolCalls = normalized.toolCalls ?? [];
+
+ if (!("text" in normalized) && toolCalls.length === 0) {
+ throw new Error('mockModel responders must return text or at least one item in "toolCalls".');
+ }
+
+ const content: GenerateResult["content"] = [];
+
+ if (normalized.text !== undefined) {
+ content.push({ text: normalized.text, type: "text" });
+ }
+
+ for (const [index, toolCall] of toolCalls.entries()) {
+ content.push({
+ input: JSON.stringify(toolCall.input ?? {}),
+ toolCallId:
+ toolCall.id ??
+ `mock-tool-call-${countUserMessages(options)}-${countToolResults(options)}-${index + 1}`,
+ toolName: toolCall.name,
+ type: "tool-call",
+ });
+ }
+
+ const promptText = options.prompt.map((message) => extractMessageText(message)).join(" ");
+ const outputText = [
+ normalized.text ?? "",
+ ...toolCalls.map((toolCall) => formatValue(toolCall.input ?? {})),
+ ].join(" ");
+ const inputTokens = normalized.usage?.inputTokens ?? estimateTokens(promptText);
+ const outputTokens = normalized.usage?.outputTokens ?? estimateTokens(outputText);
+
+ const result: GenerateResult = {
+ content,
+ finishReason: {
+ raw: undefined,
+ unified: toolCalls.length > 0 ? "tool-calls" : "stop",
+ },
+ response: {
+ id: `mock-response-${countUserMessages(options)}-${countToolResults(options)}`,
+ modelId,
+ timestamp: new Date(RESPONSE_TIMESTAMP),
+ },
+ usage: {
+ inputTokens: {
+ cacheRead: 0,
+ cacheWrite: 0,
+ noCache: inputTokens,
+ total: inputTokens,
+ },
+ outputTokens: {
+ reasoning: 0,
+ text: outputTokens,
+ total: outputTokens,
+ },
+ },
+ warnings: [],
+ };
+
+ return result;
+}
+
+function createStreamResult(result: GenerateResult): StreamResult {
+ const chunks: StreamPart[] = [{ type: "stream-start", warnings: result.warnings }];
+
+ if (result.response !== undefined) {
+ chunks.push({ ...result.response, type: "response-metadata" });
+ }
+
+ let textIndex = 0;
+
+ for (const part of result.content) {
+ if (part.type === "text") {
+ const id = `mock-text-${textIndex}`;
+ textIndex += 1;
+ chunks.push({ id, type: "text-start" });
+ if (part.text.length > 0) {
+ chunks.push({ delta: part.text, id, type: "text-delta" });
+ }
+ chunks.push({ id, type: "text-end" });
+ continue;
+ }
+
+ if (part.type === "tool-call") {
+ chunks.push(part);
+ }
+ }
+
+ chunks.push({
+ finishReason: result.finishReason,
+ type: "finish",
+ usage: result.usage,
+ });
+
+ return {
+ stream: new ReadableStream<StreamPart>({
+ start(controller) {
+ for (const chunk of chunks) {
+ controller.enqueue(chunk);
+ }
+ controller.close();
+ },
+ }),
+ };
+}
+
+function countUserMessages(options: GenerateOptions): number {
+ return options.prompt.filter((message) => message.role === "user").length;
+}
+
+function countToolResults(options: GenerateOptions): number {
+ return extractToolResults(options).length;
+}
+
+function estimateTokens(value: string): number {
+ return Math.max(1, Math.ceil(value.trim().length / 4));
+}
+
+function formatValue(value: unknown): string {
+ if (typeof value === "string") {
+ return value;
+ }
+
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+}