import OpenAI from "openai";
import readline from "node:readline/promises";
const client = new OpenAI({ baseURL: "https://api.opper.ai/v3/compat", apiKey: process.env.OPPER_API_KEY });
// A tiny order "database"
const ORDERS: Record<string, any> = {
"123123": {
email: "santa@clau.se",
status: "out for delivery",
eta: "2024-11-08",
items: ["Large wooden sled", "Reindeer harness (x2)"],
address: "Snowy Mountain 123, Greenland",
},
};
function getOrderStatus(orderId: string, email: string) {
const o = ORDERS[orderId];
if (!o || o.email.toLowerCase() !== email.toLowerCase())
return { found: false, reason: "No order matches that ID and email." };
const { status, eta, items, address } = o;
return { found: true, status, eta, items, address };
}
const tools = [{
type: "function" as const,
function: {
name: "get_order_status",
description: "Look up an order's status and contents by order ID and the email used to place it.",
parameters: {
type: "object",
properties: { order_id: { type: "string" }, email: { type: "string" } },
required: ["order_id", "email"],
},
},
}];
const system =
"You are a friendly customer support agent for a sleigh supply store. " +
"Use the get_order_status tool to answer questions about orders. " +
"Ask for the order ID and email if you need them. Keep replies short.";
async function reply(messages: any[]) {
// Loop until the model answers in text instead of calling a tool.
while (true) {
const r = await client.chat.completions.create({ model: "openai/gpt-5-mini", messages, tools });
const msg = r.choices[0].message;
messages.push(msg);
if (!msg.tool_calls) return msg.content;
for (const call of msg.tool_calls) {
const args = JSON.parse(call.function.arguments);
const result = getOrderStatus(args.order_id, args.email);
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}
}
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const messages: any[] = [{ role: "system", content: system }];
while (true) {
const user = await rl.question("User: ");
if (["quit", "exit"].includes(user.toLowerCase())) break;
messages.push({ role: "user", content: user });
console.log("Assistant:", await reply(messages));
}