Skip to content

Repository files navigation

HelpingAI JavaScript SDK

npm versionTypeScriptLicense: MIT

The official JavaScript/TypeScript SDK for HelpingAI - an advanced emotional AI platform that provides empathetic and contextually aware responses.

🚀 Quick Start

Installation

npm install helpingai
# or
yarn add helpingai
# or
pnpm add helpingai

Basic Usage

import{HelpingAI}from'helpingai';constclient=newHelpingAI({apiKey: 'your-api-key-here',});asyncfunctionmain(){constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello! How are you today?'}],});console.log(response.choices[0].message.content);}main().catch(console.error);

📋 Table of Contents

✨ Features

  • 🤖 Advanced AI Models: Access to HelpingAI's emotional AI models including Dhanishtha-2.0
  • 🛠️ Tool Calling: Built-in and custom tool support with type safety
  • 🔄 Streaming: Real-time response streaming for better user experience
  • 🔌 MCP Integration: Model Context Protocol support for external integrations
  • 📝 TypeScript First: Full TypeScript support with comprehensive type definitions
  • 🌐 Cross-Platform: Works in Node.js, browsers, and edge environments
  • ⚡ Performance: Optimized for speed with connection pooling and caching
  • 🛡️ Error Handling: Comprehensive error handling with retry mechanisms
  • 📚 Rich Examples: Extensive examples and documentation

🔧 Installation

Prerequisites

  • Node.js 16+ or modern browser environment
  • TypeScript 4.5+ (for TypeScript projects)

Package Manager Installation

# npm
npm install helpingai
# yarn
yarn add helpingai
# pnpm
pnpm add helpingai
# bun
bun add helpingai

CDN Usage (Browser)

<!-- ES Modules --><scripttype="module">import{HelpingAI}from'https://cdn.skypack.dev/helpingai';</script><!-- UMD --><scriptsrc="https://unpkg.com/helpingai/dist/helpingai.umd.js"></script>

🔐 Authentication

API Key Setup

Get your API key from the HelpingAI Dashboard and set it up:

// Method 1: Direct initializationconstclient=newHelpingAI({apiKey: 'your-api-key-here',});// Method 2: Environment variable (Node.js)// Set HELPINGAI_API_KEY in your environmentconstclient=newHelpingAI();// Automatically reads from env// Method 3: Configuration objectconstclient=newHelpingAI({apiKey: process.env.HELPINGAI_API_KEY,baseURL: 'https://api.helpingai.com/v1',// Optional custom endpointtimeout: 30000,// Optional timeout in millisecondsmaxRetries: 3,// Optional retry configuration});

Environment Variables

Create a .env file in your project root:

HELPINGAI_API_KEY=your-api-key-hereHELPINGAI_BASE_URL=https://api.helpingai.com/v1# Optional

🧠 Core Concepts

Client Initialization

import{HelpingAI}from'helpingai';constclient=newHelpingAI({apiKey: 'your-api-key',baseURL: 'https://api.helpingai.com/v1',// Optionaltimeout: 30000,// 30 secondsmaxRetries: 3,defaultHeaders: {'User-Agent': 'MyApp/1.0',},});

Chat Completions

constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'system',content: 'You are a helpful assistant.'},{role: 'user',content: 'Explain quantum computing'},],max_tokens: 1000,temperature: 0.7,});

Streaming Responses

conststream=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Tell me a story'}],stream: true,});forawait(constchunkofstream){if(chunk.choices[0].delta.content){process.stdout.write(chunk.choices[0].delta.content);}}

📚 Examples

Basic Chat

import{HelpingAI}from'helpingai';asyncfunctionbasicChat(){constclient=newHelpingAI({apiKey: 'your-api-key'});constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'What is emotional intelligence?'}],});console.log(response.choices[0].message.content);}

Tool Calling

import{HelpingAI,tools}from'helpingai';// Define a custom toolconstweatherTool=tools(functiongetWeather(city: string): string{/** * Get weather information for a city * @param city - The city name */return`Weather in ${city}: 22°C, sunny`;});asyncfunctiontoolExample(){constclient=newHelpingAI({apiKey: 'your-api-key'});constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: "What's the weather in Paris?"}],tools: [weatherTool],});console.log(response.choices[0].message.content);}

Streaming with Progress

