> ## Documentation Index
> Fetch the complete documentation index at: https://futureai-d8c0eb94.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Get started

> The Future AI SDK provides a WebSocket-based session-like system for real-time communication with the Future AI platform. It processes email content using AI to extract valuable insights about user interests and meaningful contacts.

## Install

<CodeGroup>
  ```javascript npm
     npm install @future-sdk/future-js
  ```

  ```javascript yarn
     yarn add @future-sdk/future-js
  ```

  ```javascript pnpm
     pnpm add @future-sdk/future-js
  ```
</CodeGroup>

## Prerequisites

* Future AI API Key
* Node.js environment
* Access to Future AI services

## API key & SDK configuration

To get started, you need to login to your account on [FutureAI](https://developer.futureai.com/) and create a new Api key. You will get an API key, and the necesery config to authenticate your requests.

## Quickstart

```javascript
import { startFutureSession } from '@futureai/sdk';
const session = await startFutureSession({
  apiKey: 'YOUR_API_KEY',
  iframeUrl: 'https://iframe.futureai.com',
  serverUrl: 'https://api.futureai.com',
  websocketUrl: 'wss://ws.futureai.com',
  onSessionUpdate: (session) => {
    console.log('Session updated:', session);
  },
  auth: {
    token: 'USER_AUTH_TOKEN' // Optional
  },
  onError: (error) => {
    console.error('Error:', error);
  }
});
```

## Configuration Options

| Parameter       | Type     | Required | Description                            |
| --------------- | -------- | -------- | -------------------------------------- |
| apiKey          | string   | Yes      | Your Future AI API key                 |
| iframeUrl       | string   | Yes      | URL for the Future AI iframe interface |
| serverUrl       | string   | Yes      | Base URL for REST API endpoints        |
| websocketUrl    | string   | Yes      | WebSocket server URL                   |
| onSessionUpdate | function | Yes      | Callback for session state updates     |
| auth            | object   | No       | Authentication configuration           |
| onError         | function | No       | Error handling callback                |

## Authentication flow

### 1. Initial connection

```json
{
    "id": "session_id",
    "version": 1,
    "ended": false,
    "merchantId": "merchant_id",
    "userId": null,
    "lastEventName": "SessionStarted"
}
```

### 2. Google OAuth2 Authentication

```json
{
    "id": "session_id",
    "version": 2,
    "ended": false,
    "merchantId": "merchant_id",
    "userId": null,
    "lastEventName": "LinkedAccountCreated"
}
```

### 3. User Authentication

```json
{
    "id": "session_id",
    "version": 3,
    "ended": false,
    "merchantId": "merchant_id",
    "userId": null,
    "lastEventName": "UserAuthenticated",
    "userAccessToken": "jwt_token"
}
```

### 4. Email Analysis Results

```json
{
    "id": "session_id",
    "version": 4,
    "ended": false,
    "merchantId": "merchant_id",
    "userId": "user_id",
    "lastEventName": "UserGenerativeResults",
    "userAccessToken": "jwt_token",
    "results": [/* interests and connections */]
}
```

## Future Button Implementation

### Adding the Button

```html
<div class="future-button"></div>
```

```javascript
Future.createFutureButton({
    container: '.future-button',
    sessionId: session.id,
    merchantFlowId: 'YOUR_MERCHANT_FLOW_ID'
});
```

## Error Handling

### Error Response Cases

#### Invalid API Key

```javascript
{
    success: false,
    error: {
        code: 'INVALID_MERCHANT',
        message: 'Merchant not found. API key is invalid'
    }
}
```

#### Missing API Key

```javascript
{
    success: false,
    error: {
        code: 'API_KEY_REQUIRED',
        message: 'API key is required'
    }
}
```

#### Invalid Authentication Token

```javascript
{
    success: false,
    error: {
        code: 'INVALID_CREDENTIALS',
        message: 'Invalid authentication token'
    }
}
```

#### Internal Server Error

```javascript
{
    success: false,
    error: {
        code: 'INTERNAL_ERROR',
        message: 'Internal error'
    }
}
```

## Implementation Example

```javascript
import { startFutureSession } from '@futureai/sdk';
// With new session
const session = await startFutureSession({
    apiKey: 'YOUR_API_KEY',
    onSessionUpdate: (session) => {
        switch(session.lastEventName) {
            case 'SessionStarted':
                console.log('Session initialized');
                // Initialize button
                Future.createFutureButton({
                    container: '.future-button',
                    sessionId: session.id,
                    merchantFlowId: process.env.MERCHANT_FLOW_ID
                });
                break;
            case 'LinkedAccountCreated':
                console.log('Google account linked');
                break;
            case 'UserAuthenticated':
                console.log('User authenticated');
                localStorage.setItem('userToken', session.userAccessToken);
                break;
            case 'UserGenerativeResults':
                console.log('Results ready:', session.results);
                break;
        }
    },
    onError: handleAuthError
});
function handleAuthError(error) {
    if (!error.success) {
        switch (error.error.code) {
            case 'API_KEY_REQUIRED':
                console.error('API key must be provided');
                break;
            case 'INVALID_MERCHANT':
                console.error('Invalid API key provided');
                break;
            case 'INVALID_CREDENTIALS':
                console.error('Invalid or expired authentication token');
                localStorage.removeItem('userToken');
                break;
            case 'INTERNAL_ERROR':
                console.error('System error occurred:', error.error.message);
                break;
        }
    }
}
```

## Results Structure

```typescript
interface Interest {
    interest: string;
    connections: Array<{
        name: string;
        email: string;
        score: number | null;
        relationship: string;
    }>;
}
```

## Best Practices

1. Always handle session updates through the onSessionUpdate callback
2. Implement proper error handling using the onError callback
3. Store and manage user tokens appropriately
4. Handle reconnection scenarios
5. Validate configuration before initializing
6. Implement proper cleanup on errors
