Custom AI Form
-
I want to create an AI Form that can create a book. I use 2 code, that is front end in elementor HTML element and in code snippet (php) for authorize API.
This is the code for in code snippet :function openai_generate_text() { // Get the topic and language from the AJAX request $prompt = $_POST['prompt']; $language = $_POST['language']; // Adjust the prompt based on the selected language if ($language === 'id') { $prompt = "Gunakan Bahasa Indonesia tentang " . $prompt; } else { $prompt = "Use English about " . $prompt; } // OpenAI API URL and key $api_url = 'https://api.openai.com/v1/chat/completions'; $api_key = 'API_KEY'; // Replace with your actual OpenAI API key // Headers for the OpenAI API $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ]; // Body for the OpenAI API $body = [ 'model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => $prompt]], 'temperature' => 0.7 ]; // Args for the WordPress HTTP API $args = [ 'method' => 'POST', 'headers' => $headers, 'body' => json_encode($body), 'timeout' => 120 ]; // Send the request $response = wp_remote_request($api_url, $args); // Handle the response if (is_wp_error($response)) { $error_message = $response->get_error_message(); wp_send_json_error("Something went wrong: $error_message"); } else { $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (json_last_error() !== JSON_ERROR_NONE) { wp_send_json_error('Invalid JSON in API response'); } elseif (!isset($data['choices'])) { wp_send_json_error('API request failed. Response: ' . $body); } else { wp_send_json_success($data); } } // Always die in functions echoing AJAX content wp_die(); } add_action('wp_ajax_openai_generate_text', 'openai_generate_text'); add_action('wp_ajax_nopriv_openai_generate_text', 'openai_generate_text'); function enqueue_custom_scripts() { // Enqueue jsPDF library wp_enqueue_script('jspdf', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js', array(), null, true); // Enqueue docx library wp_enqueue_script('docx', 'https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.27.0/docxtemplater-latest.min.js', array(), null, true); } add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
This is the code in HTML elementor :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Book Generator</title> <link rel="stylesheet" > <link rel="stylesheet" href="styles.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <div class="container" id="main-container"> <h1 class="text-center">AI Book Generator</h1> <form id="input-form" class="my-4"> <div class="form-group"> <label for="book-length">Book Length</label> <input type="text" id="book-length" class="form-control" placeholder="Enter book length" required> </div> <div class="form-group"> <label for="gpt-role">Role of GPT-3.5</label> <input type="text" id="gpt-role" class="form-control" placeholder="Enter role of GPT-3.5 (a name of an author you like or a profession GPT should simulate)" required> </div> <div class="form-group"> <label for="genre">Genre</label> <input type="text" id="genre" class="form-control" placeholder="Enter genre (Science-Fiction, Science Book, Advisory Book, Mystery, ...)" value="" required> </div> <div class="form-group"> <label for="keywords">Keywords</label> <input type="text" id="keywords" class="form-control" placeholder="Enter keywords (e.g. Math, Science, Computer Science, Philosophy, ...)" required> </div> <div class="form-group"> <input type="checkbox" id="auto-gen"> <label for="auto-gen">Auto Generate Chapters</label> </div> <button type="button" id="conceptButton" class="btn btn-primary">Generate Concept</button> <button type="button" id="contentButton" class="btn btn-primary">Generate Table of Contents</button> <button type="button" id="chaptersButton" class="btn btn-primary">Generate Chapters</button> </form> <div class="form-group"> <label for="concept">Book Concept</label> <textarea id="concept" class="form-control"></textarea> </div> <div class="form-group"> <label for="contents">Table of Contents</label> <textarea id="contents" class="form-control"></textarea> </div> <div class="form-group"> <label for="chapters">Chapters</label> <div id="chapters" class="border p-2"></div> </div> <button type="button" id="exportButton" class="btn btn-primary">Export to TXT</button> </div> <script> // Define DOM elements const conceptInput = document.getElementById('concept'); const conceptButton = document.getElementById('conceptButton'); const contentsInput = document.getElementById('contents'); const contentButton = document.getElementById('contentButton'); const chaptersDiv = document.getElementById('chapters'); const chaptersButton = document.getElementById('chaptersButton'); const autoGenCheckbox = document.getElementById('auto-gen'); // Define global variables let tableOfContents = []; let currentLine = 0; // Generate content using WordPress AJAX async function generateContent(role, prompt) { const formData = new FormData(); formData.append('action', 'openai_generate_text'); formData.append('prompt', prompt); formData.append('language', 'id'); // Add the language parameter if needed const response = await fetch('/wp-admin/admin-ajax.php', { method: 'POST', body: formData }); const data = await response.json(); return data.data.choices[0].message.content; } // Disable inputs and buttons function disableInputsAndButtons(inputs, buttons) { inputs.forEach(input => input.disabled = true); buttons.forEach(button => button.disabled = true); } // Get input values function getInputValues() { const gptRole = document.getElementById('gpt-role').value; const bookLength = document.getElementById('book-length').value; const genre = document.getElementById('genre').value; const keywords = document.getElementById('keywords').value.split(','); return { gptRole, bookLength, genre, keywords }; } // Event listeners for buttons // conceptButton generates a concept conceptButton.addEventListener('click', async () => { const { gptRole, bookLength, genre, keywords } = getInputValues(); const prompt =
Generate a ${bookLength}-word ${genre} concept with keywords: ${keywords.join(', ')}.
; const concept = await generateContent(gptRole, prompt); conceptInput.value = concept; }); // contentButton generates a table of contents contentButton.addEventListener('click', async () => { const { gptRole, genre, keywords } = getInputValues(); disableInputsAndButtons([conceptInput], [conceptButton]); const concept = conceptInput.value; const prompt =Based on the ${genre} concept: "${concept}" with keywords: ${keywords.join(', ')}, generate a table of contents. The table of contents should be only a list of chapters, no introductory or concluding text, no formatting, no empty lines, just a list of chapter names with a short description.
; const contents = await generateContent(gptRole, prompt); contentsInput.value = contents; }); // chaptersButton generates chapters // if auto-gen is checked, it will generate chapters until the end of the table of contents chaptersButton.addEventListener('click', async () => { const { gptRole, genre, keywords } = getInputValues(); disableInputsAndButtons([conceptInput, contentsInput], [conceptButton, contentButton]); tableOfContents = contentsInput.value.split('\n').filter(line => line.trim() !== ''); if (currentLine < tableOfContents.length) { const prompt =Based on the ${genre} chapter title: "${tableOfContents[currentLine]}" with keywords: ${keywords.join(', ')}, generate the chapter content.
; let chapter = await generateContent(gptRole, prompt); // Replace newlines with <br> tags chapter = chapter.replace(/\n/g, '<br/>\n'); chaptersDiv.innerHTML +=<h2>${tableOfContents[currentLine]}</h2><p>${chapter}</p>
; currentLine++; if (autoGenCheckbox.checked) { chaptersButton.click(); } } }); // exportButton exports the chapters to a text file document.getElementById('exportButton').addEventListener('click', () => { const element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(chaptersDiv.innerHTML)); element.setAttribute('download', 'chapters.txt'); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); }); </script> </body>It’s worked.
But, today I want to use openAI in Azure. So I should change, but stuck in authorize.
Please help me to change the code so I can use credit in Azure OpenAI. Maybe it can use AI Power plugin server side API?
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Custom AI Form’ is closed to new replies.