asyncfunctionstreamingExample(){constclient=newHelpingAI({apiKey: 'your-api-key'});conststream=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Write a poem about AI'}],stream: true,});letcontent='';forawait(constchunkofstream){if(chunk.choices[0].delta.content){content+=chunk.choices[0].delta.content;process.stdout.write(chunk.choices[0].delta.content);}if(chunk.choices[0].finish_reason){console.log('\n\nStream completed!');break;}}}

🔧 API Reference

HelpingAI Client

Constructor Options

interfaceHelpingAIOptions{apiKey?: string;// API key (required)baseURL?: string;// Base API URLtimeout?: number;// Request timeout in msmaxRetries?: number;// Max retry attemptsdefaultHeaders?: Record<string,string>;// Default headers}

Methods

  • chat.completions.create(options) - Create chat completion
  • call(toolName, parameters) - Execute tool directly
  • cleanup() - Clean up resources

Chat Completion Options

interfaceChatCompletionRequest{model: string;// Model namemessages: ChatMessage[];// Conversation messagesmax_tokens?: number;// Maximum tokens to generatetemperature?: number;// Randomness (0-2)top_p?: number;// Nucleus samplingstream?: boolean;// Enable streamingtools?: Tool[];// Available toolstool_choice?: 'auto'|'none'|string;// Tool selectionstop?: string|string[];// Stop sequences}

Message Types

interfaceChatMessage{role: 'system'|'user'|'assistant'|'tool';content: string;name?: string;// For tool messagestool_calls?: ToolCall[];// For assistant messages with tools}

🛠️ Tools System

Creating Custom Tools

import{tools}from'helpingai';// Simple toolconstcalculator=tools(functionadd(a: number,b: number): number{/** * Add two numbers together * @param a - First number * @param b - Second number */returna+b;});// Complex tool with validationconstuserManager=tools(functioncreateUser(name: string,email: string,age?: number): {id: string;name: string;email: string;age?: number}{/** * Create a new user account * @param name - User's full name * @param email - User's email address * @param age - User's age (optional) */if(!name||!email){thrownewError('Name and email are required');}return{id: Math.random().toString(36).substr(2,9),
name,
email,
age,};});

Tool Registry Management

import{getRegistry,getTools,clearRegistry}from'helpingai';// Get the tool registryconstregistry=getRegistry();// List all registered toolsconsole.log('Registered tools:',registry.listToolNames());// Get specific toolsconstmyTools=getTools(['add','createUser']);// Clear all tools (useful for testing)clearRegistry();

Built-in Tools

HelpingAI provides powerful built-in tools inspired by Qwen-Agent:

code_interpreter - Python Code Execution

Execute Python code in a secure sandboxed environment with data science capabilities:

import{HelpingAI}from'helpingai';constclient=newHelpingAI({apiKey: 'your-api-key'});// Direct tool callconstresult=awaitclient.call('code_interpreter',{code: `import matplotlib.pyplot as pltimport numpy as np# Generate sample datax = np.linspace(0, 10, 100)y = np.sin(x)# Create plotplt.figure(figsize=(10, 6))plt.plot(x, y, 'b-', linewidth=2)plt.title('Sine Wave')plt.xlabel('X values')plt.ylabel('Y values')plt.grid(True)plt.show()print("Plot generated successfully!")`,});console.log(result);

Features:

  • Automatic imports: numpy, pandas, matplotlib, seaborn
  • Plot auto-saving: Automatically saves matplotlib plots
  • Timeout protection: 30-second execution limit
  • Working directory: Isolated temporary workspace
  • Error handling: Comprehensive error reporting

web_search - Real-time Web Search

Search the web for current information using the Snapzion Search API:

// Direct tool callconstsearchResult=awaitclient.call('web_search',{query: 'latest AI developments 2024',max_results: 5,});console.log(searchResult);

Features:

  • Real-time results: Current web information
  • Rich metadata: Titles, snippets, URLs, sources
  • Configurable limits: 1-10 results per search
  • Structured output: Well-formatted results
  • Error resilience: Graceful fallback handling

Using Built-in Tools

import{executeBuiltinTool,isBuiltinTool,getAvailableBuiltinTools}from'helpingai';// Check available toolsconsole.log('Available tools:',getAvailableBuiltinTools());// Check if a tool existsif(isBuiltinTool('web_search')){constresult=awaitexecuteBuiltinTool('web_search',{query: 'TypeScript tutorials',});}// Direct executionconstcodeResult=awaitexecuteBuiltinTool('code_interpreter',{code: 'print("Hello from Python!")',});
// Using built-in toolsconstresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Search for recent AI developments'}],tools: ['web_search'],});

🔌 MCP Integration

Model Context Protocol (MCP) allows integration with external services:

import{HelpingAI,MCPClient}from'helpingai';asyncfunctionmcpExample(){constclient=newHelpingAI({apiKey: 'your-api-key'});// Connect to MCP serverconstmcpClient=newMCPClient({transport: {type: 'stdio',command: 'node',args: ['path/to/mcp-server.js'],},});awaitmcpClient.connect();// Use MCP tools in chatconstresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Get my calendar events for today'}],mcp: mcpClient,});awaitmcpClient.disconnect();}

📡 Streaming

Basic Streaming

conststream=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Tell me about space'}],stream: true,});forawait(constchunkofstream){if(chunk.choices[0].delta.content){console.log(chunk.choices[0].delta.content);}}

Advanced Streaming with Event Handling

asyncfunctionadvancedStreaming(){conststream=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Explain machine learning'}],stream: true,});letfullContent='';lettokenCount=0;conststartTime=Date.now();try{forawait(constchunkofstream){if(chunk.choices[0].delta.content){constcontent=chunk.choices[0].delta.content;fullContent+=content;tokenCount++;// Real-time processingprocess.stdout.write(content);}if(chunk.choices[0].finish_reason){constduration=Date.now()-startTime;console.log(`\n\nCompleted in ${duration}ms`);console.log(`Tokens: ${tokenCount}`);break;}}}catch(error){console.error('Streaming error:',error);}}

⚠️ Error Handling

Error Types

import{HelpingAIError,APIError,AuthenticationError,RateLimitError,TimeoutError,}from'helpingai';try{constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello'}],});}catch(error){if(errorinstanceofAuthenticationError){console.error('Invalid API key');}elseif(errorinstanceofRateLimitError){console.error('Rate limit exceeded');}elseif(errorinstanceofTimeoutError){console.error('Request timed out');}elseif(errorinstanceofAPIError){console.error('API error:',error.message);}else{console.error('Unexpected error:',error);}}

Retry Configuration

constclient=newHelpingAI({apiKey: 'your-api-key',maxRetries: 3,timeout: 30000,});// Custom retry logicasyncfunctionwithRetry<T>(fn: ()=>Promise<T>,maxRetries=3): Promise<T>{for(leti=0;i<maxRetries;i++){try{returnawaitfn();}catch(error){if(i===maxRetries-1)throwerror;// Exponential backoffconstdelay=Math.pow(2,i)*1000;awaitnewPromise(resolve=>setTimeout(resolve,delay));}}thrownewError('Max retries exceeded');}

Graceful Error Handling

asyncfunctionrobustChat(message: string){constclient=newHelpingAI({apiKey: 'your-api-key'});try{constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: message}],});returnresponse.choices[0].message.content;}catch(error){if(errorinstanceofRateLimitError){// Wait and retryawaitnewPromise(resolve=>setTimeout(resolve,60000));returnrobustChat(message);}elseif(errorinstanceofAuthenticationError){thrownewError('Please check your API key');}else{// Fallback responsereturn'I apologize, but I encountered an error. Please try again.';}}}

📘 TypeScript Support

Full Type Safety

import{HelpingAI,ChatCompletionResponse,Tool}from'helpingai';// Strongly typed clientconstclient: HelpingAI=newHelpingAI({apiKey: 'your-api-key'});// Typed responsesconstresponse: ChatCompletionResponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello'}],});// Type-safe tool definitionsconsttypedTool: Tool=tools(functionprocessData(data: {id: number;name: string}[]): {processed: number;items: string[];}{return{processed: data.length,items: data.map(item=>item.name),};});

Custom Type Extensions

// Extend the SDK types for your use caseinterfaceCustomChatMessageextendsChatMessage{timestamp?: Date;userId?: string;}interfaceCustomCompletionRequestextendsChatCompletionRequest{customMetadata?: Record<string,any>;}

🔄 Migration from Python

Key Differences

PythonJavaScript/TypeScript
from helpingai import HelpingAIimport { HelpingAI } from 'helpingai'
@tools decoratortools() function wrapper
client.chat.completions.create()Same API
Snake case (max_tokens)Same (maintains API compatibility)
async for chunk in stream:for await (const chunk of stream)

Python to JavaScript Examples

Python:

fromhelpingaiimportHelpingAI, tools@toolsdefget_weather(city: str) ->str:
"""Get weather for a city"""returnf"Weather in {city}: sunny"client=HelpingAI(api_key="your-key")
response=client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=[{"role": "user", "content": "Weather in Paris?"}],
tools=[get_weather]
)

JavaScript:

import{HelpingAI,tools}from'helpingai';constgetWeather=tools(functiongetWeather(city: string): string{/** * Get weather for a city */return`Weather in ${city}: sunny`;});constclient=newHelpingAI({apiKey: 'your-key'});constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Weather in Paris?'}],tools: [getWeather],});

🏗️ Development

Building from Source

# Clone the repository
git clone https://github.com/helpingai/helpingai.git
cd helpingai
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test# Run examples
npm run example:basic
npm run example:streaming
npm run example:tools

Project Structure

HelpingAI-js/
├── src/
│ ├── index.ts # Main exports
│ ├── client.ts # HelpingAI client
│ ├── types.ts # Type definitions
│ ├── errors.ts # Error classes
│ ├── tools/ # Tools system
│ └── mcp/ # MCP integration
├── examples/ # Usage examples
├── docs/ # Documentation
├── tests/ # Test files
└── dist/ # Built files

Available Scripts

{
"scripts": {
"build": "npm run build:cjs && npm run build:esm && npm run build:types",
"build:cjs": "tsc -p tsconfig.cjs.json",
"build:esm": "tsc -p tsconfig.esm.json",
"build:types": "tsc -p tsconfig.types.json",
"dev": "tsc --watch",
"test": "jest",
"lint": "eslint src/**/*.ts",
"example:basic": "tsx examples/basic-usage.ts",
"example:streaming": "tsx examples/streaming.ts",
"example:tools": "tsx examples/tool-calling.ts",
"example:mcp": "tsx examples/mcp-integration.ts",
"example:advanced": "tsx examples/advanced-features.ts"
}
}

🧪 Testing

Running Tests

# Run all tests
npm test# Run with coverage
npm run test:coverage
# Run specific test file
npm test -- client.test.ts
# Watch mode
npm run test:watch

Example Test

import{HelpingAI,tools}from'../src';describe('HelpingAI Client',()=>{letclient: HelpingAI;beforeEach(()=>{client=newHelpingAI({apiKey: 'test-key'});});afterEach(async()=>{awaitclient.cleanup();});test('should create chat completion',async()=>{constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello'}],});expect(response.choices).toHaveLength(1);expect(response.choices[0].message.content).toBeDefined();});test('should handle tool calling',async()=>{consttestTool=tools(functiontestFunction(input: string): string{return`Processed: ${input}`;});constresult=awaitclient.call('testFunction',{input: 'test'});expect(result).toBe('Processed: test');});});

🌐 Browser Support

Modern Browsers

The SDK works in all modern browsers with ES2018+ support:

  • Chrome 63+
  • Firefox 58+
  • Safari 12+
  • Edge 79+

Browser Usage

<!DOCTYPE html><html><head><title>HelpingAI Browser Example</title></head><body><scripttype="module">import{HelpingAI}from'https://cdn.skypack.dev/helpingai';constclient=newHelpingAI({apiKey: 'your-api-key-here',});asyncfunctionchat(){constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello from the browser!'}],});document.body.innerHTML=response.choices[0].message.content;}chat().catch(console.error);</script></body></html>

🔒 Security

API Key Security

  • Never expose API keys in client-side code
  • Use environment variables in server environments
  • Implement proper key rotation policies
  • Monitor API usage for anomalies

Best Practices

// ✅ Good - Server-side usageconstclient=newHelpingAI({apiKey: process.env.HELPINGAI_API_KEY,});// ❌ Bad - Client-side exposureconstclient=newHelpingAI({apiKey: 'sk-...',// Never hardcode keys});// ✅ Good - Proxy pattern for browsers// Create a server endpoint that proxies requestsfetch('/api/chat',{method: 'POST',body: JSON.stringify({message: 'Hello'}),});

📊 Performance

Optimization Tips

  1. Connection Reuse: Keep client instances alive
  2. Streaming: Use streaming for long responses
  3. Caching: Cache tool results when appropriate
  4. Batching: Combine multiple operations
  5. Timeouts: Set appropriate timeout values

Performance Monitoring

constclient=newHelpingAI({apiKey: 'your-api-key',timeout: 30000,maxRetries: 3,});// Monitor response timesconststartTime=Date.now();constresponse=awaitclient.chat.completions.create({model: 'Dhanishtha-2.0-preview',messages: [{role: 'user',content: 'Hello'}],});constduration=Date.now()-startTime;console.log(`Response time: ${duration}ms`);

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Fork and clone the repository
git clone https://github.com/your-username/helpingai.git
cd helpingai
# Install dependencies
npm install
# Create a feature branch
git checkout -b feature/your-feature-name
# Make your changes and test
npm test
npm run lint
# Commit and push
git commit -m "Add your feature"
git push origin feature/your-feature-name

Code Style

  • Use TypeScript for all new code
  • Follow existing code style and conventions
  • Add tests for new features
  • Update documentation as needed

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🚀 What's Next?


Made with ❤️ by the HelpingAI team

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages