npm package: @hamonikr/airun-sdk
Description: JavaScript/Node.js SDK for Hamonize AIRUN API - AI-powered system for integrated document generation and management
Author: Hamonize Team
Latest version: 1.0.7

# AIRUN JavaScript/Node.js SDK

JavaScript/TypeScript SDK for Hamonize AIRUN API - AI-powered system for integrated document generation and management.

## Installation

```bash
# npm
npm install airun-sdk

# yarn
yarn add airun-sdk

# pnpm
pnpm add airun-sdk
```

## Quick Start

### Node.js (CommonJS)

```javascript
const { AIRUN } = require('airun-sdk');

// Initialize client
const client = new AIRUN({
  serverUrl: 'http://localhost:5500',
  apiKey: 'your-api-key-here'
});

async function example() {
  try {
    // Chat with AI
    const response = await client.chat.create({
      prompt: 'Hello, how are you?',
      options: { model: 'gpt-4' }
    });
    console.log(response.data.response);

    // Generate code
    const codeResponse = await client.code.create({
      prompt: 'Create a function to calculate factorial',
      options: { language: 'javascript' }
    });
    console.log(codeResponse.data.code);

    // Search with RAG
    const ragResponse = await client.rag.search({
      query: 'What is machine learning?',
      ragSearchScope: 'personal'
    });
    console.log(ragResponse.data.results);

    // Web search
    const webResponse = await client.web.search({
      query: 'Latest AI trends in 2024'
    });
    console.log(webResponse.data.results);
  } catch (error) {
    console.error('Error:', error);
  }
}

example();
```

### TypeScript / ES Modules

```typescript
import { AIRUN, ChatOptions } from 'airun-sdk';

// Initialize client
const client = new AIRUN({
  serverUrl: 'http://localhost:5500',
  apiKey: 'your-api-key-here'
});

// Example with TypeScript types
async function chatExample() {
  const options: ChatOptions = {
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 1000
  };

  const response = await client.chat.create({
    prompt: 'Explain quantum computing',
    options
  });

  console.log(response.data.response);
}

chatExample();
```

### Browser Usage

```html
<!DOCTYPE html>
<html>
<head>
  <title>AIRUN SDK Example</title>
  <script src="https://unpkg.com/airun-sdk/dist/index.umd.min.js"></script>
</head>
<body>
  <script>
    const client = new AIRUN({
      serverUrl: 'http://localhost:5500',
      apiKey: 'your-api-key-here'
    });

    client.chat.create({
      prompt: 'Hello from browser!',
      options: { model: 'gpt-3.5-turbo' }
    }).then(response => {
      console.log(response.data.response);
    }).catch(error => {
      console.error(error);
    });
  </script>
</body>
</html>
```

## Configuration

You can configure the SDK using environment variables:

```bash
export AIRUN_SERVER_URL="http://localhost:5500"
export AIRUN_API_KEY="your-api-key-here"
```

Or using a `.env` file:

```env
AIRUN_SERVER_URL=http://localhost:5500
AIRUN_API_KEY=your-api-key-here
```

## Features

- **🤖 Chat AI**: Natural language conversation with AI models
- **💻 Code Generation**: Generate code in various programming languages
- **🔍 RAG Search**: Search through your documents with advanced RAG capabilities
- **🌐 Web Search**: Perform web searches with AI-powered results
- **📊 Report Generation**: Generate comprehensive reports
- **🧠 Context Management**: Manage conversation context and memories
- **👤 User System Prompts**: Manage custom system prompts
- **📝 Session Management**: Create and manage chat sessions

## API Reference

### Chat API

```typescript
// Create chat completion
const response = await client.chat.create({
  prompt: 'Your question here',
  options: {
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 1000,
    systemPrompt: 'You are a helpful assistant',
    sessionId: 'session-123'
  }
});

// Synchronous chat completion
const syncResponse = await client.chat.createSync({
  prompt: 'Your question here',
  options: { model: 'gpt-4' }
});

// Get job status
const status = await client.chat.getStatus('job-id-123');
```

### Code API

```typescript
// Generate code
const response = await client.code.create({
  prompt: 'Create a REST API server',
  options: {
    language: 'typescript',
    framework: 'express',
    includeTests: true,
    includeDocs: true
  }
});

// Generate code synchronously
const syncResponse = await client.code.createSync({
  prompt: 'Create a React component',
  options: { language: 'typescript' }
});

// Execute code
const execResponse = await client.code.execute({
  pythonCode: 'print("Hello, World!")',
  options: { timeout: 30 }
});

// Save code as ZIP
const saveResponse = await client.code.saveCode({
  pythonCode: 'def hello():\n    print("Hello")',
  options: { filename: 'my_script.py' }
});

// Download code file
await client.code.download('generated_code.py', './downloads/');
```

