Build a simple AI agent that can use multiple tools (search, calculator, database query) to answer questions.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Implementation:

import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

// Tool implementations
const tools = {
  search: (query) => {
    // Mock search - in reality, call a search API
    return `Search results for "${query}": Latest news and articles...`;
  },
  
  calculator: (expression) => {
    try {
      // WARNING: eval is dangerous in production. Use a safe math parser instead.
      return eval(expression).toString();
    } catch (error) {
      return "Error in calculation";
    }
  },
  
  database_query: (query) => {
    // Mock database - in reality, query actual database
    const mockDB = {
      "total_users": "10,542",
      "revenue_today": "$15,230"
    };
    return mockDB[query] || "Data not found";
  }
};

async function runAgent(userQuery) {
  const toolDefinitions = [
    {
      type: "function",
      function: {
        name: "search",
        description: "Search the internet for information",
        parameters: {
          type: "object",
          properties: { query: { type: "string" } },
          required: ["query"]
        }
      }
    },
    {
      type: "function",
      function: {
        name: "calculator",
        description: "Perform mathematical calculations",
        parameters: {
          type: "object",
          properties: { expression: { type: "string" } },
          required: ["expression"]
        }
      }
    },
    {
      type: "function",
      function: {
        name: "database_query",
        description: "Query the database for metrics",
        parameters: {
          type: "object",
          properties: { query: { type: "string" } },
          required: ["query"]
        }
      }
    }
  ];

  let messages = [
    {
      role: "system",
      content: "You are a helpful assistant with access to tools. Use them when needed."
    },
    { role: "user", content: userQuery }
  ];

  // Agent loop (max 5 iterations to prevent infinite loops)
  for (let i = 0; i < 5; i++) {
    const response = await openai.chat.completions.create({
      model: "gpt-4",
      messages,
      tools: toolDefinitions,
    });

    const message = response.choices[0].message;
    messages.push(message);

    if (!message.tool_calls) {
      // No more tool calls, return final answer
      return message.content;
    }

    // Execute tool calls
    for (const toolCall of message.tool_calls) {
      const functionName = toolCall.function.name;
      const args = JSON.parse(toolCall.function.arguments);
      
      const result = tools[functionName](...Object.values(args));
      
      messages.push({
        role: "tool",
        tool_call_id: toolCall.id,
        content: result
      });
    }
  }

  return "Agent reached maximum iterations";
}

// Usage
const answer = await runAgent("What is 25% of our total users?");
console.log(answer);