Why Parallel Function Calls Need Safe Execution
When an LLM returns multiple function (tool_calls) in a single assistant message, it expects you to run them and return a tool message for every single tool_call_id. Running them naively can cause problems:
- One failure can crash everything: If you use
Promise.all()and one function throws an error, the whole batch rejects and you can miss returning tool responses for the other calls. - Invalid JSON arguments: The model can occasionally return malformed JSON in
function.arguments. - Unknown or risky tool names: A tool name might not exist in your registry, or might mutate state without proper validation or timeouts.
- Missing tool replies: Every
call.idmust get atoolresponse message so the next LLM turn does not fail with a missing/invalidtool_call_iderror.
How to Execute Parallel Function Calls Safely in TypeScript
- Map each
tool_callto its own isolated promise: Catch errors per tool call so one failure never aborts the rest of the batch. - Parse arguments and validate tool names safely: Wrap
JSON.parsein atry/catchand look up the handler in a typed registry (MaporRecord). - Add timeouts and size limits: Guard slow tools with a timeout so one hung call does not stall the entire turn.
- Use
Promise.all()over per-call settled results: Since each call catches its own errors and returns a structured result with itstool_call_id, you get all results cleanly and can appendrole: "tool"messages in order.
TypeScript Example
import type {
ChatCompletionMessageFunctionToolCall,
ChatCompletionMessageParam,
ChatCompletionToolMessageParam,
} from "openai/resources/chat/completions";
type ToolHandler = (args: Record<string, unknown>) => Promise<unknown> | unknown;
const toolRegistry: Record<string, ToolHandler> = {
async get_weather({ city }: { city?: unknown }) {
if (typeof city !== "string" || !city.trim()) {
throw new Error("Invalid 'city' argument");
}
return { city, tempC: 24, condition: "Clear" };
},
async get_exchange_rate({ base, target }: { base?: unknown; target?: unknown }) {
if (typeof base !== "string" || typeof target !== "string") {
throw new Error("'base' and 'target' currencies are required");
}
return { base: base.toUpperCase(), target: target.toUpperCase(), rate: 278.5 };
},
};
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Tool '${label}' timed out after${ms}ms`));
}, ms);
promise
.then((val) => {
clearTimeout(timer);
resolve(val);
})
.catch((err) => {
clearTimeout(timer);
reject(err);
});
});
}
async function runSingleToolCall(
call: ChatCompletionMessageFunctionToolCall,
timeoutMs = 8000
): Promise<ChatCompletionToolMessageParam> {
const fnName = call.function.name;
const handler = toolRegistry[fnName];
if (!handler) {
return {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ error: `Unknown tool: \${fnName}` }),
};
}
let parsedArgs: Record<string, unknown> = {};
try {
const raw = call.function.arguments || "{}";
const value = JSON.parse(raw);
if (value && typeof value === "object" && !Array.isArray(value)) {
parsedArgs = value as Record<string, unknown>;
} else {
throw new Error("Arguments must be a JSON object");
}
} catch (err) {
const message = err instanceof Error ? err.message : "Invalid JSON arguments";
return {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ error: message }),
};
}
try {
const output = await withTimeout(
Promise.resolve(handler(parsedArgs)),
timeoutMs,
fnName
);
const serialized =
typeof output === "string" ? output : JSON.stringify(output ?? null);
return {
role: "tool",
tool_call_id: call.id,
content: serialized,
};
} catch (err) {
const message = err instanceof Error ? err.message : "Tool execution failed";
return {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ error: message }),
};
}
}
export async function executeParallelToolCalls(
messages: ChatCompletionMessageParam[],
toolCalls: ChatCompletionMessageFunctionToolCall[],
timeoutMs = 8000
): Promise<ChatCompletionToolMessageParam[]> {
// Run all tool calls concurrently while isolating each failure
const toolMessages = await Promise.all(
toolCalls.map((call) => runSingleToolCall(call, timeoutMs))
);
// Append all tool responses in the same order as requested
messages.push(...toolMessages);
return toolMessages;
}
Helpful Tips for TypeScript Tool Runners
- Validate arguments with Zod: Instead of manual
typeofchecks, parseJSON.parse(...)through a Zod schema per tool for cleaner types and clear validation errors. - Cap concurrency for heavy tools: If a model can trigger dozens of slow API or database calls at once, use a small concurrency limiter instead of firing unlimited promises simultaneously.
- Return clear error JSON: Sending
{ error: "..." }back as atoolmessage lets the LLM adjust or explain the failure instead of crashing your conversation loop.
You must log in or register to comment.
