Vercel AI SDK Human in the Loop Guide
Giving an AI agent direct access to tools is powerful, but unrestricted access to sensitive operations like database deletions or payments creates serious risks. This guide is for TypeScript and Next.js developers who need reliable approval gates before their models execute sensitive tools. By the end of this guide, you will have a working approval flow that handles requests properly without running into deprecated APIs or serverless timeouts.
Before you start
- Node.js 20 or higher installed
- Basic knowledge of TypeScript and React
- An OpenAI API key or local Ollama instance
The HITL Problem and Modern Architecture
When an autonomous agent decides to invoke a destructive action, execution must pause until a human reviews the intent. In older versions of the SDK, developers often attached approval flags directly inside tool definitions. This pattern tightly coupled tool logic to specific runs and prevented tools from being reused flexibly across different security contexts.
Modern Vercel AI SDK architecture handles approval governance at the call level. This decoupling ensures that a tool can execute automatically in trusted background jobs while requiring explicit human confirmation when called in user-facing sessions or when specific high-risk parameters are present.
Project Setup and Dependencies
Setting up a dedicated workspace ensures all modern dependencies work together cleanly. Run the project initialization script below to create a project directory and enable ECMAScript modules in the package configuration.
Next, run the package installation command to add ai, @ai-sdk/openai, zod, and supporting developer tooling. This setup was verified on a clean Debian sandbox and installs the required packages without dependency conflicts.
# Initialize project directory
mkdir -p /root/hitl-demo && cd /root/hitl-demo && npm init -y
# Enable ESM modules
npm pkg set type="module"
# Install AI SDK core and helpers
npm install ai @ai-sdk/openai zod dotenv tsx
Output from our test run
$ mkdir -p /root/hitl-demo && cd /root/hitl-demo && npm init -y
Wrote to /root/hitl-demo/package.json:
{
"name": "hitl-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
$ npm pkg set type="module"
$ npm install ai @ai-sdk/openai zod dotenv tsx
added 15 packages, and audited 16 packages in 10s
2 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilitiesDefining Tools and Call-Level Approvals
Defining a tool now focuses entirely on its schema and execution logic. In the agent.ts file shown below, create the deleteAccountTool using tool and zod to validate incoming parameters such as the identifier and deletion reason.
Notice that the tool definition does not contain any approval-specific flags. The underlying execution code only runs once the approval criteria configured on the model call are completely satisfied.
import { tool } from 'ai';
import { z } from 'zod';
export const deleteAccountTool = tool({
description: 'Permanently delete a user account',
parameters: z.object({
userId: z.string().describe('The user ID to delete'),
reason: z.string().describe('Reason for deletion'),
}),
execute: async ({ userId, reason }) => {
// Real deletion logic runs only after approval
return { success: true, message: `Account ${userId} deleted: ${reason}` };
},
});
Handling Approval Requests on the Server
To intercept sensitive tool calls, specify the toolApproval option inside generateText or streamText. In the index.ts script below, the tool is mapped to the user approval status, signaling that any call to this tool must pause for human review.
When invoked, the runtime outputs an approval request part containing an identifier and the tool arguments. After review, you send back a corresponding approval response containing the matching approval identifier and a boolean decision to resume execution.
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { deleteAccountTool } from './agent.js';
async function run() {
const result = await generateText({
model: openai('gpt-4o-mini'),
tools: { deleteAccount: deleteAccountTool },
toolApproval: {
deleteAccount: 'user-approval',
},
prompt: 'Delete user account usr_9823 because of inactive subscription.',
});
console.log('Result parts:', JSON.stringify(result.response.messages, null, 2));
}
run().catch(console.error);
Testing with a Local Model
You can verify your agent logic without incurring third-party API costs by using a local Ollama instance. Run the tested commands below to download the Ollama installer, launch the background daemon, and pull the lightweight model.
This step was verified in a Debian sandbox environment, where Ollama initialized its local API and successfully pulled the model for local inference and tool calling.
# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh
# Start Ollama background daemon
pgrep -x ollama >/dev/null || (nohup ollama serve > /tmp/ollama.log 2>&1 &)
# Pull lightweight model
sleep 3 && ollama pull qwen2.5:1.5b
Output from our test run
$ curl -fsSL https://ollama.com/install.sh | sh
>>> Installing ollama to /usr/local
>>> Downloading ollama-linux-amd64.tar.zst
######################################################################## 100.0%
>>> Creating ollama user...
>>> Adding ollama user to render group...
>>> Adding ollama user to video group...
>>> Adding current user to ollama group...
>>> Creating ollama systemd service...
WARNING: systemd is not running
WARNING: Unable to detect NVIDIA/AMD GPU. Install lspci or lshw to automatically detect and install GPU dependen
cies.
>>> The Ollama API is now available at 127.0.0.1:11434.
>>> Install complete. Run "ollama" from the command line.
$ pgrep -x ollama >/dev/null || (nohup ollama serve > /tmp/ollama.log 2>&1 &)
$ sleep 3 && ollama pull qwen2.5:1.5b
pulling manifest
pulling 183715c43589: 100% ▕█████████████████████████████████████████████████ ▏ 985 MB/986 MB 31 MB/s 0s
pulling 377ac4d7aeef: 100% ▕██████████████████████████████████████████████████▏ 487 B
verifying sha256 digest
writing manifest
success
$Frontend Integration with React useChat
In frontend applications, client components can display interactive approval banners directly inside the chat feed. The useChat hook from @ai-sdk/react provides the modern addToolApprovalResponse helper to communicate decisions back to the server.
Review the ChatConfirmation.tsx component below to see how approval requests are rendered. When a user clicks either decision button, the component triggers the callback to resume the conversation stream.
import { useChat } from '@ai-sdk/react';
export function ApprovalBanner({ part, onConfirm }: { part: any; onConfirm: (approved: boolean) => void }) {
return (
<div className="p-4 border rounded bg-amber-50">
<p className="font-medium">Approval Required</p>
<p className="text-sm text-gray-600">Action: {part.toolCall.toolName}</p>
<div className="mt-3 flex gap-2">
<button onClick={() => onConfirm(true)} className="px-3 py-1 bg-green-600 text-white rounded text-sm">
Approve
</button>
<button onClick={() => onConfirm(false)} className="px-3 py-1 bg-red-600 text-white rounded text-sm">
Deny
</button>
</div>
</div>
);
}
Avoiding Serverless Timeouts
In-chat confirmations work well for immediate human decisions, but they fail when reviews take minutes or hours. Serverless functions on standard platforms shut down after short timeouts ranging from 15 to 60 seconds.
When an approval requires external escalation through Slack, email, or manager review, decouple the execution using durable background workflows. Suspending execution through durable primitives stores the agent state in a database until a webhook signals that the action was approved.
Wrap-up
Implementing human in the loop controls is a foundational requirement for building safe, production-grade AI agents. By placing approvals at the call level and structuring responses with proper IDs, your workflows stay reliable and secure across both client interactions and durable backend jobs.
FAQ
Why is needsApproval no longer recommended inside tool definitions?
Placing approval logic inside the tool tightly couples the action to specific execution environments. Setting approval rules at the call level allows the same tool to run automatically in safe contexts and require approval only under risky conditions.
How do you handle human approvals that take several hours?
Long approvals should not keep an HTTP connection open because serverless environments terminate after short timeouts. Instead, decouple the approval using durable workflows and webhooks that persist agent state until a human responds.
What data must be returned when approving a tool call?
You must send a tool approval response payload containing the matching approval identifier and a boolean flag indicating whether the execution was approved or denied.