عملی سبق

چیٹ انٹرفیس بنائیں

ایک خوبصورت چیٹ بوٹ انٹرفیس بنانا سیکھیں

⏱️15 منٹ
📖Intermediate Level
💬Chat Interface

اس سبق میں آپ سیکھیں گے کہ کیسے ایک مکمل چیٹ انٹرفیس بنایا جائے جہاں آپ AI کے ساتھ بات چیت کر سکتے ہیں۔ یہ ایک advanced سبق ہے جو آپ کو conversation management، UI design، اور real-time updates کا طریقہ سکھائے گا۔

📋 Prerequisites: اس سبق سے پہلے آپ کو lesson-1-setup مکمل کرنا ضروری ہے۔

چیٹ انٹرفیس کی خصوصیات

💬

دو طرفہ گفتگو

صارف اور AI دونوں کی پیغامات دکھائی جاتی ہیں

🎨

خوبصورت UI

Modern design with gradient backgrounds

Real-time Updates

جواب فوری طور پر ظاہر ہوتا ہے

🔄

Conversation History

تمام پیغامات محفوظ رہتے ہیں

⌨️

Keyboard Support

Enter key سے پیغام بھیج سکتے ہیں

📱

Responsive Design

تمام devices پر کام کرتا ہے

🎨UI ڈیزائن

ہمارا چیٹ انٹرفیس تین اہم حصوں پر مشتمل ہے:

1. Header Section

  • Title (چیٹ بوٹ کا نام)
  • API Key input field

2. Messages Area

  • Scrollable container
  • User messages (دائیں طرف، نیلا)
  • Assistant messages (بائیں طرف، سفید)
  • Auto-scroll to bottom

3. Input Area

  • Text input field
  • Send button
  • Enter key support

⚙️JavaScript Logic

1. Message Display Function

function addMessage(text, isUser) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message ' + (isUser ? 'user' : 'assistant');
    messageDiv.textContent = text;
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

یہ function نئی پیغام بناتا ہے اور messages container میں شامل کرتا ہے۔

2. API Call Function

async function sendMessage() {
    // User message add کریں
    addMessage(message, true);
    
    // Loading indicator
    // API call
    // Response add کریں
}

یہ function API کو call کرتا ہے اور response کو display کرتا ہے۔

3. Keyboard Event Listener

userInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

Enter key press پر پیغام بھیجنے کے لیے۔

💻مکمل HTML کوڈ

نیچے دیا گیا کوڈ مکمل چیٹ انٹرفیس ہے۔ اسے کاپی کریں اور اپنی فائل میں پیسٹ کریں۔

Complete Chat Interface
<!DOCTYPE html>
<html lang="ur">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>اردو چیٹ بوٹ</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: system-ui, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px; 
            direction: rtl;
            min-height: 100vh;
        }
        .container { 
            max-width: 800px; 
            margin: 0 auto; 
            background: white; 
            padding: 20px; 
            border-radius: 16px; 
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            height: calc(100vh - 40px);
            display: flex;
            flex-direction: column;
        }
        .header {
            text-align: center;
            padding: 20px;
            border-bottom: 2px solid #f1f5f9;
            margin-bottom: 20px;
        }
        .header h1 {
            color: #1e293b;
            font-size: 24px;
        }
        .api-key-input {
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            margin-bottom: 10px;
            width: 100%;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8fafc;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 15px;
            padding: 12px 16px;
            border-radius: 12px;
            max-width: 80%;
            word-wrap: break-word;
        }
        .message.user {
            background: #6366f1;
            color: white;
            margin-right: auto;
            text-align: right;
        }
        .message.assistant {
            background: white;
            color: #1e293b;
            margin-left: auto;
            border: 1px solid #e2e8f0;
            text-align: right;
        }
        .chat-input-area {
            display: flex;
            gap: 10px;
        }
        .chat-input {
            flex: 1;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 16px;
        }
        .send-button {
            padding: 12px 24px;
            background: #6366f1;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
        }
        .send-button:hover {
            background: #4f46e5;
        }
        .send-button:disabled {
            background: #94a3b8;
            cursor: not-allowed;
        }
        .loading {
            color: #64748b;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 اردو چیٹ بوٹ</h1>
            <input type="password" class="api-key-input" id="apiKey" placeholder="API Key درج کریں (sk-...)">
        </div>
        
        <div class="chat-messages" id="messages">
            <div class="message assistant">
                السلام علیکم! میں آپ کی کیسے مدد کر سکتا ہوں؟
            </div>
        </div>
        
        <div class="chat-input-area">
            <input type="text" class="chat-input" id="userInput" placeholder="اپنا پیغام لکھیں..." />
            <button class="send-button" onclick="sendMessage()">بھیجیں</button>
        </div>
    </div>

    <script>
        const messagesDiv = document.getElementById('messages');
        const userInput = document.getElementById('userInput');
        const apiKeyInput = document.getElementById('apiKey');

        function addMessage(text, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + (isUser ? 'user' : 'assistant');
            messageDiv.textContent = text;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        async function sendMessage() {
            const message = userInput.value.trim();
            const apiKey = apiKeyInput.value.trim();
            
            if (!message) return;
            if (!apiKey) {
                alert('براہ کرم API key درج کریں');
                return;
            }

            // Add user message
            addMessage(message, true);
            userInput.value = '';
            
            // Add loading message
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'message assistant loading';
            loadingDiv.textContent = 'جواب آ رہا ہے...';
            messagesDiv.appendChild(loadingDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;

            try {
                const response = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + apiKey
                    },
                    body: JSON.stringify({
                        model: 'gpt-3.5-turbo',
                        messages: [
                            { role: 'system', content: 'آپ ایک مفید اردو معاون ہیں۔ تمام جوابات اردو میں دیں۔' },
                            { role: 'user', content: message }
                        ]
                    })
                });

                const data = await response.json();
                
                // Remove loading message
                messagesDiv.removeChild(loadingDiv);

                if (data.error) {
                    addMessage('خرابی: ' + data.error.message, false);
                } else {
                    addMessage(data.choices[0].message.content, false);
                }
            } catch (error) {
                messagesDiv.removeChild(loadingDiv);
                addMessage('خرابی: ' + error.message, false);
            }
        }

        // Allow Enter key to send message
        userInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>

💡بہتری کے لیے تجاویز

اضافی فیچرز

  • Conversation history کو localStorage میں save کریں
  • Markdown formatting support شامل کریں
  • Voice input feature شامل کریں
  • Dark mode toggle شامل کریں
  • Message timestamps شامل کریں

🎨UI Enhancements

  • Animations شامل کریں (fade-in effects)
  • Better typography اور spacing
  • Custom scrollbar styling
  • Loading animations