Sonamu allows you to create custom AI agents by extending BaseAgentClass. By defining tools using the @tools decorator, the LLM can select and execute appropriate tools based on the context.
BaseAgentClass
This is the base class for AI agents.
Basic Structure
import { BaseAgentClass, tools } from "sonamu/ai";import { openai } from "@ai-sdk/openai";import { z } from "zod";class CustomerSupportAgentClass extends BaseAgentClass<{ userId: number;}> { constructor() { super("CustomerSupportAgent"); } @tools({ description: "Retrieves order information", schema: { input: z.object({ orderId: z.number(), }), output: z.object({ orderId: z.number(), status: z.string(), items: z.array(z.string()), }), }, }) async getOrder(input: { orderId: number }) { // Order retrieval logic return { orderId: input.orderId, status: "shipped", items: ["Product A", "Product B"], }; }}export const CustomerSupportAgent = new CustomerSupportAgentClass();
@tools({ description: "Cancel order (dangerous operation)", schema: { /* ... */ }, needsApproval: true, // Requires user approval})
Use Case: Dangerous operations like data deletion or payments
Practical Examples
1. Hotel Booking Agent
import { BaseAgentClass, tools } from "sonamu/ai";import { z } from "zod";class HotelBookingAgentClass extends BaseAgentClass<{ userId: number; locale: string;}> { constructor() { super("HotelBookingAgent"); } @tools({ description: "Searches for available hotels by city and date", schema: { input: z.object({ city: z.string().describe("City name"), checkIn: z.string().describe("Check-in date (YYYY-MM-DD)"), checkOut: z.string().describe("Check-out date (YYYY-MM-DD)"), guests: z.number().describe("Number of guests"), }), output: z.array( z.object({ hotelId: z.number(), name: z.string(), price: z.number(), rating: z.number(), }), ), }, }) async searchHotels(input: { city: string; checkIn: string; checkOut: string; guests: number }) { // Search hotels from DB const hotels = await HotelModel.findMany("A", { sonamuFilter: { city: input.city, // before/after are exclusive (< / >); date fields have no lte/gte available_from: { before: new Date(input.checkIn) }, available_to: { after: new Date(input.checkOut) }, capacity: { gte: input.guests }, }, }); return hotels.rows.map((hotel) => ({ hotelId: hotel.id, name: hotel.name, price: hotel.price_per_night, rating: hotel.rating, })); } @tools({ description: "Books a hotel", schema: { input: z.object({ hotelId: z.number().describe("Hotel ID"), checkIn: z.string(), checkOut: z.string(), guests: z.number(), }), output: z.object({ bookingId: z.number(), confirmationNumber: z.string(), totalPrice: z.number(), }), }, needsApproval: true, // User approval before booking }) async bookHotel(input: { hotelId: number; checkIn: string; checkOut: string; guests: number }) { const userId = this.store?.userId; // Create booking const [bookingId] = await BookingModel.save([{ user_id: userId, hotel_id: input.hotelId, check_in: input.checkIn, check_out: input.checkOut, guests: input.guests, status: "confirmed", }]); const booking = await BookingModel.findById("A", bookingId); return { bookingId: booking.id, confirmationNumber: booking.confirmation_number, totalPrice: booking.total_price, }; } @tools({ description: "Cancels a booking", schema: { input: z.object({ bookingId: z.number().describe("Booking ID"), }), output: z.object({ success: z.boolean(), refundAmount: z.number(), }), }, needsApproval: true, // User approval before cancellation }) async cancelBooking(input: { bookingId: number }) { const booking = await BookingModel.findById("A", input.bookingId); // Process cancellation await BookingModel.getPuri("w").table("bookings").where("id", booking.id).update({ status: "cancelled" }); // Process refund const refundAmount = booking.total_price * 0.9; // 10% fee return { success: true, refundAmount, }; }}export const HotelBookingAgent = new HotelBookingAgentClass();
2. Data Analysis Agent
A tool that runs LLM-generated SQL can be steered by prompt injection into running whatever SQL an attacker wants. A
regex check such as /^SELECT/i does not stop multi-statement input like SELECT 1; DROP TABLE users, so the example
below uses three layers.
Least-privilege DB role: connect as a dedicated role that has SELECT only on allowed views. This is the real
boundary that blocks writes and reads of sensitive tables.
Single-statement parser: use the PostgreSQL parser (libpg-query)
to check that the SQL is exactly one SELECT statement.
Read-only transaction: run the query in a READ ONLY transaction with a statement_timeout.
First, create the views exposed to the AI and the dedicated role with a DB admin account.
-- View that contains only the columns exposed to the AICREATE SCHEMA ai_readonly;CREATE VIEW ai_readonly.daily_sales AS SELECT created_at::date AS day, count(*) AS order_count, sum(total_price) AS revenue FROM orders GROUP BY 1;-- Dedicated role that can read only the allowed viewsCREATE ROLE ai_analyst LOGIN PASSWORD 'replace-with-a-strong-password';ALTER ROLE ai_analyst SET default_transaction_read_only = on;ALTER ROLE ai_analyst SET statement_timeout = '5s';GRANT USAGE ON SCHEMA ai_readonly TO ai_analyst;GRANT SELECT ON ai_readonly.daily_sales TO ai_analyst;
Install the parser with pnpm add libpg-query, and put the connection settings in AI_ANALYST_DB_* environment
variables.
Do not use BaseModel.getPuri("r") for this. Without a read-only replica, "r" connects with the same account as
the main DB and has that accountβs privileges, which usually include writing and reading every table.
import { BaseAgentClass, tools } from "sonamu/ai";import knex from "knex";import { parse } from "libpg-query";import { z } from "zod";// Connection for the AI tool only: connects as the ai_analyst role created above.const analystDB = knex({ client: "pg", connection: { host: process.env.AI_ANALYST_DB_HOST, port: Number(process.env.AI_ANALYST_DB_PORT ?? 5432), user: process.env.AI_ANALYST_DB_USER, password: process.env.AI_ANALYST_DB_PASSWORD, database: process.env.AI_ANALYST_DB_NAME, }, pool: { min: 0, max: 2 },});/** * Uses the PostgreSQL parser to check that the SQL is exactly one SELECT statement. * A single statement also prevents ending the read-only transaction with an injected `COMMIT`. */async function assertSingleSelect(sql: string): Promise<void> { const { stmts = [] } = await parse(sql); const stmt = stmts.length === 1 ? stmts[0]?.stmt : undefined; if (stmt === undefined || !("SelectStmt" in stmt)) { throw new Error("Only a single SELECT statement is allowed"); }}class DataAnalystAgentClass extends BaseAgentClass<{ sessionId: string;}> { constructor() { super("DataAnalystAgent"); } @tools({ description: "Runs a single SELECT statement against the views in the ai_readonly schema", schema: { input: z.object({ query: z.string().describe("A single SELECT statement to run"), }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), rowCount: z.number(), }), }, }) async executeQuery(input: { query: string }) { await assertSingleSelect(input.query); // The read-only transaction also blocks writes such as data-modifying CTEs, SELECT INTO, and nextval(). const rows = await analystDB.transaction( async (trx) => { await trx.raw("SET LOCAL statement_timeout = '5s'"); const result = await trx.raw(input.query); return result.rows as Record<string, unknown>[]; }, { readOnly: true }, ); return { rows, rowCount: rows.length }; } @tools({ description: "Creates chart configuration for data visualization", schema: { input: z.object({ data: z.array(z.record(z.string(), z.unknown())), xAxis: z.string().describe("X-axis column name"), yAxis: z.string().describe("Y-axis column name"), chartType: z.enum(["bar", "line", "pie"]), }), output: z.object({ chartId: z.string(), config: z.any(), }), }, }) async createChart(input: { data: Array<Record<string, any>>; xAxis: string; yAxis: string; chartType: "bar" | "line" | "pie"; }) { const chartId = `chart_${Date.now()}`; // Create chart configuration const config = { type: input.chartType, data: { labels: input.data.map((row) => row[input.xAxis]), datasets: [ { label: input.yAxis, data: input.data.map((row) => row[input.yAxis]), }, ], }, }; return { chartId, config }; } @tools({ description: "Calculates statistical summary (mean, median, standard deviation, etc.)", schema: { input: z.object({ data: z.array(z.number()), }), output: z.object({ mean: z.number(), median: z.number(), stdDev: z.number(), min: z.number(), max: z.number(), }), }, }) async calculateStats(input: { data: number[] }) { const sorted = [...input.data].sort((a, b) => a - b); const sum = input.data.reduce((a, b) => a + b, 0); const mean = sum / input.data.length; const median = sorted.length % 2 === 0 ? (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2 : sorted[Math.floor(sorted.length / 2)]; const variance = input.data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / input.data.length; const stdDev = Math.sqrt(variance); return { mean, median, stdDev, min: sorted[0], max: sorted[sorted.length - 1], }; }}export const DataAnalystAgent = new DataAnalystAgentClass();
Tool Description Clarity: Write detailed descriptions that the LLM can understand
// β Uncleardescription: "Order lookup";// β Cleardescription: "Takes an order ID and returns detailed order information (status, items, price)";
Detailed Input Schema: Use describe()
input: z.object({ orderId: z.number().describe("Unique ID of the order to retrieve"), includeItems: z.boolean().describe("Whether to include the list of order items"),});
Require Approval for Dangerous Operations: needsApproval
async getOrder(input: { orderId: number }) { const order = await OrderModel.findOne("A", { id: input.orderId }); if (!order) { throw new Error(`Order ID ${input.orderId} not found`); } return order;}
Check for Undefined When Accessing Store
const userId = this.store?.userId;if (!userId) { throw new Error("User information not available");}
Avoid Tool Name Conflicts: Use clear names
@tools({ name: 'hotel_search', // Clear name // ...})