import { z } from "zod";
import { tool, generateText } from "ai";
const weatherTool = tool({
description: "Get weather for a location",
parameters: z.object({
location: z.string().describe("City name"),
unit: z.enum(["celsius", "fahrenheit"]).optional(),
}),
execute: async ({ location, unit = "celsius" }) => {
return { temperature: 22, conditions: "Sunny" };
},
});
const result = await generateText({
model: yourModel,
tools: { weather: weatherTool },
prompt: "What's the weather in Paris?",
});
toolChoice: 'auto'
toolChoice: 'required'
toolChoice: 'none'
toolChoice: { type: 'tool', toolName: 'weather' }
const { text, steps } = await generateText({
model: yourModel,
tools: { weather: weatherTool },
maxSteps: 3,
prompt: "Weather in Paris?",
onStepFinish({ text, toolCalls, toolResults }) {
console.log(`Step completed with ${toolCalls.length} tool calls`);
},
});
const allToolCalls = steps.flatMap((step) => step.toolCalls);
4. Error Handling
try {
const result = await generateText({
model: yourModel,
tools: { weather: weatherTool },
prompt: "Weather forecast?",
});
} catch (error) {
if (NoSuchToolError.isInstance(error)) {
}
if (InvalidToolArgumentsError.isInstance(error)) {
}
if (ToolExecutionError.isInstance(error)) {
}
}
return result.toDataStreamResponse({
getErrorMessage: (error) => {
if (NoSuchToolError.isInstance(error)) return "Unknown tool requested";
},
});
5. Type Safety
import { ToolCallUnion, ToolResultUnion } from "ai";
const myTools = {
weather: weatherTool,
calculator: calculatorTool,
};
type MyToolCall = ToolCallUnion<typeof myTools>;
type MyToolResult = ToolResultUnion<typeof myTools>;
function processToolResult(result: MyToolResult) {
if (result.toolName === "weather") {
return `It's ${result.result.temperature}° and ${result.result.conditions}`;
}
}
6. Tool Context & Execution Options
const contextTool = tool({
description: "Sample tool with context",
parameters: z.object({ query: z.string() }),
execute: async (args, context) => {
const id = context.toolCallId;
const history = context.messages;
context.abortSignal.addEventListener("abort", () => {
});
return { result: "Done" };
},
});
const result = await generateText({
model: yourModel,
tools: myTools,
prompt: "Calculate 5+7",
experimental_repairToolCall: async ({ toolCall, tools, error }) => {
if (error.name === "InvalidToolArgumentsError") {
return {
...toolCall,
args: JSON.stringify({ a: 5, b: 7 }),
};
}
return null;
},
});
8. Conversation Management
const messages = [{ role: "user", content: "What's the weather?" }];
const { response } = await generateText({
model: yourModel,
tools: { weather: weatherTool },
messages,
});
messages.push(...response.messages);