{"_id":"@benschoolland/ai-tools","name":"@benschoolland/ai-tools","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@benschoolland/ai-tools","version":"0.1.0","description":"A collection of reusable AI utilities for quick project bootstrapping","type":"module","main":"./dist/cjs/index.cjs","module":"./dist/esm/index.js","exports":{".":{"import":"./dist/esm/index.js","require":"./dist/cjs/index.cjs"},"./core":{"import":"./dist/esm/core/index.js","require":"./dist/cjs/core/index.cjs"},"./utils":{"import":"./dist/esm/utils/index.js","require":"./dist/cjs/utils/index.cjs"}},"engines":{"node":">=14.0.0"},"scripts":{"test":"echo \"Error: no test specified\" && exit 1","build:esm":"esbuild src/index.js src/**/*.js --outdir=dist/esm --format=esm --platform=node","build:cjs":"esbuild src/index.js src/**/*.js --outdir=dist/cjs --format=cjs --platform=node --out-extension:.js=.cjs","fix:cjs":"node scripts/fix-cjs.js","build":"npm run build:esm && npm run build:cjs && npm run fix:cjs","prepare":"npm run build","prepublishOnly":"npm run build"},"keywords":["ai","openai","utilities","tools","ChatBot"],"author":{"name":"Benjamin Schoolland"},"license":"MIT","dependencies":{"@anthropic-ai/sdk":"^0.39.0","openai":"^4.24.1"},"peerDependencies":{"dotenv":"^16.3.1"},"repository":{"type":"git","url":"git+https://github.com/bschoolland/ai-tools.git"},"devDependencies":{"esbuild":"^0.20.2"},"_id":"@benschoolland/ai-tools@0.1.0","gitHead":"fdec58297e3e1d14027b4fa4f96539aa2e49a8fb","bugs":{"url":"https://github.com/bschoolland/ai-tools/issues"},"homepage":"https://github.com/bschoolland/ai-tools#readme","_nodeVersion":"18.20.3","_npmVersion":"10.7.0","dist":{"integrity":"sha512-oOKoMailMiVkuRbG+yfU0Rxig8J6yVo3yNhAxB5X7m2JxY6bEnu5Y/4ZNqsdPYMtBFfMfttO7YhVsEVvxwoU3A==","shasum":"0b4b2d70e747d618def1630fa9499cf3e6facd32","tarball":"https://registry.npmjs.org/@benschoolland/ai-tools/-/ai-tools-0.1.0.tgz","fileCount":30,"unpackedSize":107572,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIEpj8c1wwBkNK6fp7vqebgreoJSGQB3Ws4Ot8t7YV5kmAiAa1VcMAd/eYzSqGmnfwgSZZtfIOjuFa8Fi9J+upxUnOw=="}]},"_npmUser":{"name":"benschoolland","email":"bschoolland@gmail.com"},"directories":{},"maintainers":[{"name":"benschoolland","email":"bschoolland@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ai-tools_0.1.0_1742839172084_0.8846186733986867"},"_hasShrinkwrap":false}},"time":{"created":"2025-03-24T17:59:31.976Z","0.1.0":"2025-03-24T17:59:32.293Z","modified":"2025-03-24T17:59:32.523Z"},"maintainers":[{"name":"benschoolland","email":"bschoolland@gmail.com"}],"description":"A collection of reusable AI utilities for quick project bootstrapping","homepage":"https://github.com/bschoolland/ai-tools#readme","keywords":["ai","openai","utilities","tools","ChatBot"],"repository":{"type":"git","url":"git+https://github.com/bschoolland/ai-tools.git"},"author":{"name":"Benjamin Schoolland"},"bugs":{"url":"https://github.com/bschoolland/ai-tools/issues"},"license":"MIT","readme":"# @bschoolland/ai-tools\n\nA personal collection of reusable AI utilities for quick project bootstrapping.\n\n## Requirements\n\n- Node.js >= 14.0.0\n\n## Installation\n\n1. Add to your project's `package.json`:\n```json\n{\n  \"dependencies\": {\n    \"@bschoolland/ai-tools\": \"git+https://github.com/bschoolland/ai-tools.git\"\n  }\n}\n```\n\n2. Run:\n```bash\nnpm install\n```\n\n3. Create a `.env` file in your project root:\n```\nOPENAI_API_KEY=your_api_key_here\n```\nand/or\n```\nANTHROPIC_API_KEY=your_api_key_here\n```\nNote: you must have at least one API key set for the package to work, or you can pass the API key as an option to the constructor.\n\n## Available Exports\n\nThe package exports the following:\n\nFor ES Modules:\n```javascript\n// Main imports\nimport { ChatBot, Tools, History } from '@bschoolland/ai-tools';\n```\nor for CommonJS:\n```javascript\nconst { ChatBot, Tools, History } = require('@bschoolland/ai-tools');\n```\n\n## getLLMResponse\n\nA simple function to get a one-off response from a language model without maintaining conversation history or using tools. This is useful for quick queries that don't require context or special capabilities.\n\n```javascript\nconst response = await getLLMResponse({\n    message: \"Hello\",                    // The user's message\n    systemMessage: \"Be concise\",         // Optional system prompt\n    model: \"gpt-4o-mini\",               // The model to use\n    apiKey: process.env.OPENAI_API_KEY   // Optional API key\n});\n```\n\n## doAgentTask\n\nA more powerful function that allows the AI to use tools to complete tasks. This function maintains a conversation history and can make multiple tool calls to achieve the desired result. It's ideal for tasks that require external capabilities like getting the current time, performing calculations, or accessing data.\n\n```javascript\nconst response = await doAgentTask({\n    message: \"What time is it?\",         // The user's task/question\n    systemMessage: \"\",                   // Optional system prompt\n    tools: new Tools([/* your tools */]), // Tools the agent can use\n    model: \"gpt-4o-mini\",               // The model to use\n    apiKey: process.env.OPENAI_API_KEY,  // Optional API key\n    maxToolCalls: 25,                    // Max number of tool calls (default: 25)\n    maxHistory: 100                      // Max history messages to keep (default: 100)\n});\n```\n\n## Working with Tools\n\nThe Tools system allows you to give your AI assistant access to custom functions. There are two ways to create tools:\n\n### 1. Simple Tool Creation\nBest for simple functions with no parameters:\n\n```javascript\nimport { Tools, doAgentTask } from '@bschoolland/ai-tools';\n\nconst tools = new Tools();\n\n// function must have a name that describes what it does\nfunction getCurrentTime() {\n    return new Date().toISOString();\n}\n// Register a simple function\ntools.register(getCurrentTime);\n\nconsole.log(tools.toolsJson);\n\nconsole.log(await doAgentTask({\n    systemMessage: \"You are a helpful assistant.\",\n    tools: tools,\n    message: \"What time is it?\"\n}));\n```\n\n### 2. Detailed Tool Creation\nBetter for complex functions with parameters:\n\n```javascript\nimport { Tools } from '@bschoolland/ai-tools';\n\n// Create tools with detailed specifications\nconst tools = new Tools([\n    {\n        func: (x, y) => x + y,\n        name: 'add',  // Optional: defaults to function name\n        description: 'Add two numbers together',\n        parameters: {\n            x: {\n                type: 'number',\n                description: 'First number to add'\n            },\n            y: {\n                type: 'number',\n                description: 'Second number to add'\n            }\n        }\n    },\n    {\n        func: (text) => text.toUpperCase(),\n        description: 'Convert text to uppercase',\n        parameters: {\n            text: {\n                type: 'string',\n                description: 'Text to convert'\n            }\n        }\n    }\n]);\n\n// Add more tools later\ntools.register({\n    func: (date) => new Date(date).toLocaleDateString(),\n    description: 'Format a date string',\n    parameters: {\n        date: {\n            type: 'string',\n            description: 'Date string to format'\n        }\n    }\n});\n```\n\n### Using Tools with ChatBot\n\n```javascript\nconst tools = new Tools([/* your tools */]);\nconst chatbot = new ChatBot({\n    apiKey: process.env.OPENAI_API_KEY,\n    tools: tools,\n    systemMessage: 'You are a helpful assistant. Use the provided tools when appropriate.'\n});\n\n// The AI will automatically use tools when needed\nconst response = await chatbot.sendMessage('What time is it in UTC?');\n```\n\n### Tool Usage Example\n\nHere's a complete example showing tool usage:\n\n```javascript\nimport { ChatBot, Tools } from '@bschoolland/ai-tools';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\n// Create tools\nconst tools = new Tools([\n    {\n        func: (text) => text.length,\n        description: 'Count characters in text',\n        parameters: {\n            text: {\n                type: 'string',\n                description: 'Text to count'\n            }\n        }\n    },\n    {\n        func: () => new Date().toISOString(),\n        description: 'Get current time in ISO format',\n        parameters: {}\n    }\n]);\n\n// Create ChatBot with tools\nconst chatbot = new ChatBot({\n    apiKey: process.env.OPENAI_API_KEY,\n    tools: tools,\n    systemMessage: 'You are a helpful assistant that can work with text and time.'\n});\n\n// Example usage\nasync function main() {\n    try {\n        const response = await chatbot.sendMessage(\n            'How many characters are in \"Hello, World!\" and what time is it?'\n        );\n        console.log('Response:', response);\n    } catch (error) {\n        console.error('Error:', error);\n    }\n}\n\nmain();\n```\n\n## Working with History\n\nThe History class manages conversation history for AI interactions. While it's used internally by ChatBot and doAgentTask, you can also use it directly for advanced use cases like:\n- Manually managing conversation context\n- Editing conversation history\n- Persisting conversations between sessions\n\n### Basic Usage\n\n```javascript\nimport { History } from '@bschoolland/ai-tools';\n\n// Create a new history\nconst history = new History(\n    [\n        {role: \"system\", content: \"You are a helpful assistant.\"},\n        {role: \"user\", content: \"Hello!\"},\n        {role: \"assistant\", content: \"Hello, how can I assist you today?\"}\n    ]\n);\n\n// Add or change the system message\nhistory.setSystemMessage(\"You are a very helpful assistant.\");\n\n// manually append messages\nhistory.addMessage({ role: \"user\", content: \"Hello!\" });\nhistory.addMessage({ role: \"assistant\", content: \"Hi there!\" });\n\n// Get the full history to use elsewhere in your application\nconst allMessages = history.getHistory();\n\n// Get limited history (useful for context windows)\nconst lastFewMessages = history.getHistory(5); // Get last 5 messages (preserves system message)\n```\n\n### Using with ChatBot\n\n```javascript\nimport { ChatBot, History } from '@bschoolland/ai-tools';\n\n// Create a history with existing messages (for example, from a previous conversation or database)\nconst history = new History([\n    {role: \"system\", content: \"You are a helpful assistant.\"},\n    {role: \"user\", content: \"Hello!\"},\n    {role: \"assistant\", content: \"Hello, how can I assist you today?\"}\n]);\n\n// Create a ChatBot with existing history\nconst chatbot = new ChatBot({\n    apiKey: process.env.OPENAI_API_KEY,\n    history: history\n});\n\n// Get the history at any time\nconst currentHistory = chatbot.getHistory();\n\n// Replace the history\nchatbot.setHistory(new History([/* your messages */]));\n// Note that the above will use the existing system message from the ChatBot if you don't provide one in the History constructor\n```\n\n### History Message Format\n\nMessages in the history should follow this format:\n```javascript\n{\n    role: string,      // \"system\", \"user\", \"assistant\", or \"tool\"\n    content: string,   // The message content\n    tool_call_id?: string,  // Optional: ID for tool calls\n    name?: string      // Optional: Name of the tool used\n}\n```\n\nThe History class automatically handles system messages (ensuring they stay at the start of the conversation) and provides methods to manage the conversation flow.\n\n## Complete Example\n\nHere's a working example showing how to set up and use the package:\n\n```javascript\n// example.js\nimport dotenv from 'dotenv';\nimport { ChatBot, Tools } from '@bschoolland/ai-tools';\n\n// Load environment variables\ndotenv.config();\n\nfunction getCurrentTime() {\n    return new Date().toISOString();\n}\n\n// Create a tool\nconst tools = new Tools([\n    {\n        func: getCurrentTime,\n        description: 'Get the current time',\n        parameters: {}\n    }\n]);\n\n// Initialize ChatBot\nconst chatbot = new ChatBot({\n    apiKey: process.env.OPENAI_API_KEY,\n    model: 'gpt-4o-mini',\n    tools: tools,\n    systemMessage: 'You are a helpful assistant that can tell the time.'\n});\n\n// Example conversation\nasync function main() {\n    try {\n        const response = await chatbot.sendMessage('What time is it?');\n        console.log('Bot:', response);\n        \n        // Access conversation history\n        console.log('Full conversation:', chatbot.getHistory().getHistory());\n    } catch (error) {\n        console.error('Error:', error);\n    }\n}\n\nmain();\n```\n\n## Experimental: ChatBotManager\n\nThe chatbot manager is a class that manages multiple conversations, identified by a conversationID. While still a work in progress, it is useful for multi user applications where each user needs to talk to their own instance of the AI.  \n\n### Usage\n\n```javascript\nimport { ChatBotManager } from '@bschoolland/ai-tools';\n\n// define the manager along with some defaults to use whenever creating a new conversation\nconst manager = new ChatBotManager(\n    {\n        model: \"gpt-4o-mini\",\n        tools: new Tools([/* your tools */]),\n        systemMessage: \"You are a helpful assistant.\",\n        saveCallback: async (conversationID, history) => { // conversationID is the unique identifier for the user, and history is the conversation history as an array of messages\n            // your code here to save the history to a database or other persistent storage\n        },\n        loadCallback: async (conversationID) => { // conversationID is the unique identifier for the user, and the callback should return the conversation history as an array of messages\n            // your code here to load the history from a database or other persistent storage\n            return [];\n        },\n        conversationTTL: 1000 * 60 * 60 * 24 * 30, // 30 days\n        checkInterval: 1000 * 60 * 60 * 24 // 1 day\n    }\n);\n\n// from here, you can create or access a conversation for a specific user\nconst conversation = await manager.getConversation({ conversationID: \"123\" });\n\n// send a message from the user and receive a response, just like with the ChatBot class\nconst response = await conversation.sendMessage(\"Hello, how are you?\");\n\n// each conversation may optionally be initialized with a custom model, tools object, and system message, which it will use instead of the manager's defaults\nconst conversation2 = await manager.getConversation({ conversationID: \"345\", model: \"gpt-4o\", tools: new Tools([/* your tools */]), systemMessage: \"You are a helpful assistant.\" });\n```\nIf the conversationID already exists, the conversation will be retrieved instead of creating a new one, and the manager keeps track of History for each conversation in memory for it's TTL\n\nThe saveCallback is called whenever a message is sent, and the loadCallback is called whenever a conversation is initialized.\n\nNote that passing custom model, systemMessage, or tools as options to getConversation will not work for existing conversations, they will only be used if the conversation does not already exist.\n\nAgain, this feature is still a work in progress and may need to be expanded or modified in the future.\n\n## Custom Identifier for User-Specific Context\n\nBroilerplateAI supports passing user-specific context to tools through the `customIdentifier` feature. This allows you to:\n\n1. Pass user permissions and preferences to tools\n2. Provide user-specific data like timezones, locale settings, or organization information\n3. Apply authentication context without modifying tool signatures\n\n### Using customIdentifier\n\n#### At Chatbot Creation\n\n```javascript\n// Create a manager with a default customIdentifier\nconst manager = new ChatbotManager({\n  model: \"gpt-4o\",\n  tools: myTools,\n  systemMessage: \"You are a helpful assistant\",\n  customIdentifier: {\n    defaultPermission: \"user\"  // Applied to all conversations by default\n  }\n});\n\n// Create a conversation with a specific customIdentifier\nconst userConversation = await manager.getConversation({\n  conversationID: \"user_123\",\n  customIdentifier: {\n    timezone: \"America/New_York\",\n    permissions: [\"read\", \"write\"],\n    userId: \"user_123\"\n  }\n});\n```\n\n#### During a Conversation\n\nYou can update the customIdentifier at any time:\n\n```javascript\n// Update a user's customIdentifier\nmanager.setCustomIdentifier(\"user_123\", {\n  timezone: \"Europe/London\",\n  permissions: [\"read\", \"write\", \"admin\"],\n  userId: \"user_123\"\n});\n```\n\n#### Tools that Use customIdentifier\n\nRegister tools that need the customIdentifier:\n\n```javascript\n// Define a tool that uses customIdentifier\nfunction getUserTimeZone(customIdentifier = null) {\n  if (!customIdentifier || !customIdentifier.timezone) {\n    return \"No timezone configured\";\n  }\n  return `User timezone: ${customIdentifier.timezone}`;\n}\n\n// Register the tool with acceptsCustomIdentifier flag\ntools.register({\n  func: getUserTimeZone,\n  acceptsCustomIdentifier: true,  // Mark this tool as needing customIdentifier\n  description: \"Get the user's timezone\",\n  parameters: {}  // No user-provided parameters needed\n});\n```\n\n### Benefits\n\n- **Permissions Control**: Gate access to sensitive information based on user roles\n- **Personalization**: Provide user-specific responses without complex parameter passing\n- **Stateful Context**: Pass session information that persists across multiple tool calls\n- **Clean API Design**: Tools can accept user context without cluttering their interfaces\n\nThe `customIdentifier` is transparently handled by the chatbot system and automatically passed to tools that need it, regardless of which AI model provider you're using.\n\n## General Troubleshooting\n\nCommon issues and solutions:\n\n\n1. **\"ERR_PACKAGE_PATH_NOT_EXPORTED\"**\n   - Check your import path matches the exports in package.json\n   - Use the exact paths shown in \"Available Exports\" section\n\n2. **OpenAI, Anthropic, or other API errors**\n   - Ensure OPENAI_API_KEY, ANTHROPIC_API_KEY, or other API keys are set in your .env file are being passed as an option to the constructor\n\n## Directory Structure\n\n```\nsrc/\n├── core/           # Core AI functionality\n│   ├── ChatBot.js  # Main ChatBot implementation\n│   └── tools.js    # Tool system for extending AI capabilities\n├── utils/          # Utility functions\n│   └── history.js  # Chat history management\n└── index.js        # Main entry point\n```\n\n## Features\n\n- 🤖 Easy-to-use ChatBot integration\n- 🛠️ Extensible tools system\n- 📝 Chat history management\n- 📦 Modular and reusable\n- 🔌 Simple integration\n\n## License\n\nMIT","readmeFilename":"README.md","_rev":"1-a98c435ecf670ff55a2fb14afa284ee6"}