Your chatbot said the search worked. The tool had already thrown.
I caught this in a demo transcript, not in a dashboard.
The assistant had written, cheerfully, “I looked up your last three invoices. You’re all set — nothing is overdue.” There were no invoices. The searchInvoices tool had thrown relation "invoices" does not exist two seconds earlier. The model did what models do when a tool result is ugly: it summarized the intent of the call instead of the result.
The UI made it worse. I had been streaming assistant tokens into a single markdown bubble. The bubble said “searching…” until the model started talking, then flipped to “done.” From the user’s point of view, the search had succeeded. The error never left the server logs.
What follows is the loop I ended up with. It is not a new framework. It is a Next.js App Router route, a small tool registry, and a UI that treats tool events as first-class state. The model can still be wrong. It just can’t pretend a failed tool call was a successful one.
I am assuming you have already called an LLM from a route handler and have some notion of tool calling. If you have already shipped a chat box with tools in the SDK and a loading spinner, this is probably for you.
The TypeScript in this post is from a scratch Next.js app I actually ran: schema checks, timeouts, bad JSON, unknown tools, a four-step cap, and a POST handler that streams events. I am not going to paste every file here. The important parts are below.
The model’s text is not a source of truth
A tool call is.
“I searched the database” is narration. { ok: false, error: "relation does not exist" } is a fact. If those two disagree, the fact should win, and the narration should not be allowed to repaint the UI.
Streaming hides the seam. If you only render assistant tokens, there is a stretch of time where the model has decided to call a tool, the tool is running or has already failed, and the user is still watching a cursor blink in an empty bubble. Then a confident paragraph arrives. That confidence is part of the product, whether you meant it to be or not.
Retries without identity make it worse. I added a createDraftReply tool to the same demo. The model called it, the request aborted, the client retried, and I ended up with two drafts until I keyed the write. The model then apologized for the duplicates. Helpful.
None of this is exotic. It shows up the first time you put tools in front of a real store.
Stream events, not one growing string
I wanted the client to receive a stream of events.
// lib/chat-events.ts
export type ChatEvent =
| { type: "text-delta"; text: string }
| { type: "tool-start"; callId: string; name: string; args: unknown }
| {
type: "tool-end";
callId: string;
name: string;
args: unknown;
ok: true;
result: unknown;
durationMs: number;
}
| {
type: "tool-end";
callId: string;
name: string;
args: unknown;
ok: false;
error: string;
durationMs: number;
}
| { type: "done" }
| { type: "error"; error: string };
The assistant bubble only ever renders text-delta. Tool cards render tool-start / tool-end. If a tool ends with ok: false, the card stays red even if the model later writes “all good.” That last part is the whole point.
I also made a rule for myself: never let the model choose the success message for a mutation. If a tool creates a record, the UI should show the record the tool returned, not the sentence the model invented about it.
Fail closed before the function runs
Tools live in a registry with a Zod schema and a hard timeout. The model can ask for whatever arguments it wants. They don’t reach execute until they parse.
// lib/tools.ts
export const searchInvoicesSchema = z.object({
query: z.string().max(200).optional(),
status: z.enum(["open", "paid", "overdue"]).optional(),
limit: z.number().int().min(1).max(20).default(5),
});
export const searchInvoices = {
name: "searchInvoices",
description:
"Search the signed-in user's invoices by status or a free-text query. Returns a list of invoices, which may be empty.",
schema: searchInvoicesSchema,
timeoutMs: 8_000,
execute: async (args, ctx) => {
const rows = await findInvoices({ ...args, userId: ctx.userId, store: ctx.store });
return { invoices: rows, count: rows.length };
},
} satisfies Tool;
A few dull choices in there matter. limit is clamped; I have seen a model ask for 10,000 rows “to be thorough.” The description says the list may be empty. Models still ignore that sometimes, but it helps on the second turn, when you feed the empty result back. The tool returns data, not a sentence. “You’re all set” does not belong in execute.
Execution sits behind one function so every tool gets the same timeout and the same error wrapping.
// lib/run-tool.ts
export async function runTool(
tool: Tool,
rawArgs: unknown,
ctx: ToolContext
): Promise<{ ok: true; result: unknown } | { ok: false; error: string }> {
const parsed = tool.schema.safeParse(rawArgs);
if (!parsed.success) {
return {
ok: false,
error: `Invalid arguments: ${parsed.error.issues
.map((i) => i.message)
.join("; ")}`,
};
}
const timeout = new Promise<never>((_, reject) => {
setTimeout(
() => reject(new ToolError(`Timed out after ${tool.timeoutMs}ms`)),
tool.timeoutMs
);
});
try {
const result = await Promise.race([tool.execute(parsed.data, ctx), timeout]);
return { ok: true, result };
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown tool error";
return { ok: false, error: message };
}
}
I return { ok: false } instead of throwing out of the route. Throwing is how I ended up with a model that never saw the error and a UI that looked finished. In the repo I also have a test-only hangForever tool with a 30ms timeout, just to prove that path actually trips.
Run the loop yourself
Most LLM SDKs will run tools for you. That is convenient until you want to emit tool-start before the function returns, or you want to stop a mutation from being retried. I ended up writing the loop myself against an OpenAI-compatible chat.completions shape. The same idea works with other APIs; the important part is that you decide when a tool runs.
Two details I would not drop on a rewrite:
The tool result that goes back to the model is the same object I sent to the client ({ ok, result } or { ok, error }). If those diverge, you have two stories again.
I cap the loop at four steps. That is arbitrary and a little tight for a multi-hop research agent. For an invoice bot, four is plenty. An uncapped loop is how you wake up to a bill you did not mean to run.
And if the model emits arguments that are not valid JSON, I now fail that call immediately. I originally stuffed the raw string into { _parseError: ... } and let Zod see it. searchInvoices has all-optional fields, so the schema accepted the junk, applied the default limit, and ran a real query. That was a bug in my first version. Parse errors should not fall through.
// lib/chat-loop.ts (excerpt)
let parseError: string | undefined;
try {
parsedArgs = JSON.parse(call.function.arguments || "{}");
} catch {
parseError = "Arguments were not valid JSON.";
parsedArgs = { _parseError: call.function.arguments };
}
args.emit({ type: "tool-start", callId: call.id, name, args: parsedArgs });
if (parseError) {
args.emit({
type: "tool-end",
callId: call.id,
name,
args: parsedArgs,
ok: false,
error: parseError,
durationMs: Date.now() - started,
});
conversation.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ ok: false, error: parseError }),
});
continue;
}
if (!tool) {
const error = `Unknown tool: ${name}`;
// same tool-end + tool-message shape as a normal failure
continue;
}
const outcome = await runTool(tool, parsedArgs, args.ctx);
args.emit({
type: "tool-end",
callId: call.id,
name,
args: parsedArgs,
durationMs: Date.now() - started,
...outcome,
});
conversation.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(outcome),
});
If you want token-by-token assistant text, stream the inner completion and forward chunks as text-delta. I kept the turn itself synchronous in the demo so the control flow stays visible. The tool events do not change.
Idempotency for anything that writes
Reads can be retried. Writes need a key.
I pass requestId from the client and combine it with the tool name and a hash of the parsed arguments. The tool checks a small map (a tool_mutations table, in anything real) before inserting.
// lib/mutation-key.ts
import { createHash } from "node:crypto";
export function mutationKey(
requestId: string,
toolName: string,
args: unknown
): string {
const digest = createHash("sha256")
.update(JSON.stringify(args))
.digest("hex")
.slice(0, 16);
return `${requestId}:${toolName}:${digest}`;
}
If the row already exists, return the original result. Do not create a second draft and do not ask the model to “clean it up.” Client retries should reuse the same requestId for a given user send. A new message from the user gets a new id. That distinction sounds obvious when you write it down. It is less obvious when a fetch wrapper retries on abort.
The UI that refuses to be gaslit
On the client I accumulate events, not markdown. Failed tools stay visible after the turn ends. A toast that disappears is how this bug hid from me the first time.
// components/chat-transcript.tsx (excerpt)
export function applyEvent(
text: string,
tools: Record<string, ToolCardState>,
event: ChatEvent
): { text: string; tools: Record<string, ToolCardState> } {
if (event.type === "text-delta") {
return { text: text + event.text, tools };
}
if (event.type === "tool-start") {
return {
text,
tools: {
...tools,
[event.callId]: { name: event.name, args: event.args, status: "running" },
},
};
}
if (event.type === "tool-end") {
return {
text,
tools: {
...tools,
[event.callId]: {
name: event.name,
args: event.args,
status: event.ok ? "ok" : "error",
result: event.ok ? event.result : undefined,
error: event.ok ? undefined : event.error,
durationMs: event.durationMs,
},
},
};
}
return { text, tools };
}
I still show the assistant text. I just don’t let it overwrite the card. If searchInvoices failed and the model writes “you’re all set,” the user sees a red card and a dubious paragraph. That is an honest product. You can go further and hide the paragraph until every tool on that turn has ended, then, if any tool failed, show a fixed line like “I couldn’t complete this lookup.” I prefer that for mutations. For search, I still let the model talk — as long as the card shows count: 0 or a red error.
Things that were not worth it
I tried asking the model, in the system prompt, to “never claim a tool succeeded if it failed.” It helped in the first paragraph of a demo and failed as soon as the error message was long or looked like a stack trace. Prompts are not a control plane.
I also tried running tools on the client “for transparency.” That lasted until I needed a database. Keep execution on the server. Stream the events. Transparency is a UI problem, not a reason to ship your query layer to the browser.
Parallel tool calls are fine for reads. I would not run two mutations in parallel unless they cannot touch the same row. The loop above runs them sequentially on purpose.
If the model only ever answers from a system prompt, you do not need any of this. The registry and the idempotency key start to pay rent when something is written, or when a failure is indistinguishable from success in the transcript.
In my demo the missing relation was a flag I flipped on purpose: missingRelation: true. A boring outage, if this were a real database. The model turned it into a reassurance. Once the UI showed the error as its own object, the incident looked like what it was: a missing table, not a successful search.
That is the bar I now use. If the tool failed and a reasonable user would think it worked, the interface is lying — even if every token the model produced was, in isolation, well written.