Site icon Vinir Shah

Creating Your Own AI Agent from Scratch in Minutes

Creating Your Own AI Agent from Scratch in Minutes

Introduction

The way we use technology is changing as a result of AI agents. AI-powered assistants, such as chatbots and automation technologies, can effectively streamline processes. It is now simpler than ever to develop a personalized AI agent that can help consumers with particular issues, task automation, or insightful analysis thanks to AI breakthroughs. AI agents are becoming a crucial component of digital solutions, whether they are used for data retrieval, computation, or query responding.

In this blog, we’ll use JavaScript and OpenAI’s GPT model to create a basic AI agent. Financial computations like EMI calculations, compound interest calculations, and savings growth estimation will be carried out by this agent. The intention is to show how simple it is to incorporate AI into real-world applications that can help both people and companies.

Prerequisites

Before we dive in, ensure you have:

Step 1: Creating an OpenAI Account and Getting API Access

To use OpenAI’s API, follow these steps:

  1. Sign Up on OpenAI: Visit OpenAI’s website and create an account.
  2. Go to API Dashboard: Once logged in, navigate to the API section.
  3. Generate an API Key: Under the API Keys section, create a new key and copy it.
  4. Enable Billing: OpenAI offers a Pay-as-You-Go pricing model. Add a payment method to enable API access.
  5. Check Free Credits: OpenAI provides free tier credits for new users, so check your available quota before upgrading.

Step 2: Setting Up the Project

Create a new project folder and initialize a Node.js project:

mkdir ai-financial-agent
cd ai-financial-agent
npm init -y

Then, install the required dependencies:

npm install openai readline-sync

Step 3: Writing the AI Agent

Step 3.1: Creating the Main Script

Create a index.js file and import the required dependencies:

import OpenAI from "openai";
import readlineSync from 'readline-sync';

const OPENAI_API_KEY = "Your-API-Key-Here";
const client = new OpenAI({ apiKey: OPENAI_API_KEY });

Step 3.2: Defining Financial Calculation Functions

Add the following functions to perform financial calculations:

function calculateEMI(principal, rate, tenure) {
    const monthlyRate = rate / (12 * 100);
    const emi = (principal * monthlyRate * Math.pow(1 + monthlyRate, tenure)) /
                (Math.pow(1 + monthlyRate, tenure) - 1);
    return `Your EMI is ₹${emi.toFixed(2)} per month.`;
}

function calculateCompoundInterest(principal, rate, time, timesCompounded) {
    const r = rate / 100;
    const amount = principal * Math.pow(1 + (r / timesCompounded), timesCompounded * time);
    const interestEarned = amount - principal;
    return `After ${time} years, your total amount will be ₹${amount.toFixed(2)}, and the total interest earned will be ₹${interestEarned.toFixed(2)}.`;
}

function calculateSavingsGrowth(initial, monthly, rate, years) {
    let total = initial;
    for (let i = 0; i < years * 12; i++) {
        total = (total + monthly) * (1 + rate / (12 * 100));
    }
    return `Your savings after ${years} years will be ₹${total.toFixed(2)}.`;
}

const tools = {
    "calculateEMI": calculateEMI,
    "calculateCompoundInterest": calculateCompoundInterest,
    "calculateSavingsGrowth": calculateSavingsGrowth
};

Step 3.3: Defining the AI’s Behavior

Define the system prompt and message structure:

const SYSTEM_PROMPT = `
You are an AI Financial Calculator.
You strictly respond in JSON format and help users calculate financial metrics.

Available Tools:
1. calculateEMI(principal, rate, tenure) - Calculates EMI for a loan.
2. calculateCompoundInterest(principal, rate, time, timesCompounded) - Computes compound interest.
3. calculateSavingsGrowth(initial, monthly, rate, years) - Estimates savings growth.

Example JSON response:
{
    "type": "output",
    "output": "Your EMI is ₹2,500 per month."
}`;

const messages = [{ "role": 'system', content: SYSTEM_PROMPT }];

Step 3.4: Implementing the Chat Function

Add the main chat function to process user input:

async function chat() {
while (true) {
const query = readlineSync.question('>> ');
const userMessage = { type: 'user', user: query };
messages.push({ role: "user", content: JSON.stringify(userMessage) });
    while (true) {
        const chat = await client.chat.completions.create({
            model: "gpt-4o-mini",
            messages: messages,
            response_format: { type: "json_object" }
        });

        const result = chat.choices[0].message.content;
        messages.push({ role: 'assistant', content: result });

        console.log('\n\n-------------- START AI --------------');
        console.log(result);
        console.log('-------------- END AI --------------\n\n');

        const call = JSON.parse(result);

        if (call.type === "output") {
            console.log(`🤖: ${call.output}`);
            break;
        } else if (call.type === "action") {
            const fn = tools[call.function];
            const observation = fn(...Object.values(call.input));
            const obs = { type: "observation", observation: observation };
            messages.push({ role: "developer", content: JSON.stringify(obs) });
        }
    }
}
}

Step 4: Running the AI Agent

Run the script using:

node index.js

Try asking:

>> What will be my EMI for a ₹5,00,000 loan at 7% interest for 5 years?
>> How much will ₹1,00,000 grow in 10 years at 8% interest, compounded annually?
>> If I save ₹5,000 per month with ₹50,000 initial savings at 6% interest, what will I have in 5 years?

Conclusion

In just a few minutes, we built an AI-powered financial assistant that can perform complex calculations! This approach can be extended to various domains, such as health tracking, expense management, and business analytics. 🚀

Want to explore more? Try integrating this with a web or mobile app to enhance usability. 🎯

Exit mobile version