Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>AI Code Generator</title>
- <script src="https://cdn.tailwindcss.com"></script>
- <style>
- /* Custom scrollbar for the codebox */
- .codebox::-webkit-scrollbar {
- width: 8px;
- }
- .codebox::-webkit-scrollbar-track {
- background: #1e1e1e;
- border-radius: 10px;
- }
- .codebox::-webkit-scrollbar-thumb {
- background: #00bfa6;
- border-radius: 10px;
- }
- .codebox::-webkit-scrollbar-thumb:hover {
- background: #009e8e;
- }
- </style>
- </head>
- <body class="flex h-screen bg-gray-900 text-gray-100 font-sans">
- <div class="sidebar w-64 bg-gray-800 p-6 border-r border-gray-700 flex flex-col">
- <h2 class="text-xl font-bold mb-4 text-teal-400">💻 Code Refinery</h2>
- <p class="text-sm mb-4 text-gray-400">5-Step AI Code Enhancement</p> <p class="text-sm mb-2 font-semibold">Models used:</p>
- <ul class="list-disc list-inside text-sm text-gray-400 space-y-1">
- <li>AI 5</li>
- <li>AI 4</li>
- <li>AI 3</li>
- <li>AI 2</li>
- <li>AI 1</li>
- </ul>
- </div>
- <div class="main flex-1 flex flex-col p-8">
- <div class="chatbox flex flex-col gap-4 h-full">
- <textarea
- id="prompt"
- rows="5"
- placeholder="Describe what you want coded..."
- class="w-full p-4 bg-gray-800 border border-gray-700 text-white rounded-lg resize-none focus:outline-none focus:border-teal-500"
- ></textarea>
- <button
- onclick="startPipeline()"
- class="px-6 py-3 bg-teal-600 text-white font-semibold rounded-lg cursor-pointer hover:bg-teal-700 transition duration-200 ease-in-out shadow-lg"
- >
- 🚀 Generate Code
- </button>
- <div id="status" class="status mt-4 text-sm italic text-gray-500">Status: Waiting for input...</div>
- <div
- id="output"
- class="codebox flex-1 bg-gray-800 p-4 rounded-lg border-l-4 border-teal-500 text-gray-300 font-mono whitespace-pre-wrap overflow-y-auto text-sm"
- style="min-height: 200px;" /* Ensure minimum height */
- >
- Your code will appear here...
- </div>
- <button
- onclick="copyCode()"
- class="px-6 py-3 bg-gray-700 text-white font-semibold rounded-lg cursor-pointer hover:bg-gray-600 transition duration-200 ease-in-out shadow-lg"
- >
- 📋 Copy Final Code
- </button>
- </div>
- </div>
- <script>
- // !!! IMPORTANT: Replace with your actual OpenRouter API Key !!!
- // Be cautious about exposing API keys in client-side code in production.
- const API_KEY = ""; // Your API key added here
- // List of model IDs to use in the pipeline, change these with the ids/names in openrouter
- const MODELS = [
- "thudm/glm-z1-32b:free",
- "google/gemini-2.0-flash-exp:free",
- "moonshotai/kimi-vl-a3b-thinking:free",
- "deepseek/deepseek-chat-v3-0324:free",
- "deepseek/deepseek-r1-zero:free"
- ];
- /**
- * Queries a specific AI model via the OpenRouter API.
- * @param {string} prompt - The prompt to send to the model.
- * @param {string} model - The model name to use.
- * @returns {Promise<string>} - A promise that resolves with the model's response or an error message.
- */
- async function queryModel(prompt, model) {
- const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
- method: "POST",
- headers: {
- "Authorization": `Bearer ${API_KEY}`,
- "Content-Type": "application/json",
- "X-Title": "AI Code Generator App" // Custom header for OpenRouter
- },
- body: JSON.stringify({
- model: model,
- messages: [
- { role: "user", content: prompt }
- ],
- // Optional: Add temperature, max_tokens, etc. here if needed
- temperature: 0.7,
- max_tokens: 65536 // Adjust as needed
- })
- });
- // Check for non-OK HTTP status codes
- if (!res.ok) {
- const errorBody = await res.text(); // Get error response body
- throw new Error(`HTTP error ${res.status} from ${model}: ${errorBody}`);
- }
- const data = await res.json();
- // Check if the response structure is as expected
- if (!data.choices || data.choices.length === 0 || !data.choices[0].message || !data.choices[0].message.content) {
- console.error("Unexpected API response structure:", data);
- return `[${model} returned an unexpected response format.]`;
- }
- return data.choices[0].message.content;
- }
- /**
- * Starts the code generation pipeline, querying models sequentially.
- */
- async function startPipeline() {
- const userPrompt = document.getElementById("prompt").value.trim();
- const outputBox = document.getElementById("output");
- const statusBox = document.getElementById("status");
- if (!userPrompt) {
- alert("Please enter a prompt first!");
- return;
- }
- if (API_KEY === "YOUR_OPENROUTER_API_KEY") {
- statusBox.textContent = "Error: Please replace 'YOUR_OPENROUTER_API_KEY' with your actual API key.";
- alert("Please replace 'YOUR_OPENROUTER_API_KEY' with your actual API key.");
- return;
- }
- let code = ""; // Variable to hold the evolving code
- outputBox.textContent = "Starting AI pipeline..."; // Initial status
- for (let i = 0; i < MODELS.length; i++) {
- const currentModel = MODELS[i];
- statusBox.textContent = `Step ${i + 1}/${MODELS.length}: Querying ${currentModel}...`;
- outputBox.textContent = `Waiting for ${currentModel} response...`; // Clear previous output while waiting
- try {
- // For the first model, use the user's prompt.
- // For subsequent models, use the previous model's output as the prompt for improvement/debugging.
- const prompt = i === 0
- ? userPrompt
- : `Review and improve/debug the following code. Provide the complete, corrected code and say NOTHING else except the code:\n\n\`\`\`\n${code}\n\`\`\``; // Added markdown formatting for clarity
- const modelResponse = await queryModel(prompt, currentModel);
- // Update the code variable with the latest response
- code = modelResponse;
- statusBox.textContent = `Step ${i + 1}/${MODELS.length}: ${currentModel} responded.`;
- outputBox.textContent = code; // Display the current model's output
- } catch (err) {
- // If any model fails, log the error and stop the pipeline
- console.error(`Error during pipeline step ${i + 1} with ${currentModel}:`, err);
- statusBox.textContent = `Step ${i + 1}/${MODELS.length}: ${currentModel} failed. Error: ${err.message}`;
- outputBox.textContent = `An error occurred during the pipeline. See status for details.\n\nLast received code (if any):\n${code}\n\nError: ${err.message}`;
- break; // Stop the pipeline on error
- }
- // Add a small delay between model calls to avoid hitting rate limits too quickly
- if (i < MODELS.length - 1) {
- statusBox.textContent += " Waiting before next step...";
- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for 2 seconds
- }
- }
- // Final status update
- if (statusBox.textContent.includes("failed")) {
- statusBox.textContent = "Pipeline finished with errors.";
- } else {
- statusBox.textContent = "✅ Pipeline complete. Final code generated.";
- }
- }
- /**
- * Copies the content of the output box to the clipboard.
- */
- function copyCode() {
- const output = document.getElementById("output").textContent;
- if (!output || output === "Your code will appear here..." || output.includes("An error occurred")) {
- alert("Nothing to copy yet or an error occurred.");
- return;
- }
- navigator.clipboard.writeText(output).then(() => {
- // Use a simple message box instead of alert as per instructions
- statusBox.textContent = "Code copied to clipboard!";
- setTimeout(() => {
- // Restore previous status after a short delay
- if (!statusBox.textContent.includes("Pipeline complete")) {
- statusBox.textContent = "✅ Pipeline complete. Final code generated.";
- }
- }, 3000); // Message disappears after 3 seconds
- }).catch(err => {
- console.error("Failed to copy code:", err);
- statusBox.textContent = "Failed to copy code.";
- });
- }
- // Get status box element globally for easier access in copyCode
- const statusBox = document.getElementById("status");
- </script>
- </body>
- </html>
Advertisement
Comments
-
- for a simple tutorial on how to use/change the ai models, from line 78 to line 86 lets you add your openrouter api key and change the model names via ai model Id names, if you actually use money for AI and your a loser, add your paid model IDs there.
- for temp(temperature changes creativity of the models responses, 0.1 - 0 is recommended but its 0.7 by default) control go to line 109 also somewhere near line 109 lets you change the tokens.
- this lets you stack ai models for coding, allowing you to add more and more parameters so you can multi-ai till you get for example 10 trillion parameters
Add Comment
Please, Sign In to add comment
Advertisement