UNPKG

insight-aid

Version:

Insight-aid: lightweight floating help + AI chatbot plugin

292 lines (220 loc) β€’ 9.85 kB
# InsightAid Plugin Suite **InsightAid** is a lightweight, pluggable JavaScript suite for enhancing user experience with: * πŸ•‹οΈ Inline contextual help (`insightAid`) * πŸ€– AI-powered chatbot (`insightAidBot`) This plugin works with **any server-side language** (PHP, Node.js, Python, etc.) and supports **any UI framework** (Bootstrap, Tailwind, plain HTML). --- ## 🌐 Overview ### βœ… `InsightAid` * Displays floating help icons next to targeted DOM elements. * Supports inline editing of help text when in `"dev"` mode. * In `"prod"` mode, shows help content as read-only. * Automatically captures metadata such as labels, titles, placeholders, and URL paths. * Communicates with your backend to save and retrieve contextual help text. ### βœ… `InsightAidBot` * Minimal, floating AI chatbot embedded in your UI. * Accepts user questions and responds using InsightAid’s saved help data. * Works with any AI service (OpenAI, Gemini, Claude, etc.) to generate contextual answers based on `insightAid` data. --- ## πŸ“† Installation Add the following to your HTML file: ```html <!-- InsightAid Styles --> <link rel="stylesheet" href="/path-to/insight-aid/insight-aid.css" /> <link rel="stylesheet" href="/path-to/insight-aid/insight-aid-bot.css" /> <!-- InsightAid Scripts --> <script src="/path-to/insight-aid/insight-aid.js"></script> <script src="/path-to/insight-aid/insight-aid-bot.js"></script> ``` Ensure icons (`insight-logo.png`, `bot-logo.png`) are placed in the same `/insight-aid/` folder. --- ## 🧠 Initialization: `insightAid` ```javascript insightAid({ apiBase: "/your-backend/helpagent", // Backend API endpoint iconUrl: "/insight-aid/insight-logo.png", // Help icon path role: "dev", // "dev" (editable), "prod" (read-only) selectors: ["form", ".card", ".modal-content"], // Target elements appId: "your-app-id" // Unique app identifier }); ``` --- ## πŸ’¬ Initialization: `insightAidBot` ```javascript insightAidBot({ apiUrl: "/your-backend/insight_aid_bot", // Backend endpoint for chatbot responses iconUrl: "/insight-aid/bot-logo.png" // (Optional) Chatbot icon }); ``` --- ## πŸ“‘ Backend Format FOR Insight-Aid ## πŸ“ƒ Database Schema (SQL) This is an example schema. You can use SQL (MySQL, PostgreSQL, SQLite) or NoSQL (MongoDB, Firestore, etc.). ⚠️ **Important:** Column names in your database **must match exactly** with the ones defined in the schema (`insight_aid_id`, `insight_aid_text`, `insight_aid_metadata`, etc.). > Changing column names may break the plugin's functionality. ### βœ… SQL Table Example ```sql CREATE TABLE insight_aid ( id INT AUTO_INCREMENT PRIMARY KEY, app_id VARCHAR(100) NOT NULL, insight_aid_id VARCHAR(255) NOT NULL, insight_aid_text TEXT NOT NULL, insight_aid_metadata TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); ``` ### πŸ“Œ Column Reference | Column Name | Type | Description | | ---------------------- | ------------ | ------------------------------------ | | `id` | INT | Primary key (auto-increment) | | `app_id` | VARCHAR(100) | Unique app identifier | | `insight_aid_id` | VARCHAR(255) | Unique ID (base64 of appId + DOM ID) | | `insight_aid_text` | TEXT | Help text content (HTML allowed) | | `insight_aid_metadata` | TEXT | JSON string with metadata | | `updated_at` | TIMESTAMP | (Optional) Auto-updated on edit | --- ### βœ… `POST DATA INTO DB` ```json { "app_id": "your-app-id", "insight_aid_id": "base64-id", "insight_aid_text": "Updated help text", "insight_aid_metadata": "{\"extractedText\":\"...\",\"urlPath\":\"...\"}" } ``` #### βœ… `GET DATA FROM DB` ```json [ { "id": "7", "app_id": "APP-ID", "insight_aid_id": "ZGFzaGJvYXJkLXYxLU1vbmV5IFRyYW5zZmVyCgoKClNo", "insight_aid_text": "YOUR-TEXT-HERE", "insight_aid_metadata": "YOUR-METADATA-HERE", "updated_at": "2023-07-26 19:49:39" }, ] ``` ### Example in PHP (Codeigniter) $method = $this->input->method(true); $app_id = $this->input->get_post("appId"); if ($method === "GET") { // Fetch help data for app $query = $this->db->get_where("insight_aid", ["app_id" => $app_id]); echo json_encode($query->result()); } elseif ($method === "POST") { $data = json_decode(file_get_contents("php://input"), true); if (!$data || !isset($data["insight_aid_id"])) { http_response_code(400); echo json_encode(["error" => "Invalid input"]); return; } // Upsert logic $insert_data = [ "app_id" => $data["app_id"], "insight_aid_id" => $data["insight_aid_id"], "insight_aid_text" => $data["insight_aid_text"], "insight_aid_metadata" => $data["metadata"] ]; $exists = $this->db->get_where("insight_aid", [ "app_id" => $data["app_id"], "insight_aid_id" => $data["insight_aid_id"] ])->row(); if ($exists) { $this->db->where("id", $exists->id)->update("insight_aid", $insert_data); } else { $this->db->insert("insight_aid", $insert_data); } echo json_encode(["status" => "saved"]); } else { http_response_code(405); echo json_encode(["error" => "Method not allowed"]); } --- ## πŸ“‘ Backend Format FOR Insight-Aid-Bot The database format is the same as used by insightAid. The chatbot works like a search engine β€” it generates answers based solely on the provided data and does not store user queries or responses in the database. Your backend can call any LLM API (e.g., OpenAI, Gemini) to generate this answer. #### βœ… `Payload` ```json { "question": "How do I create a report?" } ``` **Expected response:** ```json { "answer": "To create a report, navigate to Reports > New Report and follow the prompts." } ``` #### βœ… `Example in PHP(codeigniter) using google-gemini` $input = json_decode(file_get_contents('php://input'), true); $question = $input['question'] ?? ''; if (!$question) { echo json_encode(["answer" => "No question provided."]); return; } // Get help data from DB $helpData = $this->db->get("insight_aid")->result(); // returns stdClass[] $helpDataArray = json_decode(json_encode($helpData), true); // convert to array $origin = $_SERVER['HTTP_ORIGIN'] ?? " "; // Build prompt $prompt = <<<EOT You are a smart and friendly assistant inside a web app. Help users based on the following page information. === Help Agent Info (from database) === {HELP_DATA} === domain === $origin === Instructions for Links === - If including a link, wrap the full URL in an HTML <a> tag like: <a target="_blank" href="https://example.com">Click here</a>. Do not show the raw URL text. - Always prepend $origin to relative paths from the data before creating links. === User Question === $question Instructions: - If the user just says hi, hello, etc., reply politely and ask how you can help. - If the question matches a insight_aid_text or extractedText, explain what the user should do in plain terms. - If the user asks how to do something (like "add new customer"), explain in simple terms what action to take and don't give extra info. - If user ask add new customer then provide link if available and only short info. - Only mention the URL if it helps the user. - Do NOT say β€œbased on data” or refer to database info β€” respond naturally. - If there's no helpful answer, say: "Info not available. Please check with the admin." - Keep replies short, clear, and non-technical. - Use extracted metadata or context to be accurate. - Don’t answer any question if it’s not in the provided data. EOT; $prompt = str_replace("{HELP_DATA}", json_encode($helpDataArray, JSON_PRETTY_PRINT), $prompt); // Gemini API info $apiKey = "API_KEY"; // replace with your real key $apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$apiKey"; $postData = [ "contents" => [ [ "role" => "user", "parts" => [ ["text" => $prompt] ] ] ] ]; $ch = curl_init($apiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); $response = curl_exec($ch); curl_close($ch); $res = json_decode($response, true); if (isset($res['candidates'][0]['content']['parts'][0]['text'])) { echo json_encode(["answer" => $res['candidates'][0]['content']['parts'][0]['text']]); } else { echo json_encode(["answer" => "Something went wrong!"]); } --- ## πŸ’ͺ Backend Compatibility You can implement the backend in **any language**: * βœ… PHP (CodeIgniter, Laravel, etc.) * βœ… Node.js (Express, Fastify) * βœ… Python (Flask, Django, FastAPI) * βœ… Go, Ruby, .NET, Java, etc. ---