Skip to main content
The AI tab provides intelligent, conversational explanations using OpenAI’s GPT models. It offers two main features: simplified explanations and an interactive Q&A chat interface.
The AI tab requires an OpenAI API key. Users must add their own API key in the extension settings to use this feature.

How It Works

1

API Key Check

When the AI tab is opened, the extension checks if an OpenAI API key exists in local storage.
2

Context Building

The extension builds context from the Wikipedia summary (if cached) and surrounding page text where the term was found.
3

AI Request

User clicks “Explain Simply” or types a question. The extension sends the request to OpenAI’s Chat Completions API.
4

Display Response

The AI’s response appears in the chat interface. Users can ask up to 5 follow-up questions per session.

API Used

The AI tab uses OpenAI’s Chat Completions API:
// From background.js:251-305
async function callOpenAI(messages, language, maxTokens = 500) {
  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-5-nano',
      messages: messages,
      max_completion_tokens: maxTokens,
      reasoning_effort: 'minimal'
    })
  });
  
  return data.choices[0].message.content;
}
The extension uses the gpt-5-nano model with minimal reasoning effort to optimize for speed and cost.

Features

1. Explain Simply

One-click button that generates a plain-language explanation:
// From content.js:1187-1248
async function handleExplainSimply() {
  const systemPrompt = buildSystemPrompt('explain');
  const userMessage = currentLanguage === 'ar'
    ? `اشرح "${cleanedTerm}" بلغة بسيطة وسهلة الفهم.`
    : `Explain "${cleanedTerm}" in simple, easy-to-understand language.`;

  const response = await chrome.runtime.sendMessage({
    action: 'callOpenAI',
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userMessage }
    ],
    language: currentLanguage
  });
}
System Prompt for Explanations:
// From content.js:916
systemContent = `You are a helpful assistant that explains topics in simple, plain language. Respond in ${lang}. Keep your explanation to 2-3 short sentences that anyone can understand. Avoid jargon.`;

2. Interactive Q&A Chat

Users can ask up to 5 questions about the topic:
// From content.js:1251-1332
async function handleAIQuestion() {
  // Add user message to conversation
  aiConversation.push({ role: 'user', content: question });
  
  // Build messages for API
  const messages = [{ role: 'system', content: systemPrompt }];
  
  // Add conversation history
  for (const msg of aiConversation) {
    if (msg.role === 'user' || msg.role === 'assistant') {
      messages.push({ role: msg.role, content: msg.content });
    }
  }
  
  // Send to OpenAI
  const response = await chrome.runtime.sendMessage({
    action: 'callOpenAI',
    messages: messages,
    language: currentLanguage
  });
  
  aiConversation.push({ role: 'assistant', content: response.data });
  aiExchangeCount++;
}
System Prompt for Chat:
// From content.js:918-919
systemContent = `You are a helpful assistant that answers questions about topics. Respond in ${lang}. Keep answers concise (2-4 sentences). Be accurate and helpful.`;

Context Enhancement

The AI receives contextual information to improve answer quality:

1. Wikipedia Summary

// From content.js:922-924
if (summaryText) {
  systemContent += `\n\nWikipedia summary for "${cleanedTerm}":\n${summaryText}`;
}

2. Page Context

Captures ~500 characters of surrounding text from where the term was found:
// From content.js:846-873
function capturePageContext() {
  const range = selection.getRangeAt(0);
  const container = range.commonAncestorContainer;
  const parentEl = container.nodeType === Node.TEXT_NODE 
    ? container.parentElement 
    : container;

  // Get text from the closest meaningful block
  const block = parentEl.closest('p, div, article, section, td, li') || parentEl;
  let text = (block.textContent || '').trim();

  // Limit to ~500 chars centered around the selection
  if (text.length > 500) {
    const selText = selection.toString().trim();
    const idx = text.indexOf(selText);
    if (idx !== -1) {
      const start = Math.max(0, idx - 200);
      const end = Math.min(text.length, idx + selText.length + 200);
      text = text.substring(start, end);
    }
  }
  
  return text;
}
// From content.js:926-928
if (pageContext) {
  systemContent += `\n\nContext from the page where the user found this term:\n${pageContext}`;
}
Providing Wikipedia summaries and page context helps the AI give more accurate, relevant answers.

User Interface

Chat Display

Messages are displayed in color-coded bubbles:
// From content.js:1175-1181
function createChatMessage(role, content) {
  const msg = document.createElement('div');
  msg.className = 'wiki-ai-message ' + 
    (role === 'user' ? 'user' : 
     role === 'system' ? 'system' : 
     'ai');
  msg.textContent = content;
  return msg;
}
  • User messages: Displayed in one style
  • AI responses: Displayed in another style
  • System messages: Used for errors or special notifications

