Agent function examples
Complete agent functions you can adapt. Each table, column or API drawn as a chip, such as orders, orders.email or createTicket, is a reference you insert from the editor's suggestions. When you rebuild an example, pick your own tables, columns and APIs: type " after tables.search( or apis.execute(, or "@ anywhere else. See Get suggestions.
Look up a customer's recent orders
An agent tool with one input, email. The agent calls it when a user asks about their orders.
import { tables } from "@yellow/bot";
export default async function* ({ email }) {
const orders = await tables.search(
"orders",
{ "orders.email": email },
{ sort: { created_at: -1 }, limit: 3 },
);
if (orders.length === 0) {
return { found: false, message: "No orders found for this email address." };
}
return {
found: true,
orders: orders.map((order) => ({
id: order.order_id,
status: order.status,
total: order.total,
})),
};
}
Save a lead without duplicates
A Function node that checks for an existing phone number before adding a row.
import { tables } from "@yellow/bot";
export default async function* ({ name, phone }, context) {
const existing = await tables.search(
"leads",
{ "leads.phone": phone },
{ limit: 1 },
);
if (existing.length > 0) {
return { saved: false, reason: "duplicate" };
}
const result = await tables.insert("leads", {
"leads.name": name,
"leads.phone": phone,
"leads.channel": context.source,
});
return { saved: result.success };
}
Create a support ticket
Calls a ticketing API and keeps the ticket number in a global variable for later steps.
import { apis, variables } from "@yellow/bot";
export default async function* ({ subject, details }, context) {
try {
const response = await apis.execute("createTicket", {
subject,
description: details,
customerId: context.sender,
});
await variables.global.set({ lastTicketId: response.body.ticketId });
return { created: true, ticketId: response.body.ticketId };
} catch (error) {
console.error("Ticket creation failed", error);
return { created: false, message: "We couldn't create a ticket right now. Please try again shortly." };
}
}
Cancel an order
Checks the order, asks your system to cancel it, and only then updates the table.
import { apis, tables } from "@yellow/bot";
export default async function* ({ orderId }) {
const [order] = await tables.search(
"orders",
{ "orders.order_id": orderId },
{ limit: 1 },
);
if (!order) {
return { ok: false, message: "Order not found." };
}
if (order.status === "shipped") {
return { ok: false, message: "This order has already shipped and can't be cancelled." };
}
try {
await apis.execute("cancelOrder", { orderId });
} catch (error) {
console.error("Cancellation failed", error);
return { ok: false, message: "We couldn't cancel the order. An agent will follow up." };
}
await tables.update("orders", {
set: { "orders.status": "cancelled" },
where: [{ column: "orders.order_id", operation: "equals", value: orderId }],
});
return { ok: true };
}
Validate and normalise what the user typed
An agent tool that checks a phone number and an email before anything is saved. It returns a clear reason, so the agent can ask again.
export default async function* ({ phone, email }) {
const digits = String(phone ?? "").replace(/\D/g, "");
const normalisedPhone = digits.length === 10 ? `+91${digits}` : digits.length === 12 && digits.startsWith("91") ? `+${digits}` : null;
const normalisedEmail = String(email ?? "").trim().toLowerCase();
const problems = [];
if (!normalisedPhone) {
problems.push("phone should have 10 digits");
}
if (!/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/.test(normalisedEmail)) {
problems.push("email doesn't look right");
}
if (problems.length > 0) {
return { valid: false, problems };
}
return { valid: true, phone: normalisedPhone, email: normalisedEmail };
}
Tell the user, then book and stop
Available from runtime 2026.10.19. The function says what it's doing, books the slot, confirms it, and halts the agent's turn so the agent doesn't repeat the confirmation.
import { apis, variables } from "@yellow/bot";
import { sendMessage, sendCards } from "@yellow/bot/responses";
import { haltTurn } from "@yellow/bot/agent";
export default async function* ({ slot, name }, context) {
yield sendMessage("Booking that for you…");
let booking;
try {
const response = await apis.execute("bookAppointment", { slot, name, phone: context.sender });
booking = response.body;
} catch (error) {
console.error("Booking failed", error);
return { booked: false, message: "That slot was just taken. Please pick another." };
}
await variables.global.set({ lastBookingId: booking.id });
if (context.callSid) {
yield sendMessage(`You're booked for ${slot}. Your reference is ${booking.id}.`);
} else {
yield sendCards([
{
title: `Booked: ${slot}`,
description: `Reference ${booking.id}`,
buttons: ["Reschedule", "Cancel booking"],
},
]);
}
return haltTurn({ booked: true, reference: booking.id });
}
Total a customer's open orders across pages
Reads up to 500 rows with paging and adds them up, using columns to keep each row small.
import { tables } from "@yellow/bot";
export default async function* ({ email }) {
let total = 0;
let count = 0;
for (let page = 0; page < 5; page++) {
const rows = await tables.search(
"orders",
{ "orders.email": email, "orders.status": "open" },
{ sort: { id: 1 }, limit: 100, skip: count, columns: ["orders.total"] },
);
for (const row of rows) {
total += Number(row.total) || 0;
}
count += rows.length;
if (rows.length < 100) {
break;
}
}
const formatted = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(total);
return { openOrders: count, total, formatted };
}
Combine two APIs into one answer
Calls two APIs at the same time and returns one summary. If either fails, the answer says what's missing instead of failing the whole tool.
import { apis } from "@yellow/bot";
export default async function* ({ customerId }) {
const [account, offers] = await Promise.allSettled([
apis.execute("getAccount", { customerId }),
apis.execute("getOffers", { customerId }),
]);
return {
plan: account.status === "fulfilled" ? account.value.body.plan : null,
balance: account.status === "fulfilled" ? account.value.body.balance : null,
offers: offers.status === "fulfilled" ? offers.value.body.items.slice(0, 3) : [],
missing: [
account.status === "rejected" ? "account" : null,
offers.status === "rejected" ? "offers" : null,
].filter(Boolean),
};
}
Check business hours
Uses the current time to decide whether to offer a live agent. The function's clock is in UTC, so the offset is added. See Dates and time zones.
export default async function* () {
const ist = new Date(Date.now() + 5.5 * 60 * 60 * 1000);
const day = ist.getUTCDay(); // 0 is Sunday
const hour = ist.getUTCHours();
const open = day >= 1 && day <= 5 && hour >= 9 && hour < 18;
return { open, nextOpening: open ? null : "Monday to Friday, 9 am to 6 pm IST" };
}
More
- Remember the customer between steps, with global variables
- Sign a webhook, with crypto
- Send messages, work with voice calls and halt the agent's turn
- Handle errors, when to return an error and when to throw
- Tests for a function, with mocks