Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): answer tool calls skipped when model output is cut short (#4227)

vercel[bot]43f585c06b9d
diff --git a/.changeset/answer-cut-short-tool-calls.md b/.changeset/answer-cut-short-tool-calls.md
new file mode 100644
index 000000000..582649ff0
--- /dev/null
+++ b/.changeset/answer-cut-short-tool-calls.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A model step that ends early, for example at the output token limit, no longer leaves its tool calls unanswered. The AI SDK does not run tools from such a step, so the next model call failed with "Tool results are missing". eve now answers each skipped call with an error, and the model can call the tool again.
diff --git a/packages/eve/src/harness/tool-input-validation.integration.test.ts b/packages/eve/src/harness/tool-input-validation.integration.test.ts
index 969976469..51515019f 100644
--- a/packages/eve/src/harness/tool-input-validation.integration.test.ts
+++ b/packages/eve/src/harness/tool-input-validation.integration.test.ts
@@ -1,5 +1,5 @@
-import type { LanguageModel, ModelMessage } from "ai";
-import { MockLanguageModelV4 } from "ai/test";
+import { jsonSchema, type LanguageModel, type ModelMessage } from "ai";
+import { convertArrayToReadableStream, MockLanguageModelV4 } from "ai/test";
import { describe, expect, it, vi } from "vitest";
import { createToolLoopHarness } from "#harness/tool-loop.js";
@@ -112,4 +112,156 @@ describe("framework tool input validation (real AI SDK)", () => {
expect(validStep.next).toBeNull();
expect(validStep.settledTurn).toEqual({ output: { answer: "done" } });
});
+
+ it.each([
+ {
+ name: "beside a truncated call",
+ truncated: [{ input: '{"path": "notes/bob', toolCallId: "read-truncated" }],
+ },
+ { name: "alone", truncated: [] },
+ ])("answers complete tool calls cut short at the output limit $name", async ({ truncated }) => {
+ const skippedCallId = "read-skipped";
+ const model = new MockLanguageModelV4({
+ doGenerate: [
+ {
+ content: [
+ {
+ input: JSON.stringify({ path: "notes/alice.md" }),
+ toolCallId: skippedCallId,
+ toolName: "read_note",
+ type: "tool-call",
+ },
+ ...truncated.map((call) => ({
+ ...call,
+ toolName: "read_note",
+ type: "tool-call" as const,
+ })),
+ ],
+ finishReason: { raw: undefined, unified: "length" },
+ usage,
+ warnings: [],
+ },
+ {
+ content: [{ text: "I will read Alice's note again.", type: "text" }],
+ finishReason: { raw: undefined, unified: "stop" },
+ usage,
+ warnings: [],
+ },
+ ],
+ modelId: "output-limit-model",
+ provider: "eve-integration-mock",
+ });
+ const execute = vi.fn(async () => ({ text: "Meeting moved to Friday." }));
+ const runStep = createToolLoopHarness({
+ resolveModel: async (): Promise<LanguageModel> => model,
+ tools: new Map([
+ [
+ "read_note",
+ {
+ name: "read_note",
+ description: "Read one of Alice's notes.",
+ execute,
+ inputSchema: jsonSchema({
+ properties: { path: { type: "string" } },
+ required: ["path"],
+ type: "object",
+ }),
+ },
+ ],
+ ]),
+ });
+ const session: HarnessSession = {
+ agent: {
+ modelReference: { id: "output-limit-model" },
+ system: "Help Alice with her notes.",
+ tools: [],
+ },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "task:output-limit-session",
+ history: [],
+ sessionId: "output-limit-session",
+ };
+
+ const cutShortStep = await runStep(session, { message: "Read Alice's and Bob's notes." });
+ if (typeof cutShortStep.next !== "function") {
+ throw new TypeError("Expected the cut-short step to continue the tool loop.");
+ }
+ const nextStep = await cutShortStep.next(cutShortStep.session);
+
+ expect(execute).not.toHaveBeenCalled();
+ expect(model.doGenerateCalls).toHaveLength(2);
+ const retryPrompt = model.doGenerateCalls[1]?.prompt ?? [];
+ expect(findToolResult(retryPrompt, skippedCallId)).toMatchObject({
+ output: { type: "error-text", value: expect.stringContaining("finish reason: length") },
+ });
+ for (const call of truncated) {
+ expect(findToolResult(retryPrompt, call.toolCallId)).toBeDefined();
+ }
+ expect(nextStep.next).toBeNull();
+ });
+
+ it("settles a streamed call cut short at the output limit before the step completes", async () => {
+ const model = new MockLanguageModelV4({
+ doStream: async () => ({
+ stream: convertArrayToReadableStream([
+ {
+ input: JSON.stringify({ path: "notes/alice.md" }),
+ toolCallId: "read-skipped",
+ toolName: "read_note",
+ type: "tool-call",
+ },
+ { finishReason: { raw: undefined, unified: "length" }, type: "finish", usage },
+ ]),
+ }),
+ modelId: "output-limit-model",
+ provider: "eve-integration-mock",
+ });
+ const events: string[] = [];
+ const runStep = createToolLoopHarness({
+ handleEvent: async (event) => {
+ if (event.type === "action.result") {
+ events.push(
+ `action.result:${event.data.result.callId}:${String(event.data.result.isError)}`,
+ );
+ } else {
+ events.push(event.type);
+ }
+ },
+ resolveModel: async (): Promise<LanguageModel> => model,
+ tools: new Map([
+ [
+ "read_note",
+ {
+ name: "read_note",
+ description: "Read one of Alice's notes.",
+ execute: async () => ({ text: "Meeting moved to Friday." }),
+ inputSchema: jsonSchema({ type: "object" }),
+ },
+ ],
+ ]),
+ });
+
+ await runStep(
+ {
+ agent: {
+ modelReference: { id: "output-limit-model" },
+ system: "Help Alice with her notes.",
+ tools: [],
+ },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "task:output-limit-stream-session",
+ history: [],
+ sessionId: "output-limit-stream-session",
+ },
+ { message: "Read Alice's note." },
+ );
+
+ const stepEvents = events.slice(events.indexOf("step.started"));
+ expect(stepEvents.slice(0, 4)).toEqual([
+ "step.started",
+ "actions.requested",
+ "action.result:read-skipped:true",
+ "step.completed",
+ ]);
+ });
});
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 8938ee9b6..8ae076a42 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -1637,13 +1637,28 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
) {
throw new EmptyModelResponseError();
}
- await emitStepActions(emit, emissionState, stepResult, {
- emittedActionCallIds,
- excludedActionCallIds: invalidInputToolCallIds,
- excludedActionToolNames,
- handledInlineToolResultCallIds,
- tools: presentationTools,
- });
+ const skippedToolResults = answerSkippedToolCalls(stepResult, effectiveTools);
+ // Settle skipped calls with the step's other results, before step.completed.
+ await emitStepActions(
+ emit,
+ emissionState,
+ skippedToolResults.length === 0
+ ? stepResult
+ : withAccumulatedResponseMessages({
+ responseMessages: appendMissingToolResultMessages({
+ append: skippedToolResults,
+ responseMessages: stepResult.response.messages,
+ }),
+ stepResult,
+ }),
+ {
+ emittedActionCallIds,
+ excludedActionCallIds: invalidInputToolCallIds,
+ excludedActionToolNames,
+ handledInlineToolResultCallIds,
+ tools: presentationTools,
+ },
+ );
const existingToolResults = stepResult.toolResults as TypedToolResult<ToolSet>[];
const toolResultsByCallId = new Map(
existingToolResults.map((toolResult) => [toolResult.toolCallId, toolResult]),
@@ -1654,7 +1669,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
return withAccumulatedResponseMessages({
invalidInputToolCallIds,
responseMessages: appendMissingToolResultMessages({
- append: trailingInlineToolResultParts,
+ append: [...trailingInlineToolResultParts, ...skippedToolResults],
responseMessages: accumulatedResponseMessages,
}),
stepResult,
@@ -1680,7 +1695,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
throw new EmptyModelResponseError();
}
return withAccumulatedResponseMessages({
- responseMessages: generateResult.responseMessages,
+ responseMessages: appendMissingToolResultMessages({
+ append: answerSkippedToolCalls(stepResult, effectiveTools),
+ responseMessages: generateResult.responseMessages,
+ }),
stepResult,
});
};
@@ -2280,6 +2298,44 @@ function getInvalidToolCallInputErrors(input: {
return errors;
}
+/**
+ * The AI SDK runs tools only when a step finishes with `stop` or `tool-calls`.
+ * A step cut short, such as at the output token limit, leaves the calls it
+ * would have run unanswered, and the next model call rejects that history.
+ * Answer each with an error so the model can call the tool again. Calls the
+ * SDK never runs (deferred tools, `final_output`) keep their usual handling.
+ */
+function answerSkippedToolCalls(step: HarnessStepResult, tools: ToolSet): ToolResultPart[] {
+ const { finishReason } = step;
+ if (finishReason === "stop" || finishReason === "tool-calls") return [];
+
+ const answeredCallIds = extractToolResultCallIds(step.response.messages);
+ const pendingApprovalCallIds = new Set(
+ (step.content ?? []).flatMap((part) =>
+ part.type === "tool-approval-request" && part.isAutomatic !== true
+ ? [part.toolCall.toolCallId]
+ : [],
+ ),
+ );
+ const value = `The tool did not run because the model response ended early (finish reason: ${finishReason}). Call the tool again if you still need its result.`;
+ return ((step.toolCalls ?? []) as TypedToolCall<ToolSet>[])
+ .filter(
+ (toolCall) =>
+ tools[toolCall.toolName]?.execute !== undefined &&
+ toolCall.providerExecuted !== true &&
+ !isInvalidToolCall(toolCall) &&
+ getInvalidToolCallInputError({ toolCall }) === undefined &&
+ !answeredCallIds.has(toolCall.toolCallId) &&
+ !pendingApprovalCallIds.has(toolCall.toolCallId),
+ )
+ .map((toolCall) => ({
+ output: { type: "error-text", value },
+ toolCallId: toolCall.toolCallId,
+ toolName: toolCall.toolName,
+ type: "tool-result",
+ }));
+}
+
/**
* CallIds answered anywhere in the response messages. Scans every message
* role: provider-executed tool results arrive inline in the *assistant*