AI Development

Creating Robots with ChatGPT API

A complete guide to building intelligent conversational robots using OpenAI's ChatGPT API, from basic setup to advanced integration techniques.

AI Engineer
January 12, 2024
12 min read

Getting Started

Building AI-powered robots with ChatGPT API opens up endless possibilities for automation, customer service, and interactive applications. This guide will walk you through the entire process.

Prerequisites

  • OpenAI API key (get from platform.openai.com)
  • Python 3.8+ installed
  • Basic knowledge of Python and APIs
  • Telegram Bot Token (for Telegram integration)

Initial Setup

Setup Commands
# Install required packages
pip install openai python-telegram-bot

# Set up your environment
export OPENAI_API_KEY="your-api-key-here"
export TELEGRAM_BOT_TOKEN="your-bot-token-here"

Basic Bot Implementation

Here's a simple Telegram bot that integrates with ChatGPT API:

basic_bot.py
import openai
import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters

# Initialize OpenAI client
openai.api_key = "your-api-key"

async def start(update: Update, context):
    await update.message.reply_text(
        "🤖 Hello! I'm your AI assistant. How can I help you today?"
    )

async def handle_message(update: Update, context):
    user_message = update.message.text
    
    try:
        # Get response from ChatGPT
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": user_message}
            ]
        )
        
        ai_response = response.choices[0].message.content
        await update.message.reply_text(ai_response)
        
    except Exception as e:
        await update.message.reply_text("Sorry, I encountered an error. Please try again.")

async def main():
    app = Application.builder().token("your-bot-token").build()
    
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    
    await app.run_polling()

if __name__ == "__main__":
    asyncio.run(main())

Advanced Features

Take your bot to the next level with conversation history, multiple modes, and interactive buttons:

advanced_bot.py
import openai
import json
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters

class AdvancedAIBot:
    def __init__(self, openai_key: str, bot_token: str):
        self.openai_client = openai.OpenAI(api_key=openai_key)
        self.bot_token = bot_token
        self.conversation_history = {}
        
    async def start(self, update: Update, context):
        keyboard = [
            [InlineKeyboardButton("📚 Learn", callback_data="learn")],
            [InlineKeyboardButton("🎮 Play", callback_data="play")],
            [InlineKeyboardButton("💼 Work", callback_data="work")]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        
        await update.message.reply_text(
            "🤖 Welcome to Advanced AI Bot! Choose your mode:",
            reply_markup=reply_markup
        )
    
    async def handle_callback(self, update: Update, context):
        query = update.callback_query
        await query.answer()
        
        user_id = query.from_user.id
        mode = query.data
        
        # Set conversation context based on mode
        contexts = {
            "learn": "You are an educational assistant. Provide clear, engaging explanations.",
            "play": "You are a fun, creative assistant. Be entertaining and playful.",
            "work": "You are a professional assistant. Be concise and business-focused."
        }
        
        self.conversation_history[user_id] = {
            "context": contexts.get(mode, "You are a helpful assistant."),
            "messages": []
        }
        
        await query.edit_message_text(f"Mode set to: {mode.title()} 🎯")
    
    async def process_message(self, update: Update, context):
        user_id = update.message.from_user.id
        user_message = update.message.text
        
        # Initialize conversation if not exists
        if user_id not in self.conversation_history:
            self.conversation_history[user_id] = {
                "context": "You are a helpful assistant.",
                "messages": []
            }
        
        # Add user message to history
        self.conversation_history[user_id]["messages"].append({
            "role": "user",
            "content": user_message
        })
        
        try:
            # Prepare messages for OpenAI
            messages = [
                {"role": "system", "content": self.conversation_history[user_id]["context"]}
            ] + self.conversation_history[user_id]["messages"][-10:]  # Keep last 10 messages
            
            # Get AI response
            response = self.openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=messages,
                max_tokens=500,
                temperature=0.7
            )
            
            ai_response = response.choices[0].message.content
            
            # Add AI response to history
            self.conversation_history[user_id]["messages"].append({
                "role": "assistant",
                "content": ai_response
            })
            
            await update.message.reply_text(ai_response)
            
        except Exception as e:
            await update.message.reply_text(f"Error: {str(e)}")
    
    async def run(self):
        app = Application.builder().token(self.bot_token).build()
        
        app.add_handler(CommandHandler("start", self.start))
        app.add_handler(CallbackQueryHandler(self.handle_callback))
        app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.process_message))
        
        await app.run_polling()

# Usage
if __name__ == "__main__":
    bot = AdvancedAIBot("your-openai-key", "your-bot-token")
    asyncio.run(bot.run())

Best Practices

Follow these best practices to ensure your bot is robust, secure, and efficient:

  • Rate Limiting: Implement proper rate limiting to avoid API quota issues
  • Security: Never expose API keys in client-side code
  • Monitoring: Log conversations and monitor bot performance
  • Testing: Thoroughly test your bot before deployment

Join the Discussion

0 comments