Skip to content

TheODDYSEY/Math-LLM-Agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ› οΈ Integrating AI Agents and MathJS for Robust Mathematical Processing

Project Screenshot

πŸ§ πŸ’‘ Large Language Models (LLMs) like GPT often struggle with mathematical calculations and complex logical reasoning. However, we can enhance their abilities by combining them with AI agents, MathJS, and BaseAI tool calls. This approach allows us to create a powerful calculator that leverages the strengths of both LLMs and specialized math tools.

πŸ”§πŸ’»

Prerequisites

Before starting, ensure you have the following:

  • Node.js installed 🐍
  • npm (Node Package Manager) πŸ’Ό
  • A Langbase account for API key πŸ”‘
  • An OpenAI account for LLM key (GPT-4o mini used in this example) πŸ”’

Project Setup

Step 1: Create Project Directory and Install Dependencies

mkdir my-math-agent
cd my-math-agent
npm init -y
npm install dotenv mathjs

Step 2: Create AI Agent Pipe

npx baseai@latest pipe

Follow the prompts to create a new pipe named "pipe-with-tool".

Step 3: Set Up .env File

Create a .env file in the project root and add your API keys:

LANGBASE_API_KEY=your_langbase_api_key_here
OPENAI_API_KEY=your_openai_api_key_here

Step 4: Configure AI Agent Pipe

Edit the generated pipe-with-tool.ts file:

import { PipeI } from '@baseai/core';

const pipeWithTool = (): PipeI => ({
   apiKey: process.env.LANGBASE_API_KEY!,
   name: 'pipe-with-tool',
   description: 'An AI agent pipe that can call tools',
   status: 'private',
   model: 'openai:gpt-4o-mini',
   stream: true,
   json: false,
   store: true,
   moderate: true,
   top_p: 1,
   max_tokens: 1000,
   temperature: 0.7,
   presence_penalty: 1,
   frequency_penalty: 1,
   stop: [],
   tool_choice: 'auto',
   parallel_tool_calls: true,
   messages: [{ role:'system', content: `You are a helpful AI assistant that will work as a calculator.` }],
   variables: [],
   memory: [],
   tools: []
});

export default pipeWithTool;

Step 5: Create Calculator Tool

Generate a new tool:

npx baseai@latest tool

Name it "Calculator" and describe it as "Evaluate mathematical expressions".

Edit the generated calculator.ts file:

import * as math from 'mathjs';

export async function calculator({expression}: {expression: string}) {
   return math.evaluate(expression);
}

const toolCalculator = () => ({
   run: calculator,
   type: 'function' as const,
   function: {
       name: 'calculator',
       description: `A tool that can evaluate mathematical expressions. Example expressions: '5.6 * (5 + 10.5)', '7.86 cm to inch', 'cos(80 deg) ^ 4'`,
       parameters: {
           type: 'object',
           required: ['expression'],
           properties: {
               expression: {
                   type: 'string',
                   description: 'The mathematical expression to evaluate.',
               },
           },
       },
   },
});

export default toolCalculator;

Step 6: Integrate Tools in AI Agent Pipe

Update pipe-with-tool.ts:

import {PipeI} from '@baseai/core';
import toolCalculator from './tools/calculator';

const pipeWithTools = (): PipeI => ({
   apiKey: process.env.LANGBASE_API_KEY!,
   name: 'pipe-with-tool',
   description: 'An AI agent pipe that can call tools',
   status: 'public',
   model: 'openai:gpt-4o-mini',
   stream: false,
   json: false,
   store: true,
   moderate: true,
   top_p: 1,
   max_tokens: 1000,
   temperature: 0.7,
   presence_penalty: 1,
   frequency_penalty: 1,
   stop: [],
   tool_choice: 'auto',
   parallel_tool_calls: true,
   messages: [{role:'system', content: `You are a helpful AI assistant that will work as a calculator.`}],
   variables: [],
   memory: [],
   tools: [ toolCalculator()],
});

export default pipeWithTools;

Step 7: Create Interactive CLI

Create index.ts:

import 'dotenv/config';
import { Pipe } from '@baseai/core';
import inquirer from 'inquirer';
import ora from 'ora';
import chalk from 'chalk';
import pipePipeWithTool from './baseai/pipes/pipe-with-tool';

const pipe = new Pipe(pipePipeWithTool());

async function main() {
   const initialSpinner = ora('Conversation with Math agent...').start();
   try {
       const { completion: calculatorTool} = await pipe.run({
           messages: [{ role: 'user', content: 'Hello' }],
       });
       initialSpinner.stop();
       console.log(chalk.cyan('Math agent response...'));
       console.log(calculatorTool);
   } catch (error) {
       initialSpinner.stop();
       console.error(chalk.red('Error processing initial request:'), error);
   }

   while (true) {
       const { userMsg } = await inquirer.prompt([
           {
               type: 'input',
               name: 'userMsg',
               message: chalk.blue('Enter your query (or type "exit" to quit):'),
           },
       ]);

       if (userMsg.toLowerCase() === 'exit') {
           console.log(chalk.green('Goodbye!'));
           break;
       }

       const spinner = ora('Processing your request...').start();

       try {
           const { completion: reportAgentResponse } = await pipe.run({
               messages: [{ role: 'user', content: userMsg }],
           });

           spinner.stop();
           console.log(chalk.cyan('Agent:'));
           console.log(reportAgentResponse);
       } catch (error) {
           spinner.stop();
           console.error(chalk.red('Error processing your request:'), error);
       }
   }
}

main();

Step 8: Start BaseAI Server

npx baseai@latest dev

Step 9: Run the AI Agent Pipe

npx tsx index.ts

Usage

Run the application and interact with the AI agent by entering mathematical queries. The agent will use the integrated calculator tool to provide accurate results for complex calculations.

Conclusion

πŸŽ‰ This project demonstrates how to create an AI agent that enhances LLM capabilities for mathematical tasks using MathJS and BaseAI tool calls. By leveraging the strengths of both LLMs and specialized math tools, we've created a powerful calculator that can handle a wide range of mathematical operations accurately.

πŸ”’ Remember to keep your API keys secure and never share them publicly. Also, consider implementing additional error handling and input validation for a production-ready application.

About

πŸ› οΈ MathGenius: AI-Powered Calculator with LLM Integration

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published