### RAG API

```typescript
// Search documents
const response = await client.rag.search({
  query: 'Find information about...',
  ragSearchScope: 'personal', // or 'global'
  options: { limit: 10 }
});

// Search synchronously
const syncResponse = await client.rag.searchSync({
  query: 'Search query',
  ragSearchScope: 'personal'
});

// Add documents to RAG
const addResponse = await client.rag.add({
  documents: ['path/to/document.pdf', 'https://example.com/doc'],
  userId: 'user123'
});

// Initialize RAG for user
const initResponse = await client.rag.init({
  userId: 'user123',
  documentName: 'My Documents'
});

// List RAG documents
const documents = await client.rag.list();

// Delete documents
const deleteResponse = await client.rag.delete({
  userId: 'user123',
  filePaths: ['doc1.pdf', 'doc2.pdf']
});
```

### Web Search API

```typescript
// Search web
const response = await client.web.search({
  query: 'Python best practices 2024',
  options: {
    limit: 10,
    region: 'kr',
    language: 'ko',
    safeSearch: 'moderate',
    includeImages: false
  }
});

// Search synchronously
const syncResponse = await client.web.searchSync({
  query: 'AI news today'
});

// Get image
await client.web.getImage('image.jpg', './downloads/');
```

### Report API

```typescript
// Generate report
const response = await client.report.create({
  topic: 'Market Analysis Report',
  dataSources: ['source1.pdf', 'source2.csv'],
  options: {
    format: 'pdf',
    language: 'en',
    template: 'professional',
    includeToc: true,
    includeSummary: true
  }
});
```

### Context API

```typescript
// Save memory
await client.context.saveMemory({
  memoryType: 'user_preference',
  key: 'theme',
  value: 'dark_mode',
  userId: 'user123'
});

// Get memories
const memories = await client.context.getMemories({
  userId: 'user123',
  memoryType: 'user_preference',
  limit: 50
});

// Delete memory
await client.context.deleteMemory({
  memoryType: 'user_preference',
  key: 'theme',
  userId: 'user123'
});

// Clear all memories
await client.context.clearMemories({ userId: 'user123' });

// Get session summaries
const sessions = await client.context.getSessions({
  userId: 'user123'
});

// Get session details
const session = await client.context.getSession({
  sessionId: 'session-123',
  userId: 'user123'
});
```

### User API

```typescript
// Get system prompt
const prompt = await client.user.getSystemPrompt({
  userId: 'user123'
});

// Update system prompt
await client.user.updateSystemPrompt({
  userId: 'user123',
  systemPrompt: 'You are a helpful assistant...'
});
```

### Session API

```typescript
// Create session
const session = await client.sessions.create({
  type: 'chat',
  title: 'My Chat Session',
  metadata: { topic: 'AI discussion' }
});

// Get all sessions
const sessions = await client.sessions.getSessions({
  type: 'chat'
});

// Get specific session
const session = await client.sessions.getSession('session-123');

// Update session
await client.sessions.updateSession({
  sessionId: 'session-123',
  title: 'Updated Title',
  metadata: { updated: true }
});

// Delete session
await client.sessions.deleteSession('session-123');

// Delete all sessions
await client.sessions.deleteAllSessions();
```

## Error Handling

The SDK provides comprehensive error handling with typed exceptions:

```typescript
import {
  AIRUN,
  AIRUNError,
  APIError,
  AuthenticationError,
  ValidationError,
  NetworkError,
  RateLimitError
} from 'airun-sdk';

const client = new AIRUN({ apiKey: 'your-key' });

try {
  const response = await client.chat.create({ prompt: 'Hello' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded. Retry after:', error.retryAfter);
  } else if (error instanceof APIError) {
    console.error(`API error: ${error.code} - ${error.message}`);
  } else if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message, 'Field:', error.field);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}
```

## Development

```bash
# Clone repository
git clone https://github.com/hamonikr/airun.git
cd airun/sdk/js-sdk

# Install dependencies
npm install

# Build the SDK
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Lint code
npm run lint

# Format code
npm run format

# Type checking
npm run type-check

# Build in development mode with watch
npm run dev
```

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions out of the box:

```typescript
import { AIRUN, ChatOptions, CodeOptions, RAGOptions } from 'airun-sdk';

const client = new AIRUN({
  serverUrl: process.env.AIRUN_SERVER_URL,
  apiKey: process.env.AIRUN_API_KEY
});

const options: ChatOptions = {
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 1000
};
```

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- Documentation: https://docs.hamonize.kr/airun
- Issues: https://github.com/hamonikr/airun/issues
- Email: team@hamonize.kr