example: embedchain playground (#384)

This commit is contained in:
Sahil Kumar Yadav
2023-08-08 21:13:05 +05:30
committed by GitHub
parent 5e94980aaa
commit ec09a8a6fc
60 changed files with 13340 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
export default function PageWrapper({ children }) {
return (
<>
<div className="flex pt-4 px-4 sm:ml-64 min-h-screen">
<div className="flex-grow pt-4 px-4 rounded-lg">{children}</div>
</div>
</>
);
}

View File

@@ -0,0 +1,16 @@
export default function BotWrapper({ children }) {
return (
<>
<div className="rounded-lg">
<div className="flex flex-row items-center">
<div className="flex items-center justify-center h-10 w-10 rounded-full bg-black text-white flex-shrink-0">
B
</div>
<div className="ml-3 text-sm bg-white py-2 px-4 shadow-lg rounded-xl">
<div>{children}</div>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,16 @@
export default function HumanWrapper({ children }) {
return (
<>
<div className="rounded-lg">
<div className="flex items-center justify-start flex-row-reverse">
<div className="flex items-center justify-center h-10 w-10 rounded-full bg-blue-800 text-white flex-shrink-0">
H
</div>
<div className="mr-3 text-sm bg-blue-200 py-2 px-4 shadow-lg rounded-xl">
<div>{children}</div>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,73 @@
import { useState } from "react";
import { useRouter } from "next/router";
export default function CreateBot() {
const [botName, setBotName] = useState("");
const [status, setStatus] = useState("");
const router = useRouter();
const handleCreateBot = async (e) => {
e.preventDefault();
const data = {
name: botName,
};
const response = await fetch("/api/create_bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (response.ok) {
const botSlug = botName.toLowerCase().replace(/\s+/g, "_");
router.push(`/${botSlug}/app`);
} else {
setBotName("");
setStatus("fail");
setTimeout(() => {
setStatus("");
}, 3000);
}
};
return (
<>
<div className="w-full">
{/* Create Bot */}
<h2 className="text-xl font-bold text-gray-800">CREATE BOT</h2>
<form className="py-2" onSubmit={handleCreateBot}>
<label
htmlFor="bot_name"
className="block mb-2 text-sm font-medium text-gray-900"
>
Name of Bot
</label>
<div className="flex flex-col sm:flex-row gap-x-4 gap-y-4">
<input
type="text"
id="bot_name"
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
placeholder="Eg. Naval Ravikant"
required
value={botName}
onChange={(e) => setBotName(e.target.value)}
/>
<button
type="submit"
className="h-fit text-white bg-black hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center"
>
Submit
</button>
</div>
{status === "fail" && (
<div className="text-red-600 text-sm font-bold py-1">
An error occurred while creating your bot!
</div>
)}
</form>
</div>
</>
);
}

View File

@@ -0,0 +1,71 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
export default function DeleteBot() {
const [bots, setBots] = useState([]);
const router = useRouter();
useEffect(() => {
const fetchBots = async () => {
const response = await fetch("/api/get_bots");
const data = await response.json();
setBots(data);
};
fetchBots();
}, []);
const handleDeleteBot = async (event) => {
event.preventDefault();
const selectedBotSlug = event.target.bot_name.value;
if (selectedBotSlug === "none") {
return;
}
const response = await fetch("/api/delete_bot", {
method: "POST",
body: JSON.stringify({ slug: selectedBotSlug }),
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
router.reload();
}
};
return (
<>
{bots.length !== 0 && (
<div className="w-full">
{/* Delete Bot */}
<h2 className="text-xl font-bold text-gray-800">DELETE BOTS</h2>
<form className="py-2" onSubmit={handleDeleteBot}>
<label className="block mb-2 text-sm font-medium text-gray-900">
List of Bots
</label>
<div className="flex flex-col sm:flex-row gap-x-4 gap-y-4">
<select
name="bot_name"
defaultValue="none"
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
>
<option value="none">Select a Bot</option>
{bots.map((bot) => (
<option key={bot.slug} value={bot.slug}>
{bot.name}
</option>
))}
</select>
<button
type="submit"
className="h-fit text-white bg-red-600 hover:bg-red-600/90 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center"
>
Delete
</button>
</div>
</form>
</div>
)}
</>
);
}

View File

@@ -0,0 +1,47 @@
import { useState } from "react";
export default function PurgeChats() {
const [status, setStatus] = useState("");
const handleChatsPurge = (event) => {
event.preventDefault();
localStorage.clear();
setStatus("success");
setTimeout(() => {
setStatus(false);
}, 3000);
};
return (
<>
<div className="w-full">
{/* Purge Chats */}
<h2 className="text-xl font-bold text-gray-800">PURGE CHATS</h2>
<form className="py-2" onSubmit={handleChatsPurge}>
<label className="block mb-2 text-sm font-medium text-red-600">
Warning
</label>
<div className="flex flex-col sm:flex-row gap-x-4 gap-y-4">
<div
type="text"
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
>
The following action will clear all your chat logs. Proceed with
caution!
</div>
<button
type="submit"
className="h-fit text-white bg-red-600 hover:bg-red-600/80 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center"
>
Purge
</button>
</div>
{status === "success" && (
<div className="text-green-600 text-sm font-bold py-1">
Your chats have been purged!
</div>
)}
</form>
</div>
</>
);
}

View File

@@ -0,0 +1,73 @@
import { useState } from "react";
export default function SetOpenAIKey({ setIsKeyPresent }) {
const [openAIKey, setOpenAIKey] = useState("");
const [status, setStatus] = useState("");
const handleOpenAIKey = async (e) => {
e.preventDefault();
const response = await fetch("/api/set_key", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ openAIKey }),
});
if (response.ok) {
setOpenAIKey("");
setStatus("success");
setIsKeyPresent(true);
} else {
setStatus("fail");
}
setTimeout(() => {
setStatus("");
}, 3000);
};
return (
<>
<div className="w-full">
{/* Set Open AI Key */}
<h2 className="text-xl font-bold text-gray-800">SET OPENAI KEY</h2>
<form className="py-2" onSubmit={handleOpenAIKey}>
<label
htmlFor="openai_key"
className="block mb-2 text-sm font-medium text-gray-900"
>
OpenAI Key
</label>
<div className="flex flex-col sm:flex-row gap-x-4 gap-y-4">
<input
type="password"
id="openai_key"
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
placeholder="Enter Open AI Key here"
required
value={openAIKey}
onChange={(e) => setOpenAIKey(e.target.value)}
/>
<button
type="submit"
className="h-fit text-white bg-black hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center"
>
Submit
</button>
</div>
{status === "success" && (
<div className="text-green-600 text-sm font-bold py-1">
Your Open AI key has been saved successfully!
</div>
)}
{status === "fail" && (
<div className="text-red-600 text-sm font-bold py-1">
An error occurred while saving your OpenAI Key!
</div>
)}
</form>
</div>
</>
);
}

View File

@@ -0,0 +1,156 @@
import { useRouter } from "next/router";
import React, { useState, useEffect } from "react";
import BotWrapper from "@/components/chat/BotWrapper";
import HumanWrapper from "@/components/chat/HumanWrapper";
import SetSources from "@/containers/SetSources";
export default function ChatWindow({ embedding_model, app_type, setBotTitle }) {
const [bot, setBot] = useState(null);
const [chats, setChats] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [selectChat, setSelectChat] = useState(true);
const router = useRouter();
const { bot_slug } = router.query;
useEffect(() => {
if (bot_slug) {
const fetchBots = async () => {
const response = await fetch("/api/get_bots");
const data = await response.json();
const matchingBot = data.find((item) => item.slug === bot_slug);
setBot(matchingBot);
setBotTitle(matchingBot.name);
};
fetchBots();
}
}, [bot_slug]);
useEffect(() => {
const storedChats = localStorage.getItem(`chat_${bot_slug}_${app_type}`);
if (storedChats) {
const parsedChats = JSON.parse(storedChats);
setChats(parsedChats.chats);
}
}, [app_type, bot_slug]);
const handleChatResponse = async (e) => {
e.preventDefault();
setIsLoading(true);
const queryInput = e.target.query.value;
e.target.query.value = "";
const chatEntry = {
sender: "H",
message: queryInput,
};
setChats((prevChats) => [...prevChats, chatEntry]);
const response = await fetch("/api/get_answer", {
method: "POST",
body: JSON.stringify({
query: queryInput,
embedding_model,
app_type,
}),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (response.ok) {
const botResponse = data.response;
const botEntry = {
sender: "B",
message: botResponse,
};
setIsLoading(false);
setChats((prevChats) => [...prevChats, botEntry]);
const savedChats = {
chats: [...chats, chatEntry, botEntry],
};
localStorage.setItem(
`chat_${bot_slug}_${app_type}`,
JSON.stringify(savedChats)
);
} else {
router.reload();
}
};
return (
<>
<div className="flex flex-col justify-between h-full">
<div className="space-y-4 overflow-x-auto h-full pb-8">
{/* Greeting Message */}
<BotWrapper>
Hi, I am {bot?.name}. How can I help you today?
</BotWrapper>
{/* Chat Messages */}
{chats.map((chat, index) => (
<React.Fragment key={index}>
{chat.sender === "B" ? (
<BotWrapper>{chat.message}</BotWrapper>
) : (
<HumanWrapper>{chat.message}</HumanWrapper>
)}
</React.Fragment>
))}
{/* Loader */}
{isLoading && (
<BotWrapper>
<div className="flex items-center justify-center space-x-2 animate-pulse">
<div className="w-2 h-2 bg-black rounded-full"></div>
<div className="w-2 h-2 bg-black rounded-full"></div>
<div className="w-2 h-2 bg-black rounded-full"></div>
</div>
</BotWrapper>
)}
</div>
<div className="bg-white fixed bottom-0 left-0 right-0 h-28 sm:h-16"></div>
{/* Query Form */}
<div className="flex flex-row gap-x-2 sticky bottom-3">
<SetSources
setChats={setChats}
embedding_model={embedding_model}
setSelectChat={setSelectChat}
/>
{selectChat && (
<form
onSubmit={handleChatResponse}
className="w-full flex flex-col sm:flex-row gap-y-2 gap-x-2"
>
<div className="w-full">
<input
id="query"
name="query"
type="text"
placeholder="Enter your query..."
className="text-sm w-full border-2 border-black rounded-xl focus:outline-none focus:border-blue-800 sm:pl-4 h-11"
required
/>
</div>
<div className="w-full sm:w-fit">
<button
type="submit"
id="sender"
disabled={isLoading}
className={`${
isLoading ? "opacity-60" : ""
} w-full bg-black hover:bg-blue-800 rounded-xl text-lg text-white px-6 h-11`}
>
Send
</button>
</div>
</form>
)}
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,160 @@
import { useState } from "react";
import PlusIcon from "../../public/icons/plus.svg";
import CrossIcon from "../../public/icons/cross.svg";
import YoutubeIcon from "../../public/icons/youtube.svg";
import PDFIcon from "../../public/icons/pdf.svg";
import WebIcon from "../../public/icons/web.svg";
import DocIcon from "../../public/icons/doc.svg";
import SitemapIcon from "../../public/icons/sitemap.svg";
import TextIcon from "../../public/icons/text.svg";
export default function SetSources({
setChats,
embedding_model,
setSelectChat,
}) {
const [sourceName, setSourceName] = useState("");
const [sourceValue, setSourceValue] = useState("");
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const dataTypes = {
youtube_video: "YouTube Video",
pdf_file: "PDF File",
web_page: "Web Page",
doc_file: "Doc File",
sitemap: "Sitemap",
text: "Text",
};
const dataIcons = {
youtube_video: <YoutubeIcon className="w-5 h-5 mr-3" />,
pdf_file: <PDFIcon className="w-5 h-5 mr-3" />,
web_page: <WebIcon className="w-5 h-5 mr-3" />,
doc_file: <DocIcon className="w-5 h-5 mr-3" />,
sitemap: <SitemapIcon className="w-5 h-5 mr-3" />,
text: <TextIcon className="w-5 h-5 mr-3" />,
};
const handleDropdownClose = () => {
setIsDropdownOpen(false);
setSourceName("");
setSelectChat(true);
};
const handleDropdownSelect = (dataType) => {
setSourceName(dataType);
setSourceValue("");
setIsDropdownOpen(false);
setSelectChat(false);
};
const handleAddDataSource = async (e) => {
e.preventDefault();
setIsLoading(true);
const addDataSourceEntry = {
sender: "B",
message: `Adding the following ${dataTypes[sourceName]}: ${sourceValue}`,
};
setChats((prevChats) => [...prevChats, addDataSourceEntry]);
let name = sourceName;
let value = sourceValue;
setSourceValue("");
const response = await fetch("/api/add_sources", {
method: "POST",
body: JSON.stringify({
embedding_model,
name,
value,
}),
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
const successEntry = {
sender: "B",
message: `Successfully added ${dataTypes[sourceName]}!`,
};
setChats((prevChats) => [...prevChats, successEntry]);
} else {
const errorEntry = {
sender: "B",
message: `Failed to add ${dataTypes[sourceName]}. Please try again.`,
};
setChats((prevChats) => [...prevChats, errorEntry]);
}
setSourceName("");
setIsLoading(false);
setSelectChat(true);
};
return (
<>
<div className="w-fit">
<button
type="button"
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
className="w-fit p-2.5 rounded-xl text-white bg-black hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300"
>
<PlusIcon className="w-6 h-6" />
</button>
{isDropdownOpen && (
<div className="absolute left-0 bottom-full bg-white border border-gray-300 rounded-lg shadow-lg mb-2">
<ul className="py-1">
<li
className="block px-4 py-2 text-sm text-black cursor-pointer hover:bg-gray-200"
onClick={handleDropdownClose}
>
<span className="flex items-center text-red-600">
<CrossIcon className="w-5 h-5 mr-3" />
Close
</span>
</li>
{Object.entries(dataTypes).map(([key, value]) => (
<li
key={key}
className="block px-4 py-2 text-sm text-black cursor-pointer hover:bg-gray-200"
onClick={() => handleDropdownSelect(key)}
>
<span className="flex items-center">
{dataIcons[key]}
{value}
</span>
</li>
))}
</ul>
</div>
)}
</div>
{sourceName && (
<form
onSubmit={handleAddDataSource}
className="w-full flex flex-col sm:flex-row gap-y-2 gap-x-2 items-center"
>
<div className="w-full">
<input
type="text"
placeholder="Enter URL, Data or File path here..."
className="text-sm w-full border-2 border-black rounded-xl focus:outline-none focus:border-blue-800 sm:pl-4 h-11"
required
value={sourceValue}
onChange={(e) => setSourceValue(e.target.value)}
/>
</div>
<div className="w-full sm:w-fit">
<button
type="submit"
disabled={isLoading}
className={`${
isLoading ? "opacity-60" : ""
} w-full bg-black hover:bg-blue-800 rounded-xl text-lg text-white px-6 h-11`}
>
Send
</button>
</div>
</form>
)}
</>
);
}

View File

@@ -0,0 +1,131 @@
import Link from "next/link";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import DrawerIcon from "../../public/icons/drawer.svg";
import SettingsIcon from "../../public/icons/settings.svg";
import BotIcon from "../../public/icons/bot.svg";
import DropdownIcon from "../../public/icons/dropdown.svg";
import TwitterIcon from "../../public/icons/twitter.svg";
import GithubIcon from "../../public/icons/github.svg";
import LinkedinIcon from "../../public/icons/linkedin.svg";
export default function Sidebar() {
const [bots, setBots] = useState([]);
useEffect(() => {
const fetchBots = async () => {
const response = await fetch("/api/get_bots");
const data = await response.json();
setBots(data);
};
fetchBots();
}, []);
const toggleDropdown = () => {
const dropdown = document.getElementById("dropdown-toggle");
dropdown.classList.toggle("hidden");
};
return (
<>
{/* Mobile Toggle */}
<button
data-drawer-target="logo-sidebar"
data-drawer-toggle="logo-sidebar"
aria-controls="logo-sidebar"
type="button"
className="inline-flex items-center p-2 mt-2 ml-3 text-sm text-gray-500 rounded-lg sm:hidden hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-200"
>
<DrawerIcon className="w-6 h-6" />
</button>
{/* Sidebar */}
<div
id="logo-sidebar"
className="fixed top-0 left-0 z-40 w-64 h-screen transition-transform -translate-x-full sm:translate-x-0"
>
<div className="flex flex-col h-full px-3 py-4 overflow-y-auto bg-gray-100">
<div className="pb-10">
<Link href="/" className="flex items-center justify-evenly mb-5">
<Image
src="/images/embedchain.png"
alt="Embedchain Logo"
width={45}
height={0}
className="block h-auto w-auto"
/>
<span className="self-center text-2xl font-bold whitespace-nowrap">
Embedchain
</span>
</Link>
<ul className="space-y-2 font-medium text-lg">
{/* Settings */}
<li>
<Link
href="/"
className="flex items-center p-2 text-gray-900 rounded-lg hover:bg-gray-200 group"
>
<SettingsIcon className="w-6 h-6 text-gray-600 transition duration-75 group-hover:text-gray-900" />
<span className="ml-3">Settings</span>
</Link>
</li>
{/* Bots */}
{bots.length !== 0 && (
<li>
<button
type="button"
className="flex items-center w-full p-2 text-base text-gray-900 transition duration-75 rounded-lg group hover:bg-gray-200"
onClick={toggleDropdown}
>
<BotIcon className="w-6 h-6 text-gray-600 transition duration-75 group-hover:text-gray-900" />
<span className="flex-1 ml-3 text-left whitespace-nowrap">
Bots
</span>
<DropdownIcon className="w-3 h-3" />
</button>
<ul
id="dropdown-toggle"
className="hidden text-sm py-2 space-y-2"
>
{bots.map((bot, index) => (
<React.Fragment key={index}>
<li>
<Link
href={`/${bot.slug}/app`}
className="flex items-center w-full p-2 text-gray-900 transition duration-75 rounded-lg pl-11 group hover:bg-gray-200"
>
{bot.name}
</Link>
</li>
</React.Fragment>
))}
</ul>
</li>
)}
</ul>
</div>
<div className="bg-gray-200 absolute bottom-0 left-0 right-0 h-20"></div>
{/* Social Icons */}
<div className="mt-auto mb-3 flex flex-row justify-evenly sticky bottom-3">
<a href="https://twitter.com/embedchain" target="blank">
<TwitterIcon className="w-6 h-6 text-gray-600 transition duration-75 hover:text-gray-900" />
</a>
<a href="https://github.com/embedchain/embedchain" target="blank">
<GithubIcon className="w-6 h-6 text-gray-600 transition duration-75 hover:text-gray-900" />
</a>
<a
href="https://www.linkedin.com/company/embedchain"
target="blank"
>
<LinkedinIcon className="w-6 h-6 text-gray-600 transition duration-75 hover:text-gray-900" />
</a>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,25 @@
import Wrapper from "@/components/PageWrapper";
import Sidebar from "@/containers/Sidebar";
import ChatWindow from "@/containers/ChatWindow";
import { useState } from "react";
import Head from "next/head";
export default function App() {
const [botTitle, setBotTitle] = useState("");
return (
<>
<Head>
<title>{botTitle}</title>
</Head>
<Sidebar />
<Wrapper>
<ChatWindow
embedding_model="open_ai"
app_type="app"
setBotTitle={setBotTitle}
/>
</Wrapper>
</>
);
}

View File

@@ -0,0 +1,14 @@
import "@/styles/globals.css";
import Script from "next/script";
export default function App({ Component, pageProps }) {
return (
<>
<Script
src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/1.7.0/flowbite.min.js"
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</>
);
}

View File

@@ -0,0 +1,18 @@
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html lang="en">
<Head>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/1.7.0/flowbite.min.css"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}

View File

@@ -0,0 +1,52 @@
import Wrapper from "@/components/PageWrapper";
import Sidebar from "@/containers/Sidebar";
import CreateBot from "@/components/dashboard/CreateBot";
import SetOpenAIKey from "@/components/dashboard/SetOpenAIKey";
import PurgeChats from "@/components/dashboard/PurgeChats";
import DeleteBot from "@/components/dashboard/DeleteBot";
import { useEffect, useState } from "react";
export default function Home() {
const [isKeyPresent, setIsKeyPresent] = useState(false);
useEffect(() => {
fetch("/api/check_key")
.then((response) => response.json())
.then((data) => {
if (data.status === "ok") {
setIsKeyPresent(true);
}
});
}, []);
return (
<>
<Sidebar />
<Wrapper>
<div className="text-center">
<h1 className="mb-4 text-4xl font-extrabold leading-none tracking-tight text-gray-900 md:text-5xl">
Welcome to Embedchain Playground
</h1>
<p className="mb-6 text-lg font-normal text-gray-500 lg:text-xl">
embedchain is a framework to easily create LLM powered bots over any
dataset
</p>
</div>
<div
className={`pt-6 gap-y-4 gap-x-8 ${
isKeyPresent ? "grid lg:grid-cols-2" : "w-[50%] mx-auto"
}`}
>
<SetOpenAIKey setIsKeyPresent={setIsKeyPresent} />
{isKeyPresent && (
<>
<CreateBot />
<DeleteBot />
<PurgeChats />
</>
)}
</div>
</Wrapper>
</>
);
}

View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;