Typing Indicator

Shown while waiting for AI response:
// From content.js:875-903
function createTypingIndicator() {
  const typing = document.createElement('div');
  typing.className = 'wiki-ai-typing';
  for (let i = 0; i < 3; i++) {
    const dot = document.createElement('span');
    dot.className = 'wiki-ai-typing-dot';
    typing.appendChild(dot);
  }
  return typing;
}

Exchange Limit

Displays remaining questions counter:
// From content.js:989-994
const limitText = document.createElement('div');
limitText.textContent = currentLanguage === 'ar'
  ? `${MAX_AI_EXCHANGES - aiExchangeCount} أسئلة متبقية`
  : `${MAX_AI_EXCHANGES - aiExchangeCount} questions remaining`;
The 5-question limit (defined as MAX_AI_EXCHANGES = 5 in content.js:23) prevents excessive API usage and costs.

API Key Management

No Key State

When no API key is configured, displays:
// From content.js:1001-1027
function renderAINoKey(contentArea) {
  const text = document.createElement('p');
  text.textContent = currentLanguage === 'ar'
    ? 'أضف مفتاح OpenAI API في إعدادات الإضافة لاستخدام ميزات الذكاء الاصطناعي.'
    : 'Add your OpenAI API key in the extension settings to use AI features.';

  const hint = document.createElement('div');
  hint.textContent = currentLanguage === 'ar'
    ? 'انقر على أيقونة الإضافة → أدخل مفتاح API'
    : 'Click the extension icon → Enter your API key';
}

Key Storage

// From background.js:6-12
chrome.runtime.onInstalled.addListener(async () => {
  // Migrate from sync to local storage for security
  const sync = await chrome.storage.sync.get(['openaiKey']);
  if (sync.openaiKey) {
    await chrome.storage.local.set({ openaiKey: sync.openaiKey });
    await chrome.storage.sync.remove('openaiKey');
  }
});
API keys are stored in local storage (not sync storage) for security. Users must enter their key on each device.

Error Handling

The AI tab handles specific OpenAI API errors:
// From content.js:1334-1364
function handleAIError(errorMsg, chatArea) {
  if (errorMsg === 'NO_API_KEY') {
    displayMsg = 'No API key set. Add one in extension settings.';
  } else if (errorMsg === 'INVALID_API_KEY') {
    displayMsg = 'Invalid API key. Please check your key in settings.';
  } else if (errorMsg === 'RATE_LIMITED') {
    displayMsg = 'Too many requests. Please wait a moment.';
  } else if (errorMsg === 'INSUFFICIENT_QUOTA') {
    displayMsg = 'Insufficient OpenAI quota. Please check your account.';
  }
}
// From background.js:274-296
if (!response.ok) {
  const status = response.status;
  
  if (status === 401) {
    throw new Error('INVALID_API_KEY');
  } else if (status === 429) {
    throw new Error('RATE_LIMITED');
  } else if (status === 402) {
    throw new Error('INSUFFICIENT_QUOTA');
  } else if (status === 400) {
    throw new Error(`INVALID_REQUEST: ${errorDetail}`);
  }
}
The OpenAI API key is incorrect or revoked. User needs to update the key in extension settings.
Too many requests sent to OpenAI API. User should wait before trying again.
The OpenAI account has exhausted its API credits or quota. User needs to add credits to their OpenAI account.
The request format was incorrect. This usually indicates a bug in the extension.

Language Support

The AI responds in the detected language:
  • English: Default for Latin text
  • Arabic: Automatic for Arabic text
  • All system prompts and messages specify the target language
// From content.js:907
const lang = currentLanguage === 'ar' ? 'Arabic' : 'English';

Session Management

// From content.js:20-23
let aiConversation = [];
let aiExchangeCount = 0;
const MAX_AI_EXCHANGES = 5;
Each time the Knowledge button is clicked:
  • aiConversation is reset to an empty array
  • aiExchangeCount is reset to 0
  • Page context is captured fresh
This ensures each tooltip session is independent.

Cost Considerations

Users pay for their own OpenAI API usage. The extension uses conservative settings to minimize costs:
  • max_completion_tokens: 500 limits response length
  • reasoning_effort: 'minimal' for faster, cheaper responses
  • 5 question limit per session prevents excessive usage

Data Source

OpenAI Chat Completions API: Requires API key (paid)

Build docs developers (and LLMs) love