Overview
Tools allow your agents to perform actions beyond text generation. This example demonstrates:- Creating custom tools with Zod schemas
- Managing state across multiple interactions
- Using state variables in agent instructions
- Building practical applications with persistent data
Tools are the bridge between your AI agent and the real world - they can call APIs, modify databases, send emails, and more.
Shopping Cart Example
We’ll build a shopping cart assistant that can:- Add items with quantities and prices
- View cart contents and totals
- Track state across multiple requests
Complete Example
import { createTool } from "@iqai/adk";
import * as z from "zod";
export const addItemTool = createTool({
name: "add_item",
description: "Add an item to the shopping cart",
schema: z.object({
item: z.string().describe("Item name"),
quantity: z.number().default(1).describe("Quantity to add"),
price: z.number().describe("Price per item"),
}),
fn: ({ item, quantity, price }, context) => {
const cart: { item: string; quantity: number; price: number }[] =
context.state.get("cart", []);
const existingItemIndex = cart.findIndex(
(cartItem) => cartItem.item === item,
);
let updatedCart: { item: string; quantity: number; price: number }[];
if (existingItemIndex > -1) {
updatedCart = cart.map((cartItem, index) => {
if (index === existingItemIndex) {
return { ...cartItem, quantity: cartItem.quantity + quantity };
}
return cartItem;
});
} else {
updatedCart = [...cart, { item, quantity, price }];
}
context.state.set("cart", updatedCart);
context.state.set("cartCount", updatedCart.length);
const total = updatedCart.reduce(
(sum, cartItem) => sum + cartItem.quantity * cartItem.price,
0,
);
return {
success: true,
item,
quantity,
cartTotal: total,
message: `Added ${quantity}x ${item} to cart`,
};
},
});
export const viewCartTool = createTool({
name: "view_cart",
description: "View current shopping cart contents",
fn: (_, context) => {
const cart = context.state.get("cart", []);
const total = cart.reduce(
(sum, item) => sum + item.quantity * item.price,
0,
);
return {
cart,
total,
itemCount: cart.reduce((sum, item) => sum + item.quantity, 0),
message:
cart.length > 0
? `Cart has ${cart.length} different items`
: "Cart is empty",
};
},
});
The
context parameter in tool functions provides access to:context.state: Get and set state variablescontext.session: Access session metadatacontext.saveArtifact(): Save files and artifactscontext.memory: Query long-term memory
import { AgentBuilder } from "@iqai/adk";
import dedent from "dedent";
import { addItemTool, viewCartTool } from "./tools";
export function getRootAgent() {
const initialState = {
cart: [],
cartCount: 0,
};
return AgentBuilder.create("shopping_cart_agent")
.withModel(process.env.LLM_MODEL || "gemini-3-flash-preview")
.withInstruction(
dedent`
You are a shopping cart assistant. Help users manage their cart.
Current cart state:
- Items in cart: {cartCount}
- Cart contents: {cart}
You can add items and view the cart. Always be helpful with pricing and quantities.
`,
)
.withTools(addItemTool, viewCartTool)
.withQuickSession({ state: initialState })
.build();
}
State variables in instructions (like
{cartCount} and {cart}) are automatically replaced with their current values at runtime. This gives your agent context about the current state.import { ask } from "../utils";
import { getRootAgent } from "./agents/agent";
async function main() {
const { runner } = await getRootAgent();
const questions = [
"Add 2 apples to my cart at $1.50 each",
"Add 1 banana for $0.75",
"Show me my complete cart with total",
];
for (const question of questions) {
await ask(runner, question);
}
}
main().catch(console.error);
Expected Output
Key Concepts
Tool Schema Definition
Zod schemas define the input structure for your tools:- Type Safety: TypeScript knows the exact parameter types
- Validation: Inputs are validated before the function runs
- LLM Guidance: Descriptions help the AI understand parameter purposes
State Management
State persists across multiple interactions within a session:State in Instructions
Reference state variables in your agent’s instructions:Advanced Tool Patterns
Async Tools
Tools can be asynchronous for API calls or database operations:Tools with Multiple State Operations
Error Handling in Tools
Built-in Tools
ADK-TS provides several built-in tools:RecallMemoryTool: Search long-term memoryFileReadTool: Read file contentsFileWriteTool: Write to filesHttpRequestTool: Make HTTP requestsAskUserTool: Prompt for user input
Use Cases
E-commerce
Cart management, inventory checks, order processing
Data Processing
ETL operations, data validation, transformations
API Integration
Call external services, webhooks, third-party APIs
File Operations
Read, write, process documents and data files
Next Steps
Database Sessions
Persist state beyond in-memory sessions
Multi-Agent Systems
Coordinate multiple agents with shared tools