// Debug version of ChatGPT Prompt Enhancer
console.log('ChatGPT Prompt Enhancer: Debug script loaded');
class DebugPromptEnhancer {
constructor() {
console.log('DebugPromptEnhancer: Constructor called');
this.enhanceButton = null;
this.isEnhancing = false;
this.apiKey = null;
this.enhancementLevel = 'medium';
this.systemPrompts = null;
this.init();
}
init() {
console.log('DebugPromptEnhancer: Init called');
this.loadSystemPrompts();
this.loadSettings();
this.waitForChatGPT();
}
async loadSystemPrompts() {
console.log('DebugPromptEnhancer: Loading system prompts');
try {
const response = await fetch(chrome.runtime.getURL('system-prompts.js'));
const text = await response.text();
// Create a temporary script to execute the system prompts
const script = document.createElement('script');
script.textContent = text;
document.head.appendChild(script);
// Wait a moment for the script to execute
await new Promise(resolve => setTimeout(resolve, 100));
if (typeof SYSTEM_PROMPTS !== 'undefined') {
this.systemPrompts = SYSTEM_PROMPTS;
console.log('DebugPromptEnhancer: System prompts loaded successfully');
} else {
console.log('DebugPromptEnhancer: Using fallback system prompt');
}
} catch (error) {
console.log('DebugPromptEnhancer: Failed to load system prompts, using fallback');
}
}
async loadSettings() {
console.log('DebugPromptEnhancer: Loading settings');
return new Promise((resolve) => {
chrome.storage.sync.get(['enabled', 'perplexityApiKey', 'enhancementLevel'], (result) => {
console.log('DebugPromptEnhancer: Settings loaded:', result);
this.enabled = result.enabled !== undefined ? result.enabled : true;
this.apiKey = result.perplexityApiKey || null;
this.enhancementLevel = result.enhancementLevel || 'medium';
console.log('DebugPromptEnhancer: Enabled:', this.enabled);
console.log('DebugPromptEnhancer: API Key exists:', !!this.apiKey);
console.log('DebugPromptEnhancer: Enhancement Level:', this.enhancementLevel);
resolve();
});
});
}
waitForChatGPT() {
console.log('DebugPromptEnhancer: Waiting for ChatGPT elements');
const checkInterval = setInterval(() => {
const textarea = this.findTextarea();
console.log('DebugPromptEnhancer: Looking for textarea, found:', !!textarea);
if (textarea) {
console.log('DebugPromptEnhancer: Textarea found, setting up enhancement');
clearInterval(checkInterval);
this.setupEnhancement();
}
}, 1000);
}
findTextarea() {
const selectors = [
'#prompt-textarea',
'textarea[data-id="root"]',
'textarea[placeholder*="Message"]',
'textarea'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
console.log('DebugPromptEnhancer: Found textarea with selector:', selector);
console.log('DebugPromptEnhancer: Textarea element:', element);
// Check if it's a contenteditable div
if (element.getAttribute('contenteditable') === 'true') {
console.log('DebugPromptEnhancer: Found contenteditable div');
return element;
} else {
console.log('DebugPromptEnhancer: Textarea value:', element.value);
return element;
}
}
}
console.log('DebugPromptEnhancer: No textarea found with any selector');
return null;
}
getTextareaValue(element) {
if (element.getAttribute('contenteditable') === 'true') {
// For contenteditable divs, get text from inner elements
const textContent = element.textContent || element.innerText || '';
console.log('DebugPromptEnhancer: Contenteditable text content:', textContent);
return textContent;
} else {
// For regular textareas
return element.value || '';
}
}
setTextareaValue(element, value) {
if (element.getAttribute('contenteditable') === 'true') {
// For contenteditable divs, set innerHTML
element.innerHTML = `<p>${value}</p>`;
console.log('DebugPromptEnhancer: Set contenteditable value:', value);
} else {
// For regular textareas
element.value = value;
}
}
findSendButton() {
const selectors = [
'button[data-testid="send-button"]',
'button[aria-label*="Send"]',
'button svg[data-icon="paper-plane"]',
'button[data-testid="send-button"]',
'button[aria-label="Send message"]'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
console.log('DebugPromptEnhancer: Found send button with selector:', selector);
return element.closest('button') || element;
}
}
console.log('DebugPromptEnhancer: No send button found with any selector');
return null;
}
setupEnhancement() {
console.log('DebugPromptEnhancer: Setting up enhancement');
if (!this.enabled) {
console.log('DebugPromptEnhancer: Extension is disabled');
return;
}
const textarea = this.findTextarea();
const sendButton = this.findSendButton();
console.log('DebugPromptEnhancer: Textarea found:', !!textarea);
console.log('DebugPromptEnhancer: Send button found:', !!sendButton);
if (!textarea || !sendButton) {
console.log('DebugPromptEnhancer: Missing required elements, retrying...');
setTimeout(() => this.setupEnhancement(), 2000);
return;
}
console.log('DebugPromptEnhancer: Creating enhance button');
this.createEnhanceButton(sendButton);
this.addEventListeners(textarea);
}
createEnhanceButton(sendButton) {
console.log('DebugPromptEnhancer: Creating enhance button');
// Remove existing enhance button if any
const existingButton = document.querySelector('.prompt-enhance-btn');
if (existingButton) {
console.log('DebugPromptEnhancer: Removing existing enhance button');
existingButton.remove();
}
// Create new enhance button
this.enhanceButton = document.createElement('button');
this.enhanceButton.className = 'prompt-enhance-btn';
this.enhanceButton.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
</svg>
`;
this.enhanceButton.title = 'Enhance Prompt with AI';
console.log('DebugPromptEnhancer: Inserting enhance button before send button');
sendButton.parentNode.insertBefore(this.enhanceButton, sendButton);
console.log('DebugPromptEnhancer: Enhance button created and inserted');
}
addEventListeners(textarea) {
console.log('DebugPromptEnhancer: Adding event listeners');
this.enhanceButton.addEventListener('click', (e) => {
console.log('DebugPromptEnhancer: Enhance button clicked');
e.preventDefault();
e.stopPropagation();
this.enhancePrompt(textarea);
});
}
async enhancePrompt(textarea) {
console.log('DebugPromptEnhancer: Enhancing prompt');
console.log('DebugPromptEnhancer: Textarea passed to enhancePrompt:', textarea);
if (this.isEnhancing) return;
// Re-find the textarea to make sure we have the current one
const currentTextarea = this.findTextarea();
if (!currentTextarea) {
console.error('DebugPromptEnhancer: Could not find textarea');
this.showNotification('Could not find textarea', 'error');
return;
}
console.log('DebugPromptEnhancer: Current textarea:', currentTextarea);
const originalPrompt = this.getTextareaValue(currentTextarea).trim();
console.log('DebugPromptEnhancer: Original prompt:', originalPrompt);
if (!originalPrompt) {
this.showNotification('Please enter a prompt first', 'error');
return;
}
this.isEnhancing = true;
this.enhanceButton.classList.add('enhancing');
try {
let enhancedPrompt;
if (this.apiKey) {
console.log('DebugPromptEnhancer: Using Perplexity API');
enhancedPrompt = await this.enhanceWithPerplexity(originalPrompt);
} else {
console.log('DebugPromptEnhancer: Using local enhancement');
enhancedPrompt = await this.enhanceLocally(originalPrompt);
this.showNotification('Using local enhancement (no API key)', 'info');
}
if (enhancedPrompt) {
console.log('DebugPromptEnhancer: Enhanced prompt:', enhancedPrompt);
this.setTextareaValue(currentTextarea, enhancedPrompt);
currentTextarea.focus();
this.showNotification('Prompt enhanced successfully!', 'success');
currentTextarea.dispatchEvent(new Event('input', { bubbles: true }));
}
} catch (error) {
console.error('DebugPromptEnhancer: Enhancement failed:', error);
this.showNotification('Failed to enhance prompt. Please try again.', 'error');
} finally {
this.isEnhancing = false;
this.enhanceButton.classList.remove('enhancing');
}
}
async enhanceWithPerplexity(prompt) {
console.log('DebugPromptEnhancer: Calling Perplexity API');
const systemPrompt = this.getSystemPrompt();
console.log('DebugPromptEnhancer: Using system prompt:', systemPrompt);
const response = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: 'sonar',
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: prompt
}
],
max_tokens: 500,
temperature: 0.7,
top_p: 0.9
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`Perplexity API request failed: ${response.status} - ${errorData.error?.message || 'Unknown error'}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
getSystemPrompt() {
if (this.systemPrompts && this.systemPrompts[this.enhancementLevel]) {
console.log('DebugPromptEnhancer: Using system prompt for level:', this.enhancementLevel);
return this.systemPrompts[this.enhancementLevel];
}
// Fallback system prompt
console.log('DebugPromptEnhancer: Using fallback system prompt');
return `You are a prompt enhancement specialist. Your ONLY job is to improve user prompts for ChatGPT.
CRITICAL RULES:
- NEVER answer the user's question or provide information
- ONLY return an enhanced version of their prompt
- DO NOT add explanations, commentary, or meta-text
- DO NOT start with "Here's an enhanced prompt:" or similar phrases
- Return ONLY the enhanced prompt text
ENHANCEMENT TECHNIQUES:
- Add context and background information when missing
- Make vague requests more specific and actionable
- Request well-structured responses with clear sections
- Specify desired tone, length, format, and detail level
- Add requests for examples, data, or specific details when appropriate
- Maintain the original intent and meaning
EXAMPLE:
User: "Write a blog post about AI"
You return: "Please write a comprehensive blog post about artificial intelligence. Include its definition, history, current applications, future potential, and impact on society. Structure the response with clear sections and include specific examples and data where relevant."
User: "Tell me about photosynthesis"
You return: "Please provide a detailed explanation of photosynthesis. Include the process, key components, importance to life on Earth, and its role in the carbon cycle. Structure the response with clear sections and include specific examples."
IMPORTANT: Return ONLY the enhanced prompt, nothing else.`;
}
async enhanceLocally(prompt) {
console.log('DebugPromptEnhancer: Using local enhancement');
await new Promise(resolve => setTimeout(resolve, 1000));
let enhanced = prompt;
// Add context if missing
if (!enhanced.toLowerCase().includes('context') && !enhanced.toLowerCase().includes('background')) {
enhanced = `Please provide context and background information for the following request: ${enhanced}`;
}
// Add specificity
if (enhanced.length < 50) {
enhanced = `${enhanced}. Please provide detailed and specific information.`;
}
// Add structure request
if (!enhanced.toLowerCase().includes('format') && !enhanced.toLowerCase().includes('structure')) {
enhanced = `${enhanced}. Please provide a well-structured response with clear sections.`;
}
return enhanced;
}
showNotification(message, type = 'info') {
console.log('DebugPromptEnhancer: Showing notification:', message, type);
const notification = document.createElement('div');
notification.className = `prompt-enhance-notification ${type}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 3000);
}
}
// Initialize the debug enhancer
console.log('DebugPromptEnhancer: Initializing');
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
console.log('DebugPromptEnhancer: DOM loaded, creating instance');
new DebugPromptEnhancer();
});
} else {
console.log('DebugPromptEnhancer: DOM already loaded, creating instance');
new DebugPromptEnhancer();
}
// Re-initialize on navigation
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
console.log('DebugPromptEnhancer: URL changed, reinitializing');
lastUrl = url;
setTimeout(() => {
new DebugPromptEnhancer();
}, 1000);
}
}).observe(document, { subtree: true, childList: true }); Workflows from the Neura Market marketplace related to this Perplexity resource