π§ π‘ 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.
π§π»
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) π
mkdir my-math-agent
cd my-math-agent
npm init -y
npm install dotenv mathjs
npx baseai@latest pipe
Follow the prompts to create a new pipe named "pipe-with-tool".
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
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;
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;
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;
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();
npx baseai@latest dev
npx tsx index.ts
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.
π 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.