> ## Documentation Index
> Fetch the complete documentation index at: https://docs.animusai.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Choose Your Path

> Not sure whether to use the Animus SDK or REST API? This guide will help you choose the best approach based on your project requirements, technical constraints, and development preferences.

## Quick Decision Matrix

| Factor                   | SDK                      | REST API                 |
| ------------------------ | ------------------------ | ------------------------ |
| **Language**             | JavaScript/TypeScript    | Any language             |
| **Environment**          | Browser applications     | Any environment          |
| **Setup Time**           | \< 30 seconds            | 2-5 minutes              |
| **Code Required**        | 3-5 lines                | 15-30 lines              |
| **Authentication**       | Automatic token handling | Manual header management |
| **Streaming**            | AsyncIterable pattern    | Manual SSE parsing       |
| **Event Handling**       | Built-in events          | Custom implementation    |
| **Conversation History** | Automatic management     | Manual tracking          |
| **Learning Curve**       | Minimal                  | Moderate                 |

## Choose the SDK When...

<CardGroup cols={2}>
  <Card title="Building Browser Applications" icon="globe">
    Perfect for web apps, SPAs, and browser-based tools
  </Card>

  <Card title="Want Rapid Development" icon="bolt">
    Get started in minutes with minimal boilerplate code
  </Card>

  <Card title="Need Event-Driven Architecture" icon="bullseye">
    Built-in events for messages, images, and streaming
  </Card>

  <Card title="Building Conversational Interfaces" icon="robot">
    Automatic conversation history and turn management
  </Card>
</CardGroup>

### SDK Advantages

✅ **Minimal Setup**: One import, one configuration object\
✅ **Automatic Authentication**: Secure token handling with refresh\
✅ **Built-in Events**: React to messages, images, and errors\
✅ **Conversation Management**: Automatic history and context\
✅ **Streaming Made Easy**: AsyncIterable pattern for real-time responses\
✅ **Image Generation**: Automatic detection and generation\
✅ **TypeScript Support**: Full type safety and autocomplete\
✅ **Error Handling**: Specific error types for different scenarios

### SDK Example

```javascript theme={null}
// Complete chat setup in 3 lines
import { AnimusClient } from 'animus-client';
const client = new AnimusClient({ tokenProviderUrl: 'your-auth-server' });
client.on('messageComplete', (data) => console.log('Friend:', data.content));
client.chat.send('Hey, how has your day been?');
```

## Choose the REST API When...

<CardGroup cols={2}>
  <Card title="Using Non-JavaScript Languages" icon="code">
    Python, Java, C#, Go, PHP, Ruby, or any other language
  </Card>

  <Card title="Building Backend Services" icon="server">
    Server-side applications, APIs, and microservices
  </Card>

  <Card title="Need Maximum Control" icon="wrench">
    Custom request handling and response processing
  </Card>

  <Card title="Batch Processing" icon="chart-bar">
    Processing large datasets or automated workflows
  </Card>
</CardGroup>

### REST API Advantages

✅ **Universal Language Support**: Works with any programming language\
✅ **Maximum Flexibility**: Full control over requests and responses\
✅ **Server-Side Integration**: Perfect for backend services\
✅ **Existing Infrastructure**: Integrate with current HTTP clients\
✅ **Batch Operations**: Process multiple requests efficiently\
✅ **Custom Authentication**: Implement your own auth patterns

### REST API Example

```python theme={null}
# Python example with requests
import requests

response = requests.post('https://api.animusai.co/v3/chat/completions', 
  headers={'Authorization': 'Bearer your-api-key'},
  json={
    'model': 'vivian-llama3.1-70b-1.0-fp8',
    'messages': [{'role': 'user', 'content': 'Hello!'}]
  })
```

## Use Case Scenarios

### Perfect for SDK

**🤖 Chatbot Interfaces**

```javascript theme={null}
// Natural conversation with automatic history
client.on('messageComplete', (data) => updateChatUI(data.content));
client.chat.send(userInput);
```

**📱 Real-time Applications**

```javascript theme={null}
// Streaming responses with events
const stream = await client.chat.completions({ stream: true });
for await (const chunk of stream) {
  updateUI(chunk.choices[0].delta.content);
}
```

**🎨 Creative Tools**

```javascript theme={null}
// Automatic image generation
client.on('imageGenerationComplete', (data) => displayImage(data.imageUrl));
client.chat.send('I need some inspiration today, could you create something beautiful?');
```

**🔄 Interactive Experiences**

```javascript theme={null}
// Conversational turns with natural delays
const client = new AnimusClient({
  chat: {
    systemMessage: 'You are a caring companion.',
    autoTurn: true // Natural conversation flow
  }
});
```

### Perfect for REST API

**🤝 Chat Co-pilot with Response Selection**

