# AIO-AI - Multiple AI Services Orchestrator

A TypeScript package for integrating multiple AI services (AWS Bedrock, OpenAI, Google AI, etc.) into your applications.

[![npm version](https://img.shields.io/npm/v/aio-ai.svg)](https://www.npmjs.com/package/aio-ai)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

✅ **AWS Bedrock Integration** - Support for Anthropic Claude models via AWS Bedrock  
✅ **TypeScript Support** - Full type definitions included  
✅ **Flexible Configuration** - Constructor-based configuration for easy setup  
✅ **Error Handling** - Custom error classes with proper HTTP status codes  
✅ **Translation Service** - Built-in translation capabilities  
✅ **Custom Prompts** - Process text with custom system and user prompts  
🔜 **OpenAI Integration** - Coming soon  
🔜 **Google AI Integration** - Coming soon  

## Installation

### Basic Installation

```bash
npm install aio-ai
```

### With AWS Bedrock Support

```bash
npm install aio-ai @aws-sdk/client-bedrock-runtime
```

## Usage

### AWS Bedrock Service

#### Basic Setup (JavaScript)

```javascript
const { BedrockService } = require('aio-ai');

// Initialize service with credentials
const bedrock = new BedrockService({
  region: 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
  }
});

// Translate text
async function translateExample() {
  const translation = await bedrock.translateText(
    'Hello world',
    'English',
    'Indonesian'
  );
  console.log(translation); // "Halo dunia"
}

translateExample();
```

#### TypeScript Setup

```typescript
import { BedrockService, BedrockConfig } from 'aio-ai';

// Configure with type safety
const config: BedrockConfig = {
  region: 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!
  },
  modelId: 'anthropic.claude-3-5-sonnet-20240620-v1:0', // optional
  maxTokens: 4000, // optional
  temperature: 0.1 // optional
};

const bedrock = new BedrockService(config);

// Translate with full type support
const translation = await bedrock.translateText(
  'Hello world',
  'English',
  'Indonesian'
);
```

#### Custom Prompts

```javascript
const bedrock = new BedrockService(config);

// Use custom prompts for specific tasks
const result = await bedrock.translateWithCustomPrompt(
  'Explain quantum computing',
  'You are a physics professor explaining concepts to high school students',
  'Explain quantum computing in simple terms with examples'
);

console.log(result);
```

#### Translation with Custom Prompts

```javascript
// Override default translation prompts
const translation = await bedrock.translateText(
  'Technical documentation text',
  'English',
  'Indonesian',
  'You are a technical translator specializing in software documentation',
  'Translate this keeping technical terms in English: Technical documentation text'
);
```

### Utility Functions

```javascript
const { sayHello, greet, welcomeMessage } = require('aio-ai');

console.log(sayHello()); // "Hello, World!"
console.log(sayHello('Ian')); // "Hello, Ian!"
console.log(greet('Ian', 'Hi')); // "Hi, Ian!"
console.log(welcomeMessage()); // "Welcome to AIO-AI - Multiple AI Services Orchestrator!"
```

### Express.js Integration

#### Complete Express.js Example with AWS Bedrock

```javascript
const express = require('express');
const { BedrockService, ResponseError } = require('aio-ai');
require('dotenv').config();

const app = express();
app.use(express.json());

// Initialize Bedrock service
const bedrock = new BedrockService({
  region: process.env.AWS_BEDROCK_REGION,
  credentials: {
    accessKeyId: process.env.AWS_BEDROCK_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_BEDROCK_SECRET_ACCESS_KEY
  }
});

// Translation endpoint
app.post('/api/translate', async (req, res) => {
  try {
    const { text, sourceLanguage, targetLanguage } = req.body;
    
    const translation = await bedrock.translateText(
      text,
      sourceLanguage,
      targetLanguage
    );
    
    res.json({ 
      success: true, 
      translation 
    });
  } catch (error) {
    if (error instanceof ResponseError) {
      res.status(error.statusCode).json({ 
        success: false, 
        error: error.message 
      });
    } else {
      res.status(500).json({ 
        success: false, 
        error: 'Internal server error' 
      });
    }
  }
});

// Custom prompt endpoint
app.post('/api/process', async (req, res) => {
  try {
    const { text, systemPrompt, userPrompt } = req.body;
    
    const result = await bedrock.translateWithCustomPrompt(
      text,
      systemPrompt,
      userPrompt
    );
    
    res.json({ 
      success: true, 
      result 
    });
  } catch (error) {
    if (error instanceof ResponseError) {
      res.status(error.statusCode).json({ 
        success: false, 
        error: error.message 
      });
    } else {
      res.status(500).json({ 
        success: false, 
        error: 'Internal server error' 
      });
    }
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

#### TypeScript Express Example

```typescript
import express, { Request, Response } from 'express';
import { BedrockService, ResponseError, BedrockConfig } from 'aio-ai';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
app.use(express.json());

// Initialize with type safety
const config: BedrockConfig = {
  region: process.env.AWS_BEDROCK_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_BEDROCK_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_BEDROCK_SECRET_ACCESS_KEY!
  }
};

const bedrock = new BedrockService(config);

interface TranslateRequest {
  text: string;
  sourceLanguage: string;
  targetLanguage: string;
}

app.post('/api/translate', async (req: Request<{}, {}, TranslateRequest>, res: Response) => {
  try {
    const { text, sourceLanguage, targetLanguage } = req.body;
    
    const translation = await bedrock.translateText(
      text,
      sourceLanguage,
      targetLanguage
    );
    
    res.json({ success: true, translation });
  } catch (error) {
    if (error instanceof ResponseError) {
      res.status(error.statusCode).json({ 
        success: false, 
        error: error.message 
      });
    } else {
      res.status(500).json({ 
        success: false, 
        error: 'Internal server error' 
      });
    }
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

## API Reference

### BedrockService

#### Constructor

```typescript
new BedrockService(config: BedrockConfig)
```

Creates a new BedrockService instance.

**Parameters:**
- `config.region` (string, required): AWS region (e.g., 'us-east-1')
- `config.credentials.accessKeyId` (string, required): AWS Access Key ID
- `config.credentials.secretAccessKey` (string, required): AWS Secret Access Key
- `config.modelId` (string, optional): Model ID to use. Default: `'anthropic.claude-3-5-sonnet-20240620-v1:0'`
- `config.maxTokens` (number, optional): Maximum tokens for response. Default: `4000`
- `config.temperature` (number, optional): Temperature for randomness. Default: `0.1`

**Throws:**
- `ResponseError` - If required configuration is missing

#### Methods

##### `translateText(text, sourceLanguage, targetLanguage, systemPrompt?, userPrompt?)`

Translates text from source language to target language.

**Parameters:**
- `text` (string, required): Text to translate
- `sourceLanguage` (string, required): Source language (e.g., 'English')
- `targetLanguage` (string, required): Target language (e.g., 'Indonesian')
- `systemPrompt` (string, optional): Custom system prompt
- `userPrompt` (string, optional): Custom user prompt

**Returns:** `Promise<string>` - Translated text

**Throws:**
- `ResponseError` - If translation fails or parameters are invalid

**Example:**
```typescript
const translation = await bedrock.translateText(
  'Hello world',
  'English',
  'Indonesian'
);
```

##### `translateWithCustomPrompt(text, customSystemPrompt?, customUserPrompt?)`

Processes text with custom system and user prompts.

**Parameters:**
- `text` (string, required): Text to process
- `customSystemPrompt` (string, optional): Custom system prompt
- `customUserPrompt` (string, optional): Custom user prompt

**Returns:** `Promise<string>` - Processed text response

**Throws:**
- `ResponseError` - If processing fails or text is missing

**Example:**
```typescript
const result = await bedrock.translateWithCustomPrompt(
  'Explain AI',
  'You are a teacher',
  'Explain this simply'
);
```

##### `getModelId()`

Gets the current model ID being used.

**Returns:** `string` - Current model ID

##### `getConfig()`

Gets the current service configuration.

**Returns:** `{ modelId: string; maxTokens: number; temperature: number }`

### ResponseError

Custom error class for handling API and service errors.

#### Constructor

```typescript
new ResponseError(statusCode: number, message: string, isOperational?: boolean)
```

**Parameters:**
- `statusCode` (number): HTTP status code
- `message` (string): Error message
- `isOperational` (boolean, optional): Whether error is operational. Default: `true`

#### Properties

- `statusCode` (number): HTTP status code
- `message` (string): Error message
- `isOperational` (boolean): Whether error is operational

#### Methods

##### `toJSON()`

Converts error to JSON format.

**Returns:** `{ statusCode: number; message: string; name: string }`

### Utility Functions

#### `sayHello(name?: string): string`

Returns a simple greeting message.

**Parameters:**
- `name` (optional): Name to greet. Default: `'World'`

**Returns:** Greeting string

#### `greet(name: string, prefix?: string): string`

Returns a custom greeting message with custom prefix.

**Parameters:**
- `name`: Name to greet
- `prefix` (optional): Custom greeting prefix. Default: `'Hello'`

**Returns:** Custom greeting string

#### `welcomeMessage(): string`

Returns a welcome message for AIO-AI.

**Returns:** Welcome message string

## Development

### Build the Package

```bash
npm install
npm run build
```

### Development Mode (Watch)

```bash
npm run dev
```

### Clean Build Files

```bash
npm run clean
```

## Publishing to NPM

1. Make sure you're logged in to npm:
   ```bash
   npm login
   ```

2. Build the package:
   ```bash
   npm run build
   ```

3. Publish:
   ```bash
   npm publish
   ```

## Environment Variables

For AWS Bedrock integration, you'll need to set these environment variables:

```bash
# AWS Bedrock Configuration
AWS_BEDROCK_REGION=us-east-1
AWS_BEDROCK_ACCESS_KEY_ID=your_access_key_id
AWS_BEDROCK_SECRET_ACCESS_KEY=your_secret_access_key
```

Or create a `.env` file:

```env
AWS_BEDROCK_REGION=us-east-1
AWS_BEDROCK_ACCESS_KEY_ID=your_access_key_id
AWS_BEDROCK_SECRET_ACCESS_KEY=your_secret_access_key
```

## Package Structure

```
aio-ai/
├── src/
│   ├── index.ts                    # Main export file
│   ├── services/
│   │   └── bedrock.service.ts     # AWS Bedrock service
│   ├── errors/
│   │   └── response.error.ts      # Custom error class
│   └── types/
│       └── index.ts               # TypeScript type definitions
├── dist/                           # Compiled JavaScript (generated)
│   ├── index.js                   # Main entry point
│   ├── index.d.ts                 # Type definitions
│   ├── services/
│   ├── errors/
│   └── types/
├── package.json
├── tsconfig.json
├── .gitignore
├── .npmignore
└── README.md
```

## Requirements

- Node.js >= 14.0.0

## License

MIT © Ian

## Author

Ian

## Supported AI Models

### AWS Bedrock
- ✅ Anthropic Claude 3.5 Sonnet (default)
- ✅ Anthropic Claude 3 Opus
- ✅ Anthropic Claude 3 Haiku
- ✅ Anthropic Claude 2.1
- ✅ Anthropic Claude 2.0

To use a different model, specify the `modelId` in the configuration:

```typescript
const bedrock = new BedrockService({
  region: 'us-east-1',
  credentials: { ... },
  modelId: 'anthropic.claude-3-opus-20240229-v1:0'
});
```

### Coming Soon
- 🔜 OpenAI (GPT-4, GPT-3.5)
- 🔜 Google AI (Gemini)
- 🔜 Anthropic Direct API
- 🔜 Azure OpenAI

## Error Handling

The package uses custom `ResponseError` class for consistent error handling:

```typescript
import { BedrockService, ResponseError } from 'aio-ai';

try {
  const translation = await bedrock.translateText(...);
} catch (error) {
  if (error instanceof ResponseError) {
    console.error(`Error ${error.statusCode}: ${error.message}`);
    // Handle specific error codes
    if (error.statusCode === 400) {
      // Bad request - invalid parameters
    } else if (error.statusCode === 500) {
      // Server error
    }
  } else {
    // Handle other errors
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Support

This package is written in TypeScript and includes full type definitions. You'll get:

- ✅ Full IntelliSense/autocomplete support
- ✅ Type checking for all parameters
- ✅ Interface definitions for all config objects
- ✅ Proper error type handling

```typescript
import { 
  BedrockService, 
  BedrockConfig, 
  ResponseError,
  TranslationOptions 
} from 'aio-ai';
```

## Keywords

- ianhomelabs
- aio-ai
- aws-bedrock
- anthropic
- claude
- ai-orchestrator
- translation
- llm
- typescript
- express

## Contributing

Feel free to submit issues or pull requests!

## Repository

GitHub: [https://github.com/mrizkyff/ai-orchestrator.git](https://github.com/mrizkyff/ai-orchestrator.git)

