import OpenAI from "openai";
import Nimble from "@nimble-way/nimble-js";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const nimble = new Nimble({ apiKey: process.env.NIMBLE_API_KEY });
const tools: OpenAI.ChatCompletionTool[] = [
{
type: "function",
function: {
name: "nimble_search",
description: "Search the web using Nimble and return relevant results.",
parameters: {
type: "object",
properties: {
query: { type: "string", description: "The search query to execute" },
},
required: ["query"],
},
},
},
{
type: "function",
function: {
name: "nimble_extract",
description: "Extract clean content from a URL using Nimble.",
parameters: {
type: "object",
properties: {
url: { type: "string", description: "The URL to extract content from" },
},
required: ["url"],
},
},
},
];
async function handleToolCall(name: string, args: Record<string, string>) {
if (name === "nimble_search") {
return await nimble.search({ query: args.query });
}
if (name === "nimble_extract") {
return await nimble.extract({ url: args.url });
}
}
const messages: OpenAI.ChatCompletionMessageParam[] = [
{ role: "system", content: "You are a research assistant with access to real-time web data." },
{ role: "user", content: "What are the latest trends in AI agents?" },
];
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages,
tools,
});
const assistantMsg = response.choices[0].message;
messages.push(assistantMsg);
if (assistantMsg.tool_calls) {
for (const tc of assistantMsg.tool_calls) {
const args = JSON.parse(tc.function.arguments);
const result = await handleToolCall(tc.function.name, args);
messages.push({
role: "tool",
tool_call_id: tc.id,
content: JSON.stringify(result),
});
}
const final = await openai.chat.completions.create({
model: "gpt-4o",
messages,
});
console.log(final.choices[0].message.content);
}