AI Agents
Rules
- Define tools as typed functions with descriptions — the model picks which tool to call
- Tool schema:
{ name, description, parameters: zodSchema, execute: async (args) => result }
- Multi-step loop: send messages → model returns tool call → execute tool → feed result back → repeat until done
maxSteps limit to prevent infinite loops — default 5-10 steps depending on complexity
- Structured outputs with Zod:
generateObject({ schema: z.object({...}) }) for guaranteed shape
- Retry logic: wrap tool execution in try/catch, retry transient failures 2-3 times with exponential backoff
- Agent orchestration: break complex tasks into sub-agents with focused tool sets, coordinator agent delegates
- Always validate tool results before feeding back to the model — sanitize untrusted data
- Use
streamText with onToolCall for real-time visibility into agent reasoning
Patterns
const tools = {
searchDatabase: tool({
description: "Search the product database",
parameters: z.object({ query: z.string(), limit: z.number().default(10) }),
execute: async ({ query, limit }) => db.products.search(query, limit),
}),
};
const result = await generateText({
model,
tools,
maxSteps: 10,
messages,
});
Avoid
- Giving agents unrestricted tool access — scope tools to the task
- Missing
maxSteps — agents can loop forever
- Trusting tool outputs without validation — always check before acting on results
- Monolithic agents — prefer focused sub-agents over one agent with 20+ tools