```python theme={null}
# Generate multiple response options for human selection
response = requests.post(api_url, json={
    'model': 'vivian-llama3.1-70b-1.0-fp8',
    'messages': [{'role': 'user', 'content': user_message}],
    'n': 3,  # Generate 3 response options
    'temperature': 0.8  # Add variety between responses
})

# Extract all response options
response_options = [choice['message']['content'] for choice in response.json()['choices']]
# Present options to human for selection
best_response = human_select_best(response_options)
```

**👁️ Video Categorization with Vision**

```python theme={null}
# Batch video analysis and categorization
video_batch = ['frame1.jpg', 'frame2.jpg', 'frame3.jpg']
for frame in video_batch:
    response = requests.post(api_url, json={
        'model': 'xavier-vision-1.0',
        'messages': [{
            'role': 'user',
            'content': [
                {'type': 'text', 'text': 'Categorize this video frame and provide a description'},
                {'type': 'image_url', 'image_url': {'url': f'data:image/jpeg;base64,{encode_image(frame)}'}}
            ]
        }]
    })
    video_analysis.append(response.json())
```

**💬 Conversation Analysis & Profiling**

```python theme={null}
# Analyze conversation patterns and build speaker profiles
conversation_history = load_chat_history(user_id)
analysis = requests.post(api_url, json={
    'model': 'vivian-llama3.1-70b-1.0-fp8',
    'messages': [{
        'role': 'user', 
        'content': f'Analyze this conversation and create personality profiles for both speakers: {conversation_history}'
    }]
})
speaker_profiles = analysis.json()['choices'][0]['message']['content']
```

## Feature Comparison

### Authentication

**SDK Approach:**

```javascript theme={null}
// Automatic token management
const client = new AnimusClient({
  tokenProviderUrl: 'http://localhost:3001/token' // Your secure backend
});
// SDK handles token refresh automatically
```

**REST API Approach:**

```python theme={null}
# Manual token management
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.post(url, headers=headers, json=data)
```

### Streaming

**SDK Approach:**

```javascript theme={null}
// Clean AsyncIterable pattern
const stream = await client.chat.completions({ stream: true });
for await (const chunk of stream) {
  console.log(chunk.choices[0].delta.content);
}
```

**REST API Approach:**

```python theme={null}
# Manual SSE parsing
response = requests.post(url, stream=True)
for line in response.iter_lines():
    if line.startswith(b'data: '):
        chunk = json.loads(line[6:])
        print(chunk['choices'][0]['delta']['content'])
```

### Error Handling

**SDK Approach:**

```javascript theme={null}
// Specific error types
try {
  // Event-driven approach
  client.chat.send('Hello');
  
  // Or use completions() for direct API calls
  const response = await client.chat.completions({
    messages: [{ role: 'user', content: 'Hello' }]
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Handle auth issues
  } else if (error instanceof ApiError) {
    // Handle API errors
  }
}
```

**REST API Approach:**

```python theme={null}
# HTTP status code handling
try:
    response = requests.post(url, json=data)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 401:
        # Handle auth error
    elif e.response.status_code == 429:
        # Handle rate limit
```

## Migration Paths

### From REST API to SDK

If you're currently using the REST API and want to migrate to the SDK:

1. **Set up authentication server** (see [SDK Quickstart](/sdk-quickstart))
2. **Replace HTTP calls** with SDK methods
3. **Add event listeners** for reactive UI updates
4. **Enable automatic features** like conversation history

### From SDK to REST API

If you need to migrate from SDK to REST API:

1. **Implement authentication** header management
2. **Add streaming parsing** for real-time responses
3. **Build conversation history** tracking
4. **Handle errors** with HTTP status codes

## Decision Framework

Ask yourself these questions:

1. **What's your primary language?**
   * JavaScript/TypeScript → SDK
   * Other languages → REST API

2. **What's your environment?**
   * Browser application → SDK
   * Server/backend → REST API

3. **How complex is your use case?**
   * Simple chat/conversation → SDK
   * Complex integrations → REST API

4. **Do you need real-time features?**
   * Yes, with minimal code → SDK
   * Yes, with full control → REST API

5. **How quickly do you need to ship?**
   * ASAP → SDK
   * Have time for custom implementation → REST API

## Get Started

Ready to choose your path?

<CardGroup cols={2}>
  <Card title="Start with SDK" icon="rocket" href="/sdk-quickstart">
    Perfect for JavaScript/TypeScript browser applications
  </Card>

  <Card title="Start with REST API" icon="code" href="/rest-api-quickstart">
    Ideal for any language or server-side applications
  </Card>
</CardGroup>

<Tip>
  **Still unsure?** Start with the SDK if you're building a browser application with JavaScript/TypeScript. You can always switch to the REST API later if you need more control or different language support.
</Tip>
