AI Chatbot Integration Guide: Add GPT-5 to Your App in 10 Minutes

Published 2026-07-26 · 13 min read

Adding an AI chatbot to your application used to require a team of ML engineers, weeks of training, and significant infrastructure. In 2026, it takes 10 minutes and a few lines of code. This guide walks you through the complete process — from getting an API key to deploying a production-ready chatbot with streaming responses, conversation history, and error handling.

Get Your Free API Key →

Prerequisites

You'll need:

That's it. No GPU, no model training, no infrastructure setup. Everything runs through a simple HTTP API.

Step 1: Get Your API Key (2 Minutes)

Sign up at ai.dr-ai.top/signin and navigate to the API Keys section in your dashboard. Create a new key — you'll use this as your authentication token for all API calls.

# Your API key looks like this:
# sk-drai-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Test it works:
curl https://ai.dr-ai.top/v1/models \
  -H "Authorization: Bearer sk-your-key"

# You should see a list of available models

Step 2: Your First Chat Completion (1 Minute)

The core API is a single endpoint: /v1/chat/completions. You send a list of messages, and the model responds with the next message:

curl https://ai.dr-ai.top/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5-mini",
    "messages": [
      {"role": "user", "content": "What is the capital of France?"}
    ]
  }'

The response contains the model's answer, token counts (for billing), and metadata:

{
  "id": "chatcmpl-xxx",
  "model": "gpt-5-mini",
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "The capital of France is Paris."
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 8,
    "total_tokens": 20
  }
}

Step 3: Build a Chatbot in Python (3 Minutes)

Here's a complete Python chatbot with conversation history:

import requests

class DrAIChatbot:
    def __init__(self, api_key, model="gpt-5-mini"):
        self.api_key = api_key
        self.model = model
        self.base_url = "https://ai.dr-ai.top/v1"
        self.history = [
            {"role": "system", "content": "You are a helpful assistant."}
        ]
    
    def chat(self, user_message):
        # Add user message to history
        self.history.append({"role": "user", "content": user_message})
        
        # Call the API
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": self.model,
                "messages": self.history,
                "temperature": 0.7,
                "max_tokens": 1000
            }
        )
        
        result = response.json()
        assistant_message = result["choices"][0]["message"]["content"]
        
        # Add assistant response to history
        self.history.append({"role": "assistant", "content": assistant_message})
        
        return assistant_message

# Use it:
bot = DrAIChatbot("sk-your-key")
print(bot.chat("Hi! Can you help me with Python?"))
print(bot.chat("How do I read a CSV file?"))

This maintains conversation context across messages — the bot remembers what was said earlier in the conversation. For more on conversation management, see our prompt engineering guide.

Step 4: Add Streaming Responses (2 Minutes)

Streaming makes your chatbot feel instant — tokens appear as they're generated instead of waiting for the entire response. This is critical for user experience:

import requests
import json

def stream_chat(api_key, model, messages):
    response = requests.post(
        "https://ai.dr-ai.top/v1/chat/completions",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "messages": messages,
            "stream": True  # Enable streaming
        },
        stream=True
    )
    
    full_response = ""
    for line in response.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                data = line[6:]
                if data == '[DONE]':
                    break
                chunk = json.loads(data)
                delta = chunk['choices'][0]['delta'].get('content', '')
                if delta:
                    full_response += delta
                    print(delta, end='', flush=True)  # Print as it arrives
    print()  # New line at end
    return full_response

# Stream a response in real-time:
stream_chat("sk-your-key", "gpt-5-mini", [
    {"role": "user", "content": "Write a short poem about coding."}
])

For a deep dive on streaming implementation (SSE vs WebSocket), see our streaming guide.

Step 5: Build a Web Frontend (2 Minutes)

Here's a minimal HTML/JavaScript chat interface that connects directly to the DrAI API:

<!DOCTYPE html>
<html>
<head><title>My AI Chatbot</title></head>
<body>
  <div id="chat"></div>
  <input id="input" placeholder="Type a message...">
  <button onclick="send()">Send</button>

<script>
let messages = [{role:"system", content:"You are a helpful assistant."}];

async function send() {
  const input = document.getElementById('input');
  const chat = document.getElementById('chat');
  const userMsg = input.value;
  
  messages.push({role:"user", content:userMsg});
  chat.innerHTML += '<p><b>You:</b> ' + userMsg + '</p>';
  input.value = '';
  
  const response = await fetch('https://ai.dr-ai.top/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-5-mini',
      messages: messages,
      stream: true
    })
  });
  
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let assistantDiv = document.createElement('p');
  assistantDiv.innerHTML = '<b>AI:</b> ';
  chat.appendChild(assistantDiv);
  
  while (true) {
    const {done, value} = await reader.read();
    if (done) break;
    const lines = decoder.decode(value).split('\n');
    for (const line of lines) {
      if (line.startsWith('data: ') && line !== 'data: [DONE]') {
        const data = JSON.parse(line.slice(6));
        const delta = data.choices[0]?.delta?.content || '';
        assistantDiv.innerHTML += delta;
      }
    }
  }
  messages.push({role:"assistant", content:assistantDiv.textContent.replace('AI: ','')});
}
</script>
</body>
</html>

