לדלג לתוכן

משתמש:מוטי בוט/AI.js

מתוך המכלול, האנציקלופדיה היהודית

לתשומת ליבך: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
/**
 * MediaWiki AI Chat Gadget using OpenAI
 * @author Your Name
 * @version 1.1.0
 */

// Load required MediaWiki modules
mw.loader.using(['jquery', 'mediawiki.api']).then(function () {
    // Start chat initialization
    initializeAIChat();
}).catch(function (error) {
    console.error('Error initializing chat:', error);
});

// Configuration
const AI_CHAT_CONFIG = {
    apiKey: 'YOUR_OPENAI_API_KEY',
    model: 'gpt-3.5-turbo',
    maxTokens: 300,
    temperature: 0.7,
    systemPrompt: `You are a digital assistant for "HaMichlol" (The Collection) wiki, designed to help new users. Your role is to:

1. Help with policies and procedures based on Wikipedia principles
2. Guide users in creating and editing pages on HaMichlol
3. Explain how to use wikitext markup and the visual editor
4. Assist with appropriate encyclopedic writing style
5. Direct users to reliable sources and emphasize the importance of citations
6. Explain copyright issues and categories
7. Help solve basic technical problems

Always respond in Hebrew with clear and practical answers, providing concrete examples when appropriate. 
Refer to relevant guides on HaMichlol when needed, and base your guidance on Wikipedia policies as a general framework.`
};

// Create chat interface
function createChatInterface() {
    const chatContainer = document.createElement('div');
    chatContainer.id = 'ai-chat-container';
    chatContainer.className = 'ai-chat-widget';

    const chatHeader = document.createElement('div');
    chatHeader.className = 'ai-chat-header';
    chatHeader.textContent = 'עוזר המכלול';

    const chatMessages = document.createElement('div');
    chatMessages.className = 'ai-chat-messages';

    const chatInput = document.createElement('div');
    chatInput.className = 'ai-chat-input';
    chatInput.innerHTML = `
        <input type="text" id="ai-chat-message" placeholder="שאל אותי על המכלול...">
        <button id="ai-chat-send">שלח</button>
    `;

    chatContainer.appendChild(chatHeader);
    chatContainer.appendChild(chatMessages);
    chatContainer.appendChild(chatInput);

    return chatContainer;
}

// Initialize AI chat interface
function initializeAIChat() {
    // בדיקת הגדרות API
    if (!AI_CHAT_CONFIG.apiKey || AI_CHAT_CONFIG.apiKey === 'YOUR_OPENAI_API_KEY') {
        console.error('OpenAI API key is not configured!');
        return;
    }

    const chat = createChatInterface();
    document.body.appendChild(chat);

    // אתחול היסטוריית צ'אט
    chatHistory = [];

    // הוספת מאזיני אירועים
    const sendButton = document.getElementById('ai-chat-send');
    const messageInput = document.getElementById('ai-chat-message');

    sendButton.addEventListener('click', async () => {
        sendButton.disabled = true;
        await sendMessage();
        sendButton.disabled = false;
    });

    messageInput.addEventListener('keypress', async function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendButton.disabled = true;
            await sendMessage();
            sendButton.disabled = false;
        }
    });

    // הוספת הודעת פתיחה
    addMessageToChat('system', 'שלום! אני כאן לעזור לכם עם המכלול - עריכה, כתיבה, חיפוש מקורות ועוד. במה אתם צריכים עזרה?');
}

// Chat history to maintain context
let chatHistory = [];

// Send message to OpenAI API
async function sendMessage() {
    const messageInput = document.getElementById('ai-chat-message');
    const message = messageInput.value.trim();
    
    if (!message) return;

    // Add user message to chat and history
    addMessageToChat('user', message);
    messageInput.value = '';
    chatHistory.push({ role: 'user', content: message });

    try {
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${AI_CHAT_CONFIG.apiKey}`
            },
            body: JSON.stringify({
                model: AI_CHAT_CONFIG.model,
                messages: [
                    { role: 'system', content: AI_CHAT_CONFIG.systemPrompt },
                    ...chatHistory.slice(-5) // Keep last 5 messages for context
                ],
                max_tokens: AI_CHAT_CONFIG.maxTokens,
                temperature: AI_CHAT_CONFIG.temperature
            })
        });

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

        const data = await response.json();
        const aiResponse = data.choices[0].message.content.trim();
        
        // Add AI response to chat and history
        addMessageToChat('ai', aiResponse);
        chatHistory.push({ role: 'assistant', content: aiResponse });

        // Limit history size
        if (chatHistory.length > 10) {
            chatHistory = chatHistory.slice(-10);
        }
    } catch (error) {
        console.error('Error:', error);
        addMessageToChat('system', 'סליחה, אירעה שגיאה בעיבוד הבקשה שלך.');
    }
}

// Add message to chat interface
function addMessageToChat(sender, message) {
    const messagesContainer = document.querySelector('.ai-chat-messages');
    const messageElement = document.createElement('div');
    messageElement.className = `ai-chat-message ${sender}-message`;
    messageElement.textContent = message;
    messagesContainer.appendChild(messageElement);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}