RahulSinghPundir/SQL_Wizard
0
1{2 "cells": [3 {4 "cell_type": "code",5 "execution_count": null,6 "metadata": {},7 "outputs": [],8 "source": [9 "<!DOCTYPE html>\n",10 "<html lang=\"en\">\n",11 "<head>\n",12 " <meta charset=\"UTF-8\">\n",13 " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",14 " <title>Draggable Database Interface</title>\n",15 " <link rel=\"stylesheet\" href=\"https://code.jquery.com/ui/1.13.3/themes/base/jquery-ui.css\">\n",16 " <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css\">\n",17 " <style>\n",18 " body {\n",19 " font-family: Arial, sans-serif;\n",20 " margin: 0;\n",21 " padding: 0;\n",22 " overflow: hidden;\n",23 " }\n",24 " .container {\n",25 " position: absolute;\n",26 " top: 0;\n",27 " left: 0;\n",28 " width: 100vw;\n",29 " height: 100vh;\n",30 " background: #f4f4f4;\n",31 " overflow: auto;\n",32 " padding: 20px;\n",33 " box-sizing: border-box;\n",34 " }\n",35 " .table-box {\n",36 " width: 300px;\n",37 " max-height: 400px;\n",38 " padding: 10px;\n",39 " background: #fff;\n",40 " border: 1px solid #ccc;\n",41 " border-radius: 5px;\n",42 " box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);\n",43 " position: absolute;\n",44 " overflow: hidden;\n",45 " display: flex;\n",46 " flex-direction: column;\n",47 " }\n",48 " .table-box h2 {\n",49 " margin: 0;\n",50 " font-size: 18px;\n",51 " background: #f4f4f4;\n",52 " padding: 5px;\n",53 " border-radius: 5px;\n",54 " cursor: move;\n",55 " display: flex;\n",56 " justify-content: space-between;\n",57 " align-items: center;\n",58 " }\n",59 " .table-box h2 .delete-table-btn {\n",60 " color: red;\n",61 " cursor: pointer;\n",62 " margin-left: 10px;\n",63 " }\n",64 " .table-container {\n",65 " flex: 1;\n",66 " max-height: 300px;\n",67 " overflow-y: auto;\n",68 " margin-top: 10px;\n",69 " }\n",70 " .table-box table {\n",71 " width: 100%;\n",72 " border-collapse: collapse;\n",73 " }\n",74 " .table-box th, .table-box td {\n",75 " padding: 5px;\n",76 " text-align: left;\n",77 " border: 1px solid #ddd;\n",78 " }\n",79 " .delete-column-btn {\n",80 " color: red;\n",81 " cursor: pointer;\n",82 " margin-left: 5px;\n",83 " }\n",84 " .add-table-btn {\n",85 " margin: 10px;\n",86 " padding: 10px;\n",87 " background: #333;\n",88 " color: #fff;\n",89 " text-decoration: none;\n",90 " border-radius: 5px;\n",91 " cursor: pointer;\n",92 " }\n",93 " .add-table-btn:hover {\n",94 " background: #555;\n",95 " }\n",96 " .line {\n",97 " position: absolute;\n",98 " background: #000;\n",99 " }\n",100 " .toggle-btn {\n",101 " cursor: pointer;\n",102 " font-size: 18px;\n",103 " }\n",104 " .add-column-btn {\n",105 " margin: 10px;\n",106 " padding: 5px;\n",107 " background: #28a745;\n",108 " color: #fff;\n",109 " text-decoration: none;\n",110 " border-radius: 5px;\n",111 " cursor: pointer;\n",112 " display: block;\n",113 " text-align: center;\n",114 " }\n",115 " .add-column-btn:hover {\n",116 " background: #218838;\n",117 " }\n",118 " .fa {\n",119 " font-size: 14px;\n",120 " }\n",121 " .edit-joins-btn {\n",122 " margin: 10px;\n",123 " padding: 5px;\n",124 " background: #007bff;\n",125 " color: #fff;\n",126 " text-decoration: none;\n",127 " border-radius: 5px;\n",128 " cursor: pointer;\n",129 " display: block;\n",130 " text-align: center;\n",131 " }\n",132 " .edit-joins-btn:hover {\n",133 " background: #0056b3;\n",134 " }\n",135 " .dialog {\n",136 " display: none;\n",137 " position: fixed;\n",138 " top: 50%;\n",139 " left: 50%;\n",140 " transform: translate(-50%, -50%);\n",141 " background: #fff;\n",142 " border: 1px solid #ccc;\n",143 " border-radius: 5px;\n",144 " padding: 20px;\n",145 " box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);\n",146 " z-index: 1000;\n",147 " }\n",148 " .dialog h3 {\n",149 " margin: 0;\n",150 " font-size: 18px;\n",151 " }\n",152 " .dialog input, .dialog textarea {\n",153 " width: 100%;\n",154 " padding: 10px;\n",155 " margin: 5px 0;\n",156 " border: 1px solid #ccc;\n",157 " border-radius: 5px;\n",158 " }\n",159 " .dialog button {\n",160 " margin-top: 10px;\n",161 " padding: 10px;\n",162 " background: #007bff;\n",163 " color: #fff;\n",164 " border: none;\n",165 " border-radius: 5px;\n",166 " cursor: pointer;\n",167 " }\n",168 " .dialog button:hover {\n",169 " background: #0056b3;\n",170 " }\n",171 " </style>\n",172 " <script src=\"https://code.jquery.com/jquery-3.7.1.js\"></script>\n",173 " <script src=\"https://code.jquery.com/ui/1.13.3/jquery-ui.js\"></script>\n",174 " <script src=\"https://cdn.jsdelivr.net/npm/leader-line\"></script>\n",175 "</head>\n",176 "<body>\n",177 " <div class=\"container\" id=\"container\">\n",178 " <a class=\"add-table-btn\" id=\"add-table-btn\">Add Table</a>\n",179 " \n",180 " </div>\n",181 " <script>\n",182 " let tableCount = 0;\n",183 " const container = document.getElementById('container');\n",184 " const lines = [];\n",185 " let joinsData = {};\n",186 " let currentJoin = null;\n",187 "\n",188 " $(function() {\n",189 " // Load JSON files\n",190 " Promise.all([\n",191 " fetch('static/database_details.json').then(response => response.json()),\n",192 " fetch('static/database_joins.json').then(response => response.json())\n",193 " ])\n",194 " .then(([tableData, loadedJoinsData]) => {\n",195 " joinsData = loadedJoinsData;\n",196 " tableData.Tables.forEach(table => addTable(table));\n",197 " // Ensure tables are added before drawing lines\n",198 " setTimeout(() => {\n",199 " drawLines();\n",200 " }, 500); // Adjust timeout as needed\n",201 " })\n",202 " .catch(error => console.error('Error loading JSON data:', error));\n",203 "\n",204 " $('#add-table-btn').on('click', function() {\n",205 " addTable();\n",206 " });\n",207 "\n",208 " $('#container').on('scroll', updateLines);\n",209 "\n",210 " \n",211 " });\n",212 "\n",213 " function addTable(tableData) {\n",214 " const tableName = tableData ? tableData.name : 'Table ' + (tableCount + 1);\n",215 "\n",216 " // Check if the table already exists\n",217 " if (document.getElementById(tableName)) {\n",218 " console.warn(`Table ${tableName} already exists!`);\n",219 " return;\n",220 " }\n",221 "\n",222 " tableCount++;\n",223 " const tableBox = document.createElement('div');\n",224 " tableBox.className = 'table-box ui-draggable ui-resizable';\n",225 " tableBox.id = tableName;\n",226 "\n",227 " // Add random position\n",228 " tableBox.style.top = (Math.random() * (window.innerHeight - 400)) + 'px';\n",229 " tableBox.style.left = (Math.random() * (window.innerWidth - 300)) + 'px';\n",230 "\n",231 " const primaryKeyColumn = tableData ? tableData.columns.find(col => col.constraints && col.constraints.includes(\"PRIMARY KEY\")) : null;\n",232 "\n",233 " tableBox.innerHTML = `\n",234 " <h2>\n",235 " <span class=\"table-name\" contenteditable=\"false\">${tableName}</span>\n",236 " <span class=\"toggle-btn\">▼</span>\n",237 " <span class=\"delete-table-btn\"><i class=\"fa fa-trash\"></i></span>\n",238 " <span class=\"edit-joins-btn\">Edit Joins</span>\n",239 " </h2>\n",240 " <div class=\"table-container\">\n",241 " <table>\n",242 " <thead>\n",243 " <tr>\n",244 " <th>Column Name</th>\n",245 " ${primaryKeyColumn ? '<th>Primary Key</th>' : ''}\n",246 " <th>Action</th>\n",247 " </tr>\n",248 " </thead>\n",249 " <tbody id=\"table-${tableName}-columns\">\n",250 " ${tableData ? tableData.columns.map(column => `\n",251 " <tr>\n",252 " <td>${column.name}</td>\n",253 " ${primaryKeyColumn ? (primaryKeyColumn.name === column.name ? '<td>✔</td>' : '') : ''}\n",254 " <td><span class=\"delete-column-btn\"><i class=\"fa fa-trash\"></i></span></td>\n",255 " </tr>\n",256 " `).join('') : ''}\n",257 " </tbody>\n",258 " </table>\n",259 " <a class=\"add-column-btn\" data-table=\"${tableName}\">Add Column</a>\n",260 " </div>\n",261 " `;\n",262 "\n",263 " container.appendChild(tableBox);\n",264 "\n",265 " $(tableBox).draggable({\n",266 " containment: 'parent'\n",267 " }).resizable({\n",268 " containment: 'parent'\n",269 " });\n",270 "\n",271 " // Add event listeners\n",272 " $(tableBox).find('.delete-table-btn').on('click', function() {\n",273 " $(tableBox).remove();\n",274 " removeLinesForTable(tableName);\n",275 " });\n",276 "\n",277 " $(tableBox).find('.add-column-btn').on('click', function() {\n",278 " const tableName = $(this).data('table');\n",279 " const columnName = prompt('Enter new column name:');\n",280 " if (columnName) {\n",281 " addColumnToTable(tableName, columnName);\n",282 " }\n",283 " });\n",284 "\n",285 " $(tableBox).find('.delete-column-btn').on('click', function() {\n",286 " $(this).closest('tr').remove();\n",287 " });\n",288 "\n",289 " $(tableBox).find('.edit-joins-btn').on('click', function() {\n",290 " openEditJoinsDialog(tableName);\n",291 " });\n",292 "\n",293 " // Add a toggle feature to hide/show columns\n",294 " $(tableBox).find('.toggle-btn').on('click', function() {\n",295 " $(tableBox).find('.table-container').toggle();\n",296 " const isExpanded = $(tableBox).find('.table-container').is(':visible');\n",297 " $(this).html(isExpanded ? '▼' : '▶');\n",298 " });\n",299 " }\n",300 "\n",301 " function addColumnToTable(tableName, columnName) {\n",302 " const table = document.getElementById(tableName);\n",303 " if (table) {\n",304 " const columnTableBody = document.getElementById(`table-${tableName}-columns`);\n",305 " const newRow = document.createElement('tr');\n",306 " newRow.innerHTML = `\n",307 " <td>${columnName}</td>\n",308 " <td><span class=\"delete-column-btn\"><i class=\"fa fa-trash\"></i></span></td>\n",309 " `;\n",310 " columnTableBody.appendChild(newRow);\n",311 "\n",312 " $(newRow).find('.delete-column-btn').on('click', function() {\n",313 " $(this).closest('tr').remove();\n",314 " });\n",315 " }\n",316 " }\n",317 "\n",318 " function openEditJoinsDialog(tableName) {\n",319 " // Find existing joins for this table\n",320 " const tableJoins = joinsData.Joins.filter(join => join.models.includes(tableName));\n",321 "\n",322 " if (tableJoins.length > 0) {\n",323 " // For simplicity, edit the first join related to this table\n",324 " currentJoin = tableJoins[0];\n",325 " $('#join-name').val(currentJoin.name);\n",326 " $('#join-type').val(currentJoin.joinType);\n",327 " $('#join-condition').val(currentJoin.condition);\n",328 " $('#edit-joins-dialog').show();\n",329 " } else {\n",330 " alert('No joins found for this table.');\n",331 " }\n",332 " }\n",333 "\n",334 " function drawLines() {\n",335 " removeLines();\n",336 " joinsData.Joins.forEach(join => {\n",337 " const [sourceTable, targetTable] = join.models;\n",338 " const sourceElem = document.getElementById(sourceTable);\n",339 " const targetElem = document.getElementById(targetTable);\n",340 " if (sourceElem && targetElem) {\n",341 " const sourcePos = getPosition(sourceElem);\n",342 " const targetPos = getPosition(targetElem);\n",343 " const line = new LeaderLine(\n",344 " LeaderLine.pointAnchor(sourceElem.querySelector('h2')),\n",345 " LeaderLine.pointAnchor(targetElem.querySelector('h2')),\n",346 " {\n",347 " color: '#000',\n",348 " size: 3,\n",349 " path: 'smooth'\n",350 " }\n",351 " );\n",352 " lines.push(line);\n",353 " }\n",354 " });\n",355 " }\n",356 "\n",357 " function removeLines() {\n",358 " lines.forEach(line => line.remove());\n",359 " lines.length = 0;\n",360 " }\n",361 "\n",362 " function removeLinesForTable(tableName) {\n",363 " lines.forEach(line => {\n",364 " if (line._points[0].element.id === tableName || line._points[1].element.id === tableName) {\n",365 " line.remove();\n",366 " }\n",367 " });\n",368 " }\n",369 "\n",370 " function updateLines() {\n",371 " removeLines();\n",372 " drawLines();\n",373 " }\n",374 "\n",375 " function getPosition(elem) {\n",376 " const rect = elem.getBoundingClientRect();\n",377 " return {\n",378 " x: rect.left + window.scrollX + rect.width / 2,\n",379 " y: rect.top + window.scrollY + rect.height / 2\n",380 " };\n",381 " }\n",382 " </script>\n",383 "</body>\n",384 "</html>\n"385 ]386 },387 {388 "cell_type": "code",389 "execution_count": null,390 "metadata": {},391 "outputs": [],392 "source": [393 "from langchain.chains import LLMChain\n",394 "from langchain.prompts import PromptTemplate, FewShotPromptTemplate\n",395 "from langchain_community.utilities.sql_database import SQLDatabase\n",396 "from langchain_experimental.sql import SQLDatabaseChain\n",397 "from langchain.chains.sql_database.prompt import PROMPT_SUFFIX\n",398 "from examples import get_example_selector\n",399 "from langgraph.graph import StateGraph, END\n",400 "from typing import TypedDict, Optional\n",401 "from get_tables import FunctionalTools\n",402 "from get_llm import get_llm_sql\n",403 "from get_memory import get_memory\n",404 "from config_variables import DB_USER, DB_PASSWORD, DB_HOST, DB_NAME\n",405 "\n",406 "memory = get_memory()\n",407 "llm = get_llm_sql()"408 ]409 },410 {411 "cell_type": "code",412 "execution_count": null,413 "metadata": {},414 "outputs": [],415 "source": [416 "user_query=\"no of work which are currently active.\"\n",417 "\n",418 "table_recommendation_prompt = PromptTemplate(\n",419 " input_variables=[\"prompts\",\"memory\",\"user_query\"],\n",420 " template=\"\"\"\n",421 " You are an assistant that recommends relevant database tables for SQL queries.\n",422 "\n",423 " Return the names of ALL the SQL tables only from given table descriptions and no need to assume any table that MIGHT be relevant to the user question. \\\n",424 " The tables are:\n",425 " {prompts} and\n",426 " History: {memory}\n",427 "\n",428 " User input: {user_query}\n",429 "\n",430 " Answer only with table names in comma-separated format.\n",431 " \"\"\"\n",432 " )\n",433 "\n",434 "recommendation_chain = LLMChain(llm=llm, prompt=table_recommendation_prompt, output_key=\"table_list\")\n",435 "recommendations = recommendation_chain.run(prompts=prompts,memory=memory,user_query=user_query)"436 ]437 },438 {439 "cell_type": "code",440 "execution_count": null,441 "metadata": {},442 "outputs": [],443 "source": [444 "prompts"445 ]446 },447 {448 "cell_type": "code",449 "execution_count": null,450 "metadata": {},451 "outputs": [],452 "source": [453 "recommendations"454 ]455 },456 {457 "cell_type": "code",458 "execution_count": null,459 "metadata": {},460 "outputs": [],461 "source": [462 "recommended_tables = [name.strip() for name in recommendations.split(',')]\n",463 "recommended_tables"464 ]465 },466 {467 "cell_type": "code",468 "execution_count": null,469 "metadata": {},470 "outputs": [],471 "source": [472 "import json\n",473 "from sentence_transformers import SentenceTransformer\n",474 "\n",475 "# Load the JSON file (assumed to be not excessively large for simplicity)\n",476 "\n",477 "l=[\"work_exp_temps\",\"work_dashboards\"]\n",478 "\n",479 "\n",480 "# Assuming you have a function to send the prompt to Gemini API\n",481 "# send_to_gemini_api(prompt)\n"482 ]483 },484 {485 "cell_type": "code",486 "execution_count": null,487 "metadata": {},488 "outputs": [],489 "source": [490 "file=json.load(open(\"config.json\"))\n",491 "print(file)"492 ]493 },494 {495 "cell_type": "code",496 "execution_count": null,497 "metadata": {},498 "outputs": [],499 "source": [500 "document.addEventListener('DOMContentLoaded', () => {\n",501 " const sendButton = document.getElementById('send-button');\n",502 " const userInput = document.getElementById('user-input');\n",503 " const chatContainer = document.getElementById('chat-container');\n",504 " const summaryButton = document.getElementById('summary-button');\n",505 " const summaryModal = document.getElementById('summary-modal');\n",506 " const closeButton = document.querySelector('.close-button');\n",507 " const summaryText = document.getElementById('summary-text');\n",508 " const updateFilesButton = document.getElementById('update-files-button');\n",509 " const fileNameInput = document.getElementById('file-name');\n",510 " const fileContentInput = document.getElementById('file-content');\n",511 " const newChatButton = document.getElementById('new-chat-button');\n",512 " const chatList = document.getElementById('chat-list');\n",513 "\n",514 " sendButton.addEventListener('click', () => {\n",515 " const userInputValue = userInput.value;\n",516 " if (userInputValue.trim()) {\n",517 " fetch('/chat', {\n",518 " method: 'POST',\n",519 " headers: {\n",520 " 'Content-Type': 'application/json',\n",521 " },\n",522 " body: JSON.stringify({ user_input: userInputValue })\n",523 " })\n",524 " .then(response => response.json())\n",525 " .then(message => {\n",526 " const userMessage = document.createElement('div');\n",527 " userMessage.classList.add('chat-message', 'user-message');\n",528 " userMessage.setAttribute(\"data-key\", message.key);\n",529 " userMessage.setAttribute(\"data-chat-id\", message.chat_id);\n",530 " userMessage.innerHTML = `<p class=\"user-input\">${message.user_input}</p>`;\n",531 " chatContainer.appendChild(userMessage);\n",532 "\n",533 " const assistantMessage = document.createElement('div');\n",534 " assistantMessage.classList.add('chat-message', 'assistant-message');\n",535 " assistantMessage.setAttribute(\"data-key\", message.key);\n",536 " assistantMessage.setAttribute(\"data-chat-id\", message.chat_id);\n",537 " assistantMessage.innerHTML = `\n",538 " <p>${message.result.answer}</p>\n",539 " <textarea class=\"sql-query\">${message.result.sql_query}</textarea>\n",540 " <button class=\"save-button\" data-key=\"${message.key}\" data-chat-id=\"${message.chat_id}\">Save</button>\n",541 " <button class=\"run-button\" data-key=\"${message.key}\" data-chat-id=\"${message.chat_id}\">Run Query</button>\n",542 " <div class=\"query-result-container\" style=\"max-height: 200px; overflow-y: auto;\"></div>\n",543 " <button class=\"open-window-button\" data-key=\"${message.key}\" data-chat-id=\"${message.chat_id}\">Open in Separate Window</button>`;\n",544 " chatContainer.appendChild(assistantMessage);\n",545 " \n",546 " userInput.value = '';\n",547 " });\n",548 " }\n",549 " });\n",550 "\n",551 " newChatButton.addEventListener('click', () => {\n",552 " fetch('/new_chat', {\n",553 " method: 'POST',\n",554 " })\n",555 " .then(response => response.json())\n",556 " .then(data => {\n",557 " const newChatItem = document.createElement('li');\n",558 " newChatItem.setAttribute('data-chat-id', data.chat_id);\n",559 " newChatItem.textContent = 'New Chat';\n",560 " chatList.appendChild(newChatItem);\n",561 "\n",562 " newChatItem.addEventListener('click', () => {\n",563 " switchChatSession(data.chat_id);\n",564 " });\n",565 "\n",566 " // Clear the chat container\n",567 " chatContainer.innerHTML = '';\n",568 " });\n",569 " });\n",570 "\n",571 " const switchChatSession = (chat_id) => {\n",572 " fetch('/switch_chat', {\n",573 " method: 'POST',\n",574 " headers: {\n",575 " 'Content-Type': 'application/x-www-form-urlencoded',\n",576 " },\n",577 " body: new URLSearchParams({ chat_id })\n",578 " })\n",579 " .then(response => response.json())\n",580 " .then(data => {\n",581 " chatContainer.innerHTML = '';\n",582 " data.messages.forEach(message => {\n",583 " const userMessage = document.createElement('div');\n",584 " userMessage.classList.add('chat-message', 'user-message');\n",585 " userMessage.setAttribute(\"data-key\", message.key);\n",586 " userMessage.setAttribute(\"data-chat-id\", chat_id);\n",587 " userMessage.innerHTML = `<p>${message.user_input}</p>`;\n",588 " chatContainer.appendChild(userMessage);\n",589 "\n",590 " const assistantMessage = document.createElement('div');\n",591 " assistantMessage.classList.add('chat-message', 'assistant-message');\n",592 " assistantMessage.setAttribute(\"data-key\", message.key);\n",593 " assistantMessage.setAttribute(\"data-chat-id\", chat_id);\n",594 " assistantMessage.innerHTML = `\n",595 " <p>${message.result.answer}</p>\n",596 " <textarea class=\"sql-query\">${message.result.sql_query}</textarea>\n",597 " <button class=\"save-button\" data-key=\"${message.key}\" data-chat-id=\"${chat_id}\">Save</button>\n",598 " <button class=\"run-button\" data-key=\"${message.key}\" data-chat-id=\"${chat_id}\">Run Query</button>\n",599 " <div class=\"query-result-container\" style=\"max-height: 200px; overflow-y: auto;\"></div>\n",600 " <button class=\"open-window-button\" data-key=\"${message.key}\" data-chat-id=\"${chat_id}\">Open in Separate Window</button>`;\n",601 " chatContainer.appendChild(assistantMessage);\n",602 " });\n",603 " });\n",604 " };\n",605 "\n",606 " chatList.addEventListener('click', (event) => {\n",607 " const chatId = event.target.getAttribute('data-chat-id');\n",608 " if (chatId) {\n",609 " switchChatSession(chatId);\n",610 " }\n",611 " });\n",612 "\n",613 " summaryButton.addEventListener('click', () => {\n",614 " fetch('/summary')\n",615 " .then(response => response.json())\n",616 " .then(data => {\n",617 " summaryText.textContent = data.chat_history.join('\\n');\n",618 " summaryModal.style.display = 'block';\n",619 " });\n",620 " });\n",621 "\n",622 " closeButton.addEventListener('click', () => {\n",623 " summaryModal.style.display = 'none';\n",624 " });\n",625 "\n",626 " window.addEventListener('click', (event) => {\n",627 " if (event.target == summaryModal) {\n",628 " summaryModal.style.display = 'none';\n",629 " }\n",630 " });\n",631 "\n",632 " document.addEventListener('click', (event) => {\n",633 " const key = event.target.getAttribute('data-key');\n",634 " const chatId = event.target.getAttribute('data-chat-id');\n",635 " if (!key || !chatId) return; // exit if key or chat_id is null\n",636 "\n",637 " if (event.target.classList.contains('save-button')) {\n",638 " const userQuery = document.querySelector(`.user-message[data-key=\"${key}\"][data-chat-id=\"${chatId}\"] .user-input`).textContent;\n",639 " const sqlQuery = document.querySelector(`.assistant-message[data-key=\"${key}\"][data-chat-id=\"${chatId}\"] .sql-query`).value;\n",640 " fetch('/update_fewshot', {\n",641 " method: 'POST',\n",642 " headers: {\n",643 " 'Content-Type': 'application/x-www-form-urlencoded',\n",644 " },\n",645 " body: new URLSearchParams({ user_query: userQuery, sql_query: sqlQuery })\n",646 " })\n",647 " .then(response => {\n",648 " if (!response.ok) {\n",649 " throw new Error('Network response was not ok');\n",650 " }\n",651 " alert('Query saved successfully');\n",652 " })\n",653 " .catch(error => {\n",654 " console.error('There was a problem with the fetch operation:', error);\n",655 " });\n",656 " }\n",657 "\n",658 " if (event.target.classList.contains('run-button')) {\n",659 " const sqlQuery = document.querySelector(`.assistant-message[data-key=\"${key}\"][data-chat-id=\"${chatId}\"] .sql-query`).value;\n",660 " const queryResultContainer = document.querySelector(`.assistant-message[data-key=\"${key}\"][data-chat-id=\"${chatId}\"] .query-result-container`);\n",661 " fetch('/run_query', {\n",662 " method: 'POST',\n",663 " headers: {\n",664 " 'Content-Type': 'application/x-www-form-urlencoded',\n",665 " },\n",666 " body: new URLSearchParams({ chat_id: chatId, key: key, sql_query: sqlQuery })\n",667 " })\n",668 " .then(response => response.json())\n",669 " .then(result => {\n",670 " queryResultContainer.innerHTML = `<pre>${JSON.stringify(result, null, 2)}</pre>`;\n",671 " });\n",672 " }\n",673 "\n",674 " if (event.target.classList.contains('open-window-button')) {\n",675 " const sqlQuery = document.querySelector(`.assistant-message[data-key=\"${key}\"][data-chat-id=\"${chatId}\"] .sql-query`).value;\n",676 " window.open(`/run_query_window?chat_id=${encodeURIComponent(chatId)}&key=${encodeURIComponent(key)}&sql_query=${encodeURIComponent(sqlQuery)}`);\n",677 " }\n",678 " });\n",679 "\n",680 " updateFilesButton.addEventListener('click', () => {\n",681 " const fileName = fileNameInput.value;\n",682 " fetch(`/get_file_content/${fileName}`)\n",683 " .then(response => response.text())\n",684 " .then(content => {\n",685 " fileContentInput.value = content;\n",686 " updateFilesModal.style.display = 'block';\n",687 " });\n",688 " });\n",689 "\n",690 " document.querySelector('#save-file-button').addEventListener('click', () => {\n",691 " const fileName = fileNameInput.value;\n",692 " const fileContent = fileContentInput.value;\n",693 " fetch('/save_file', {\n",694 " method: 'POST',\n",695 " headers: {\n",696 " 'Content-Type': 'application/x-www-form-urlencoded',\n",697 " },\n",698 " body: new URLSearchParams({ file_name: fileName, file_content: fileContent })\n",699 " })\n",700 " .then(response => {\n",701 " if (!response.ok) {\n",702 " throw new Error('Network response was not ok');\n",703 " }\n",704 " alert('File saved successfully');\n",705 " updateFilesModal.style.display = 'none';\n",706 " })\n",707 " .catch(error => {\n",708 " console.error('There was a problem with the fetch operation:', error);\n",709 " });\n",710 " });\n",711 "\n",712 " const updateFilesModal = document.getElementById('update-files-modal');\n",713 " const closeButtonUpdateFiles = document.querySelector('.close-button');\n",714 " closeButtonUpdateFiles.addEventListener('click', () => {\n",715 " updateFilesModal.style.display = 'none';\n",716 " });\n",717 "\n",718 " window.addEventListener('click', (event) => {\n",719 " if (event.target == updateFilesModal) {\n",720 " updateFilesModal.style.display = 'none';\n",721 " }\n",722 " });\n",723 "});\n",724 "\n",725 "\n",726 "\n",727 "\n",728 "\n"729 ]730 }731 ],732 "metadata": {733 "kernelspec": {734 "display_name": "myenv",735 "language": "python",736 "name": "python3"737 },738 "language_info": {739 "codemirror_mode": {740 "name": "ipython",741 "version": 3742 },743 "file_extension": ".py",744 "mimetype": "text/x-python",745 "name": "python",746 "nbconvert_exporter": "python",747 "pygments_lexer": "ipython3",748 "version": "3.9.12"749 }750 },751 "nbformat": 4,752 "nbformat_minor": 2753}754 