Production Best Practices

Always Handle Errors Gracefully

API calls can fail for many reasons: network issues, rate limits, model outages, malformed requests. Your chatbot should never crash — it should inform the user and offer a retry:

async function safeChat(messages) {
    try {
        const response = await fetch('/v1/chat/completions', {
            method: 'POST',
            headers: getHeaders(),
            body: JSON.stringify({model: 'gpt-5-mini', messages})
        });
        
        if (response.status === 429) {
            // Rate limited - wait and retry
            await new Promise(r => setTimeout(r, 2000));
            return safeChat(messages);
        }
        
        if (!response.ok) {
            throw new Error(`API error: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('Chat failed:', error);
        return {error: "I'm having trouble right now. Please try again."};
    }
}

Implement Rate Limiting

Don't let a single user consume all your API quota. Implement per-user rate limits on your backend before forwarding to the AI API. Read our rate limiting guide for implementation patterns.

Use Conversation Summarization

As conversations grow long, the token count (and cost) balloons. Every 10-15 messages, summarize the conversation so far and start fresh with the summary as context. This keeps costs predictable without losing context.

Add Content Moderation

Before sending user input to the AI, filter it for spam, NSFW content, and prompt injection attempts. See our content moderation guide for implementation details.

Choosing the Right Model for Your Chatbot

Not every message needs GPT-5's power. A tiered approach keeps costs low while maintaining quality:

Use CaseRecommended ModelCost Impact
Greeting / simple FAQGPT-5-nano$0.05/$0.40 per 1M
Standard support chatGPT-5-mini$0.25/$2.00 per 1M
Complex problem solvingGPT-5 or Claude Opus 4$5/$15 per 1M
Code assistanceClaude Sonnet 4$3/$15 per 1M

Learn how to auto-route in our model routing guide.

Deployment Architecture

For production, never expose your API key in client-side code. Always proxy through your own backend:

# Your backend (Node.js/Express example)
app.post('/api/chat', async (req, res) => {
    const response = await fetch('https://ai.dr-ai.top/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${process.env.DRAI_API_KEY}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(req.body)
    });
    
    // Forward the streaming response to the client
    response.body.pipe(res);
});

This pattern keeps your API key on the server, lets you add rate limiting and logging, and gives you a place to insert business logic (user authentication, usage tracking, etc.).

Advanced Features to Add Next

Once your basic chatbot is working, these features elevate it to production quality:

Streaming with Typing Indicators

Show a "typing..." indicator while waiting for the first token, then transition to streaming display. This manages user expectations and feels responsive even with slower models.

Function Calling / Tool Use

GPT-5 and Claude support function calling — the model can request to execute predefined functions (search a database, call an API, fetch weather data). This turns your chatbot from a conversational toy into a capable agent. DrAI supports function calling on all compatible models. Learn more in our AI agent development guide.

RAG (Retrieval-Augmented Generation)

Give your chatbot access to your own data by implementing RAG. When a user asks a question, retrieve relevant documents from a vector database and include them in the prompt. This lets the AI answer questions about your specific products, docs, or knowledge base — not just its training data.

Voice Input/Output

Add speech-to-text (Whisper API) for voice input and text-to-speech for voice output. This makes your chatbot accessible hands-free and opens up phone/voice assistant use cases.

Multi-Language Support

GPT-5 and Claude are natively multilingual. Simply let users type in their preferred language — the model handles translation automatically. For specialized Chinese-language needs, consider routing to Qwen or DeepSeek as described in our model routing guide.

Conclusion

Adding an AI chatbot to your application is genuinely a 10-minute task in 2026. The DrAI API is OpenAI-compatible, so any tutorial, library, or framework built for OpenAI works out of the box. Start with the simple examples above, add streaming and error handling, then scale up with model routing and conversation management as your needs grow.

Ready to build? Get your free API key and check our pricing to estimate costs. For more advanced patterns, explore our AI agent development guide and multi-model workflow articles.

📚 Related Reading

AI API Streaming in Python: SSE, AsyncIO, and Real-Time UIsPython AI streaming guide: OpenAI SDK SSE iteration, raw event-stream parsing, AsyncIO... AI API Error Handling Guide: Retry Logic, Timeouts, and Fal…Production AI API error handling: retry with exponential backoff, circuit breakers, model... GPT-5 Function Calling Guide: Build AI Agents That Use ToolsMaster GPT-5 function calling with this complete guide. Learn structured outputs, tool... AI Workflow Automation Guide: Chain LLMs with No-Code and C…Complete AI workflow automation guide: chain LLMs, build automated AI pipelines with...
🌐 English