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

# Api integration

# API Integration Guide

Learn how to integrate Dobby AI into your applications using our comprehensive API.

## 🎯 What You'll Learn

By the end of this guide, you'll know how to:

* Set up API authentication
* Send messages and receive responses
* Manage contexts and conversations
* Handle errors and rate limits
* Build applications with Dobby AI

## 🔑 Getting Started with the API

### Step 1: Get Your API Key

1. **Log in** to your Dobby AI account at [dobby.monleru.fun](https://dobby.monleru.fun)
2. **Go to your profile page**
3. **Navigate to the "API" section**
4. **Click "Generate New Key"**
5. **Copy and store your key securely**

### Step 2: Test Your API Key

Test your API key with a simple request:

```bash  theme={null}
curl -X POST https://api.dobby.monleru.fun/chat/send \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Hello, Dobby!",
    "model": "dobby-70b"
  }'
```

### Step 3: Understand the Response

```json  theme={null}
{
  "response": "Hello! I'm Dobby AI, your intelligent assistant. How can I help you today?",
  "timestamp": "2025-01-01T12:00:00Z"
}
```

## 🚀 Basic API Usage

### Sending Your First Message

**JavaScript Example:**

```javascript  theme={null}
const apiKey = 'your-api-key';
const baseURL = 'https://api.dobby.monleru.fun';

async function sendMessage(message) {
  const response = await fetch(`${baseURL}/chat/send`, {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: message,
      model: 'dobby-70b'
    })
  });

  const data = await response.json();
  return data.response;
}

// Usage
const response = await sendMessage('Hello, Dobby!');
console.log(response);
```

**Python Example:**

```python  theme={null}
import requests

def send_message(message, api_key):
    url = 'https://api.dobby.monleru.fun/chat/send'
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    data = {
        'message': message,
        'model': 'dobby-70b'
    }
    
    response = requests.post(url, headers=headers, json=data)
    return response.json()['response']

# Usage
api_key = 'your-api-key'
response = send_message('Hello, Dobby!', api_key)
print(response)
```

## 🧠 Context Management

### Creating and Using Contexts

**Create a New Context:**

```javascript  theme={null}
async function createContext(name) {
  const response = await fetch(`${baseURL}/chat/send`, {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: `Start a new conversation about ${name}`,
      contextId: generateUUID() // Generate a unique ID
    })
  });

  return response.json();
}
```

**Continue a Conversation:**

```javascript  theme={null}
async function continueConversation(message, contextId) {
  const response = await fetch(`${baseURL}/chat/send`, {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: message,
      contextId: contextId,
      model: 'dobby-70b'
    })
  });

  return response.json();
}
```

### Managing Multiple Contexts

**List All Contexts:**

```javascript  theme={null}
async function getContexts() {
  const response = await fetch(`${baseURL}/chat/contexts`, {
    headers: {
      'X-API-Key': apiKey
    }
  });

  return response.json();
}
```

**Get Specific Context:**

```javascript  theme={null}
async function getContext(contextId) {
  const response = await fetch(`${baseURL}/chat/context/${contextId}`, {
    headers: {
      'X-API-Key': apiKey
    }
  });

  return response.json();
}
```

## 🤖 Working with Different Models

### Model Selection

**Available Models:**

* `dobby-70b` - Default custom model
* `gpt-4` - OpenAI GPT-4
* `gpt-3.5-turbo` - OpenAI GPT-3.5 Turbo

**Using Different Models:**

```javascript  theme={null}
async function sendMessageWithModel(message, model) {
  const response = await fetch(`${baseURL}/chat/send`, {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: message,
      model: model
    })
  });

  return response.json();
}

// Usage examples
const dobbyResponse = await sendMessageWithModel('Hello!', 'dobby-70b');
const gpt4Response = await sendMessageWithModel('Analyze this data', 'gpt-4');
const gpt35Response = await sendMessageWithModel('Quick question', 'gpt-3.5-turbo');
```

### Model Comparison

**Dobby-70B:**

* Best for general conversation
* Good balance of speed and capability
* Optimized for coding help

**GPT-4:**

* Most capable for complex reasoning
* Best for analysis and creative tasks
* Slower but more accurate

**GPT-3.5 Turbo:**

* Fastest response times
* Good for simple tasks
* Cost-effective option

## 📊 Credit System Integration

### Checking Credit Status

**Get Current Credits:**

```javascript  theme={null}
async function getCreditStatus() {
  const response = await fetch(`${baseURL}/credits/status`, {
    headers: {
      'X-API-Key': apiKey
    }
  });

  return response.json();
}

// Usage
const credits = await getCreditStatus();
console.log(`Remaining credits: ${credits.data.remainingCredits}`);
```

**Handle Credit Errors:**

```javascript  theme={null}
async function sendMessageWithCreditCheck(message) {
  try {
    const response = await fetch(`${baseURL}/chat/send`, {
      method: 'POST',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message,
        model: 'dobby-70b'
      })
    });

    if (response.status === 402) {
      throw new Error('Insufficient credits');
    }

    return response.json();
  } catch (error) {
    if (error.message === 'Insufficient credits') {
      console.log('Please wait until tomorrow for credit reset');
    }
    throw error;
  }
}
```

## 🔄 Error Handling

### Common Error Responses

**Rate Limiting:**

```javascript  theme={null}
async function handleRateLimit(func) {
  try {
    return await func();
  } catch (error) {
    if (error.status === 429) {
      const retryAfter = error.headers['Retry-After'];
      console.log(`Rate limited. Retry after ${retryAfter} seconds`);
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      return await func();
    }
    throw error;
  }
}
```

**Authentication Errors:**

```javascript  theme={null}
async function sendMessageWithAuthCheck(message) {
  try {
    const response = await fetch(`${baseURL}/chat/send`, {
      method: 'POST',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message,
        model: 'dobby-70b'
      })
    });

    if (response.status === 401) {
      throw new Error('Invalid API key');
    }

    return response.json();
  } catch (error) {
    if (error.message === 'Invalid API key') {
      console.log('Please check your API key');
    }
    throw error;
  }
}
```

### Retry Logic

**Implementing Retry Logic:**

```javascript  theme={null}
async function sendMessageWithRetry(message, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(`${baseURL}/chat/send`, {
        method: 'POST',
        headers: {
          'X-API-Key': apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          message: message,
          model: 'dobby-70b'
        })
      });

      if (response.ok) {
        return response.json();
      }

      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After');
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      throw new Error(`HTTP ${response.status}`);
    } catch (error) {
      if (i === maxRetries - 1) {
        throw error;
      }
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
    }
  }
}
```

## 🏗️ Building Applications

### Simple Chat Application

**HTML Structure:**

```html  theme={null}
<!DOCTYPE html>
<html>
<head>
    <title>Dobby AI Chat</title>
    <style>
        .chat-container { max-width: 800px; margin: 0 auto; padding: 20px; }
        .messages { height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
        .message { margin-bottom: 10px; padding: 5px; }
        .user-message { background-color: #e3f2fd; text-align: right; }
        .ai-message { background-color: #f5f5f5; }
        .input-container { display: flex; gap: 10px; }
        .input-field { flex: 1; padding: 10px; border: 1px solid #ccc; }
        .send-button { padding: 10px 20px; background-color: #2196f3; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <div class="chat-container">
        <div id="messages" class="messages"></div>
        <div class="input-container">
            <input type="text" id="messageInput" class="input-field" placeholder="Type your message...">
            <button onclick="sendMessage()" class="send-button">Send</button>
        </div>
    </div>

    <script>
        const API_KEY = 'your-api-key';
        const BASE_URL = 'https://api.dobby.monleru.fun';

        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;

            // Add user message to chat
            addMessage(message, 'user');
            input.value = '';

            try {
                const response = await fetch(`${BASE_URL}/chat/send`, {
                    method: 'POST',
                    headers: {
                        'X-API-Key': API_KEY,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message,
                        model: 'dobby-70b'
                    })
                });

                const data = await response.json();
                addMessage(data.response, 'ai');
            } catch (error) {
                addMessage('Error: ' + error.message, 'ai');
            }
        }

        function addMessage(text, sender) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            messageDiv.textContent = text;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // Allow sending with Enter key
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>
```

### Node.js Server Application

**Express.js Example:**

```javascript  theme={null}
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const port = 3000;

app.use(express.json());
app.use(express.static('public'));

const API_KEY = 'your-api-key';
const BASE_URL = 'https://api.dobby.monleru.fun';

app.post('/api/chat', async (req, res) => {
  try {
    const { message, model = 'dobby-70b' } = req.body;

    const response = await fetch(`${BASE_URL}/chat/send`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message,
        model
      })
    });

    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
```

## 📱 Mobile App Integration

### React Native Example

**Install Dependencies:**

```bash  theme={null}
npm install @react-native-async-storage/async-storage
```

**API Service:**

```javascript  theme={null}
// services/dobbyAI.js
const API_KEY = 'your-api-key';
const BASE_URL = 'https://api.dobby.monleru.fun';

export class DobbyAIService {
  static async sendMessage(message, model = 'dobby-70b') {
    try {
      const response = await fetch(`${BASE_URL}/chat/send`, {
        method: 'POST',
        headers: {
          'X-API-Key': API_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          message,
          model
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  }

  static async getContexts() {
    try {
      const response = await fetch(`${BASE_URL}/chat/contexts`, {
        headers: {
          'X-API-Key': API_KEY
        }
      });

      return await response.json();
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  }
}
```

**React Component:**

```javascript  theme={null}
// components/ChatScreen.js
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList } from 'react-native';
import { DobbyAIService } from '../services/dobbyAI';

export default function ChatScreen() {
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(false);

  const sendMessage = async () => {
    if (!inputText.trim() || loading) return;

    const userMessage = { text: inputText, sender: 'user' };
    setMessages(prev => [...prev, userMessage]);
    setInputText('');
    setLoading(true);

    try {
      const response = await DobbyAIService.sendMessage(inputText);
      const aiMessage = { text: response.response, sender: 'ai' };
      setMessages(prev => [...prev, aiMessage]);
    } catch (error) {
      const errorMessage = { text: 'Error: ' + error.message, sender: 'ai' };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <FlatList
        data={messages}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <View style={{ 
            padding: 10, 
            marginVertical: 5,
            backgroundColor: item.sender === 'user' ? '#e3f2fd' : '#f5f5f5',
            alignSelf: item.sender === 'user' ? 'flex-end' : 'flex-start',
            borderRadius: 10
          }}>
            <Text>{item.text}</Text>
          </View>
        )}
      />
      
      <View style={{ flexDirection: 'row', marginTop: 10 }}>
        <TextInput
          style={{ 
            flex: 1, 
            borderWidth: 1, 
            borderColor: '#ccc', 
            padding: 10, 
            borderRadius: 5 
          }}
          value={inputText}
          onChangeText={setInputText}
          placeholder="Type your message..."
        />
        <TouchableOpacity
          style={{ 
            backgroundColor: '#2196f3', 
            padding: 10, 
            marginLeft: 10, 
            borderRadius: 5 
          }}
          onPress={sendMessage}
          disabled={loading}
        >
          <Text style={{ color: 'white' }}>
            {loading ? 'Sending...' : 'Send'}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
```

## 🔧 Advanced Features

### Streaming Responses

**Implementing Streaming:**

```javascript  theme={null}
async function sendMessageStream(message, onChunk) {
  const response = await fetch(`${baseURL}/chat/send`, {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: message,
      model: 'dobby-70b',
      stream: true
    })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = JSON.parse(line.slice(6));
        onChunk(data);
      }
    }
  }
}
```

### Batch Processing

**Processing Multiple Messages:**

```javascript  theme={null}
async function processBatch(messages) {
  const results = [];
  
  for (const message of messages) {
    try {
      const response = await sendMessage(message);
      results.push({ message, response: response.response, success: true });
    } catch (error) {
      results.push({ message, error: error.message, success: false });
    }
  }
  
  return results;
}
```

## 🆘 Troubleshooting

### Common Issues

**API Key Issues:**

* Verify your API key is correct
* Check if the key has expired
* Ensure you're using the right header format

**Rate Limiting:**

* Implement retry logic with exponential backoff
* Monitor your request frequency
* Consider upgrading your plan

**Network Issues:**

* Check your internet connection
* Verify the API endpoint is accessible
* Handle timeouts appropriately

### Debugging Tips

**Enable Logging:**

```javascript  theme={null}
const DEBUG = true;

function log(message, data) {
  if (DEBUG) {
    console.log(`[Dobby AI] ${message}`, data);
  }
}

async function sendMessage(message) {
  log('Sending message', { message });
  
  try {
    const response = await fetch(`${baseURL}/chat/send`, {
      method: 'POST',
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message,
        model: 'dobby-70b'
      })
    });

    log('Response received', { status: response.status });
    
    const data = await response.json();
    log('Response data', data);
    
    return data;
  } catch (error) {
    log('Error occurred', error);
    throw error;
  }
}
```

## 📚 Additional Resources

* [API Reference](../api-reference.md) - Complete API documentation
* [FAQ](../faq.md) - Common questions and answers
* [Getting Started](../getting-started.md) - Basic setup guide
* [Context Management](./context-management.md) - Managing conversations

***

*Ready to build with Dobby AI? Start with a simple integration and expand from there!*


Built with [Mintlify](https://mintlify.com).