Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ import type {
Output,
} from "./types.js";
import { streamText } from "./streamText.js";
import { errorToString, willContinue } from "./utils.js";
import { errorToString, hasSuccessfulToolCall, willContinue } from "./utils.js";

export { stepCountIs } from "ai";
export { hasSuccessfulToolCall };
export {
docsToModelMessages,
toModelMessage,
Expand Down
23 changes: 22 additions & 1 deletion src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import type { StepResult, StopCondition } from "ai";

/**
* A stop condition that only matches tool calls which completed
* successfully (i.e. produced a `tool-result`, not a `tool-error`).
*
* Use this instead of the AI SDK's `hasToolCall` when you want the
* agent to retry on argument validation failures rather than stopping.
*/
export function hasSuccessfulToolCall(toolName: string): StopCondition<any> {
return ({ steps }) =>
steps[steps.length - 1]?.toolResults?.some(
(result) => result.toolName === toolName,
) ?? false;
}

export async function willContinue(
steps: StepResult<any>[],

Expand All @@ -9,8 +23,15 @@ export async function willContinue(
// we aren't doing another round after a tool result
// TODO: whether to handle continuing after too much context used..
if (step.finishReason !== "tool-calls") return false;
// Count both successful results and errors as completed outputs.
// In AI SDK v6, failed tool calls produce tool-error content parts
// instead of tool-result, so only checking toolResults misses them.
const completedOutputs =
step.content?.filter(
(p) => p.type === "tool-result" || p.type === "tool-error",
).length ?? step.toolResults.length;
// we don't have a tool result, so we'll wait for more
if (step.toolCalls.length > step.toolResults.length) return false;
if (step.toolCalls.length > completedOutputs) return false;
if (Array.isArray(stopWhen)) {
return (await Promise.all(stopWhen.map(async (s) => s({ steps })))).every(
(stop) => !stop,
Expand Down