├── web ├── src │ └── app │ │ ├── interfaces │ │ ├── relate.ts │ │ └── source.ts │ │ ├── favicon.ico │ │ ├── utils │ │ ├── cn.ts │ │ ├── get-search-url.ts │ │ ├── fetch-stream.ts │ │ └── parse-streaming.ts │ │ ├── components │ │ ├── skeleton.tsx │ │ ├── wrapper.tsx │ │ ├── preset-query.tsx │ │ ├── title.tsx │ │ ├── relates.tsx │ │ ├── popover.tsx │ │ ├── search.tsx │ │ ├── footer.tsx │ │ ├── result.tsx │ │ ├── sources.tsx │ │ ├── logo.tsx │ │ └── answer.tsx │ │ ├── globals.css │ │ ├── layout.tsx │ │ ├── page.tsx │ │ ├── search │ │ └── page.tsx │ │ └── icon.svg ├── postcss.config.js ├── public │ └── bg.svg ├── next-env.d.ts ├── .eslintrc.json ├── next.config.mjs ├── tailwind.config.ts ├── tsconfig.json └── package.json ├── README.md ├── lepton_template └── README.md ├── .gitignore ├── LICENSE └── search_with_lepton.py /web/src/app/interfaces/relate.ts: -------------------------------------------------------------------------------- 1 | export interface Relate { 2 | question: string; 3 | } 4 | -------------------------------------------------------------------------------- /web/src/app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codewithsadaf/search_with_lepton/HEAD/web/src/app/favicon.ico -------------------------------------------------------------------------------- /web/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /web/public/bg.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/app/utils/cn.ts: -------------------------------------------------------------------------------- 1 | import { type ClassValue, clsx } from "clsx"; 2 | import { twMerge } from "tailwind-merge"; 3 | 4 | export function cn(...inputs: ClassValue[]) { 5 | return twMerge(clsx(inputs)); 6 | } 7 | -------------------------------------------------------------------------------- /web/next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | // NOTE: This file should not be edited 5 | // see https://nextjs.org/docs/basic-features/typescript for more information. 6 | -------------------------------------------------------------------------------- /web/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["unused-imports"], 3 | "extends": [ 4 | "next/core-web-vitals", 5 | "plugin:prettier/recommended" 6 | ], 7 | "rules": { 8 | "unused-imports/no-unused-imports": "error" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /web/src/app/utils/get-search-url.ts: -------------------------------------------------------------------------------- 1 | export const getSearchUrl = (query: string, search_uuid: string) => { 2 | const prefix = 3 | process.env.NODE_ENV === "production" ? "/search.html" : "/search"; 4 | return `${prefix}?q=${encodeURIComponent(query)}&rid=${search_uuid}`; 5 | }; 6 | -------------------------------------------------------------------------------- /web/src/app/components/skeleton.tsx: -------------------------------------------------------------------------------- 1 | import { cn } from "@/app/utils/cn"; 2 | import { HTMLAttributes } from "react"; 3 | 4 | function Skeleton({ className, ...props }: HTMLAttributes) { 5 | return ( 6 |
10 | ); 11 | } 12 | 13 | export { Skeleton }; 14 | -------------------------------------------------------------------------------- /web/src/app/components/wrapper.tsx: -------------------------------------------------------------------------------- 1 | import { FC, ReactNode } from "react"; 2 | 3 | export const Wrapper: FC<{ 4 | title: ReactNode; 5 | content: ReactNode; 6 | }> = ({ title, content }) => { 7 | return ( 8 |
9 |
{title}
10 | {content} 11 |
12 | ); 13 | }; 14 | -------------------------------------------------------------------------------- /web/src/app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | input:-webkit-autofill, 6 | input:-webkit-autofill:hover, 7 | input:-webkit-autofill:focus, 8 | textarea:-webkit-autofill, 9 | textarea:-webkit-autofill:hover, 10 | textarea:-webkit-autofill:focus, 11 | select:-webkit-autofill, 12 | select:-webkit-autofill:hover, 13 | select:-webkit-autofill:focus { 14 | -webkit-background-clip: text; 15 | } 16 | -------------------------------------------------------------------------------- /web/src/app/interfaces/source.ts: -------------------------------------------------------------------------------- 1 | export interface Source { 2 | id: string; 3 | name: string; 4 | url: string; 5 | isFamilyFriendly: boolean; 6 | displayUrl: string; 7 | snippet: string; 8 | deepLinks: { snippet: string; name: string; url: string }[]; 9 | dateLastCrawled: string; 10 | cachedPageUrl: string; 11 | language: string; 12 | primaryImageOfPage?: { 13 | thumbnailUrl: string; 14 | width: number; 15 | height: number; 16 | imageId: string; 17 | }; 18 | isNavigational: boolean; 19 | } 20 | -------------------------------------------------------------------------------- /web/next.config.mjs: -------------------------------------------------------------------------------- 1 | export default (phase, { defaultConfig }) => { 2 | const env = process.env.NODE_ENV; 3 | /** 4 | * @type {import("next").NextConfig} 5 | */ 6 | if (env === "production") { 7 | return { 8 | output: "export", 9 | assetPrefix: "/ui/", 10 | basePath: "/ui", 11 | distDir: "../ui" 12 | }; 13 | } else { 14 | return { 15 | async rewrites() { 16 | return [ 17 | { 18 | source: "/query", 19 | destination: "http://localhost:8080/query" // Proxy to Backend 20 | } 21 | ]; 22 | } 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /web/src/app/layout.tsx: -------------------------------------------------------------------------------- 1 | import type { Metadata } from "next"; 2 | import { Inter } from "next/font/google"; 3 | import "./globals.css"; 4 | import { ReactNode } from "react"; 5 | 6 | const inter = Inter({ subsets: ["latin"] }); 7 | 8 | export const metadata: Metadata = { 9 | title: "Lepton Search", 10 | description: 11 | "Answer generated by large language models (LLMs). Double check for correctness.", 12 | }; 13 | 14 | export default function RootLayout({ children }: { children: ReactNode }) { 15 | return ( 16 | 17 | {children} 18 | 19 | ); 20 | } 21 | -------------------------------------------------------------------------------- /web/src/app/components/preset-query.tsx: -------------------------------------------------------------------------------- 1 | import { getSearchUrl } from "@/app/utils/get-search-url"; 2 | import { nanoid } from "nanoid"; 3 | import Link from "next/link"; 4 | import React, { FC, useMemo } from "react"; 5 | 6 | export const PresetQuery: FC<{ query: string }> = ({ query }) => { 7 | const rid = useMemo(() => nanoid(), [query]); 8 | 9 | return ( 10 | 16 | {query} 17 | 18 | ); 19 | }; 20 | -------------------------------------------------------------------------------- /web/tailwind.config.ts: -------------------------------------------------------------------------------- 1 | import type { Config } from "tailwindcss"; 2 | 3 | const config: Config = { 4 | content: [ 5 | "./src/pages/**/*.{js,ts,jsx,tsx,mdx}", 6 | "./src/components/**/*.{js,ts,jsx,tsx,mdx}", 7 | "./src/app/**/*.{js,ts,jsx,tsx,mdx}", 8 | ], 9 | theme: { 10 | extend: { 11 | backgroundImage: { 12 | "gradient-radial": "radial-gradient(var(--tw-gradient-stops))", 13 | "gradient-conic": 14 | "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))", 15 | }, 16 | colors: { 17 | blue: { 18 | 500: "#2F80ED", 19 | }, 20 | }, 21 | }, 22 | }, 23 | plugins: [require("@tailwindcss/typography")], 24 | }; 25 | export default config; 26 | -------------------------------------------------------------------------------- /web/src/app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { Footer } from "@/app/components/footer"; 3 | import { Logo } from "@/app/components/logo"; 4 | import { PresetQuery } from "@/app/components/preset-query"; 5 | import { Search } from "@/app/components/search"; 6 | import React from "react"; 7 | 8 | export default function Home() { 9 | return ( 10 |
11 |
12 | 13 | 14 |
15 | 16 | 17 |
18 |
19 |
20 |
21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /web/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "strict": true, 12 | "noEmit": true, 13 | "esModuleInterop": true, 14 | "module": "esnext", 15 | "moduleResolution": "bundler", 16 | "resolveJsonModule": true, 17 | "isolatedModules": true, 18 | "jsx": "preserve", 19 | "incremental": true, 20 | "plugins": [ 21 | { 22 | "name": "next" 23 | } 24 | ], 25 | "paths": { 26 | "@/*": [ 27 | "./src/*" 28 | ] 29 | } 30 | }, 31 | "include": [ 32 | "next-env.d.ts", 33 | "**/*.ts", 34 | "**/*.tsx", 35 | ".next/types/**/*.ts", 36 | "../ui/types/**/*.ts" 37 | ], 38 | "exclude": [ 39 | "node_modules" 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /web/src/app/utils/fetch-stream.ts: -------------------------------------------------------------------------------- 1 | async function pump( 2 | reader: ReadableStreamDefaultReader, 3 | controller: ReadableStreamDefaultController, 4 | onChunk?: (chunk: Uint8Array) => void, 5 | onDone?: () => void, 6 | ): Promise | undefined> { 7 | const { done, value } = await reader.read(); 8 | if (done) { 9 | onDone && onDone(); 10 | controller.close(); 11 | return; 12 | } 13 | onChunk && onChunk(value); 14 | controller.enqueue(value); 15 | return pump(reader, controller, onChunk, onDone); 16 | } 17 | export const fetchStream = ( 18 | response: Response, 19 | onChunk?: (chunk: Uint8Array) => void, 20 | onDone?: () => void, 21 | ): ReadableStream => { 22 | const reader = response.body!.getReader(); 23 | return new ReadableStream({ 24 | start: (controller) => pump(reader, controller, onChunk, onDone), 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /web/src/app/components/title.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { getSearchUrl } from "@/app/utils/get-search-url"; 3 | import { RefreshCcw } from "lucide-react"; 4 | import { nanoid } from "nanoid"; 5 | import { useRouter } from "next/navigation"; 6 | 7 | export const Title = ({ query }: { query: string }) => { 8 | const router = useRouter(); 9 | return ( 10 |
11 |
15 | {query} 16 |
17 |
18 | 27 |
28 |
29 | ); 30 | }; 31 | -------------------------------------------------------------------------------- /web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "search", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint" 10 | }, 11 | "dependencies": { 12 | "@next/third-parties": "^14.0.4", 13 | "@radix-ui/react-popover": "^1.0.7", 14 | "@tailwindcss/forms": "^0.5.7", 15 | "@upstash/ratelimit": "^1.0.0", 16 | "@vercel/kv": "^1.0.1", 17 | "clsx": "^2.1.0", 18 | "headlessui": "^0.0.0", 19 | "lucide-react": "^0.309.0", 20 | "mdast-util-from-markdown": "^2.0.0", 21 | "nanoid": "^5.0.4", 22 | "next": "14.0.4", 23 | "react": "^18", 24 | "react-dom": "^18", 25 | "react-markdown": "^9.0.1", 26 | "tailwind-merge": "^2.2.0", 27 | "unist-builder": "^4.0.0" 28 | }, 29 | "devDependencies": { 30 | "@tailwindcss/typography": "^0.5.10", 31 | "@types/node": "^20", 32 | "@types/react": "^18", 33 | "@types/react-dom": "^18", 34 | "autoprefixer": "^10.0.1", 35 | "eslint": "^8", 36 | "eslint-config-next": "14.0.4", 37 | "eslint-config-prettier": "^9.0.0", 38 | "eslint-plugin-prettier": "^5.0.1", 39 | "eslint-plugin-unused-imports": "^3.0.0", 40 | "postcss": "^8", 41 | "prettier": "^3.1.0", 42 | "tailwindcss": "^3.3.0", 43 | "typescript": "^5" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /web/src/app/components/relates.tsx: -------------------------------------------------------------------------------- 1 | import { PresetQuery } from "@/app/components/preset-query"; 2 | import { Skeleton } from "@/app/components/skeleton"; 3 | import { Wrapper } from "@/app/components/wrapper"; 4 | import { Relate } from "@/app/interfaces/relate"; 5 | import { MessageSquareQuote } from "lucide-react"; 6 | import React, { FC } from "react"; 7 | 8 | export const Relates: FC<{ relates: Relate[] | null }> = ({ relates }) => { 9 | return ( 10 | 13 | Related 14 | 15 | } 16 | content={ 17 |
18 | {relates !== null ? ( 19 | relates.length > 0 ? ( 20 | relates.map(({ question }) => ( 21 | 22 | )) 23 | ) : ( 24 |
No related questions.
25 | ) 26 | ) : ( 27 | <> 28 | 29 | 30 | 31 | 32 | )} 33 |
34 | } 35 | >
36 | ); 37 | }; 38 | -------------------------------------------------------------------------------- /web/src/app/components/popover.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import * as React from "react"; 4 | import * as PopoverPrimitive from "@radix-ui/react-popover"; 5 | 6 | import { cn } from "@/app/utils/cn"; 7 | 8 | const Popover = PopoverPrimitive.Root; 9 | 10 | const PopoverTrigger = PopoverPrimitive.Trigger; 11 | 12 | const PopoverContent = React.forwardRef< 13 | React.ElementRef, 14 | React.ComponentPropsWithoutRef 15 | >(({ className, align = "center", sideOffset = 4, ...props }, ref) => ( 16 | 17 | 27 | 28 | )); 29 | PopoverContent.displayName = PopoverPrimitive.Content.displayName; 30 | 31 | export { Popover, PopoverTrigger, PopoverContent }; 32 | -------------------------------------------------------------------------------- /web/src/app/components/search.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { getSearchUrl } from "@/app/utils/get-search-url"; 3 | import { ArrowRight } from "lucide-react"; 4 | import { nanoid } from "nanoid"; 5 | import { useRouter } from "next/navigation"; 6 | import React, { FC, useState } from "react"; 7 | 8 | export const Search: FC = () => { 9 | const [value, setValue] = useState(""); 10 | const router = useRouter(); 11 | return ( 12 |
{ 14 | e.preventDefault(); 15 | if (value) { 16 | setValue(""); 17 | router.push(getSearchUrl(encodeURIComponent(value), nanoid())); 18 | } 19 | }} 20 | > 21 | 40 |
41 | ); 42 | }; 43 | -------------------------------------------------------------------------------- /web/src/app/search/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { Result } from "@/app/components/result"; 3 | import { Search } from "@/app/components/search"; 4 | import { Title } from "@/app/components/title"; 5 | import { useSearchParams } from "next/navigation"; 6 | export default function SearchPage() { 7 | const searchParams = useSearchParams(); 8 | const query = decodeURIComponent(searchParams.get("q") || ""); 9 | const rid = decodeURIComponent(searchParams.get("rid") || ""); 10 | return ( 11 |
12 |
13 |
14 |
15 | 16 | 17 |
18 |
19 |
20 |
21 | 22 |
23 |
24 |
25 |
26 | ); 27 | } 28 | -------------------------------------------------------------------------------- /web/src/app/components/footer.tsx: -------------------------------------------------------------------------------- 1 | import { Mails } from "lucide-react"; 2 | import { FC } from "react"; 3 | 4 | export const Footer: FC = () => { 5 | return ( 6 |
7 |
8 | Answer generated by large language models, plz double check for 9 | correctness. 10 |
11 |
12 | LLM, Vector DB, and other components powered by the Lepton AI platform. 13 |
14 |
15 | 24 |
if you need a performant and scalable AI cloud!
25 |
26 | 27 | 50 |
51 | ); 52 | }; 53 | -------------------------------------------------------------------------------- /web/src/app/components/result.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { Answer } from "@/app/components/answer"; 3 | import { Relates } from "@/app/components/relates"; 4 | import { Sources } from "@/app/components/sources"; 5 | import { Relate } from "@/app/interfaces/relate"; 6 | import { Source } from "@/app/interfaces/source"; 7 | import { parseStreaming } from "@/app/utils/parse-streaming"; 8 | import { Annoyed } from "lucide-react"; 9 | import { FC, useEffect, useState } from "react"; 10 | 11 | export const Result: FC<{ query: string; rid: string }> = ({ query, rid }) => { 12 | const [sources, setSources] = useState([]); 13 | const [markdown, setMarkdown] = useState(""); 14 | const [relates, setRelates] = useState(null); 15 | const [error, setError] = useState(null); 16 | useEffect(() => { 17 | const controller = new AbortController(); 18 | void parseStreaming( 19 | controller, 20 | query, 21 | rid, 22 | setSources, 23 | setMarkdown, 24 | setRelates, 25 | setError, 26 | ); 27 | return () => { 28 | controller.abort(); 29 | }; 30 | }, [query]); 31 | return ( 32 |
33 | 34 | 35 | 36 | {error && ( 37 |
38 |
39 | 40 | {error === 429 41 | ? "Sorry, you have made too many requests recently, try again later." 42 | : "Sorry, we might be overloaded, try again later."} 43 |
44 |
45 | )} 46 |
47 | ); 48 | }; 49 | -------------------------------------------------------------------------------- /web/src/app/utils/parse-streaming.ts: -------------------------------------------------------------------------------- 1 | import { Relate } from "@/app/interfaces/relate"; 2 | import { Source } from "@/app/interfaces/source"; 3 | import { fetchStream } from "@/app/utils/fetch-stream"; 4 | 5 | const LLM_SPLIT = "__LLM_RESPONSE__"; 6 | const RELATED_SPLIT = "__RELATED_QUESTIONS__"; 7 | 8 | export const parseStreaming = async ( 9 | controller: AbortController, 10 | query: string, 11 | search_uuid: string, 12 | onSources: (value: Source[]) => void, 13 | onMarkdown: (value: string) => void, 14 | onRelates: (value: Relate[]) => void, 15 | onError?: (status: number) => void, 16 | ) => { 17 | const decoder = new TextDecoder(); 18 | let uint8Array = new Uint8Array(); 19 | let chunks = ""; 20 | let sourcesEmitted = false; 21 | const response = await fetch(`/query`, { 22 | method: "POST", 23 | headers: { 24 | "Content-Type": "application/json", 25 | Accept: "*./*", 26 | }, 27 | signal: controller.signal, 28 | body: JSON.stringify({ 29 | query, 30 | search_uuid, 31 | }), 32 | }); 33 | if (response.status !== 200) { 34 | onError?.(response.status); 35 | return; 36 | } 37 | const markdownParse = (text: string) => { 38 | onMarkdown( 39 | text 40 | .replace(/\[\[([cC])itation/g, "[citation") 41 | .replace(/[cC]itation:(\d+)]]/g, "citation:$1]") 42 | .replace(/\[\[([cC]itation:\d+)]](?!])/g, `[$1]`) 43 | .replace(/\[[cC]itation:(\d+)]/g, "[citation]($1)"), 44 | ); 45 | }; 46 | fetchStream( 47 | response, 48 | (chunk) => { 49 | uint8Array = new Uint8Array([...uint8Array, ...chunk]); 50 | chunks = decoder.decode(uint8Array, { stream: true }); 51 | if (chunks.includes(LLM_SPLIT)) { 52 | const [sources, rest] = chunks.split(LLM_SPLIT); 53 | if (!sourcesEmitted) { 54 | try { 55 | onSources(JSON.parse(sources)); 56 | } catch (e) { 57 | onSources([]); 58 | } 59 | } 60 | sourcesEmitted = true; 61 | if (rest.includes(RELATED_SPLIT)) { 62 | const [md] = rest.split(RELATED_SPLIT); 63 | markdownParse(md); 64 | } else { 65 | markdownParse(rest); 66 | } 67 | } 68 | }, 69 | () => { 70 | const [_, relates] = chunks.split(RELATED_SPLIT); 71 | try { 72 | onRelates(JSON.parse(relates)); 73 | } catch (e) { 74 | onRelates([]); 75 | } 76 | }, 77 | ); 78 | }; 79 | -------------------------------------------------------------------------------- /web/src/app/components/sources.tsx: -------------------------------------------------------------------------------- 1 | import { Skeleton } from "@/app/components/skeleton"; 2 | import { Wrapper } from "@/app/components/wrapper"; 3 | import { Source } from "@/app/interfaces/source"; 4 | import { BookText } from "lucide-react"; 5 | import { FC } from "react"; 6 | 7 | const SourceItem: FC<{ source: Source; index: number }> = ({ 8 | source, 9 | index, 10 | }) => { 11 | const { id, name, url } = source; 12 | const domain = new URL(url).hostname; 13 | return ( 14 |
18 | 19 |
20 | {name} 21 |
22 |
23 |
24 |
25 | {index + 1} - {domain} 26 |
27 |
28 |
29 | {domain} 34 |
35 |
36 |
37 | ); 38 | }; 39 | 40 | export const Sources: FC<{ sources: Source[] }> = ({ sources }) => { 41 | return ( 42 | 45 | Sources 46 | 47 | } 48 | content={ 49 |
50 | {sources.length > 0 ? ( 51 | sources.map((item, index) => ( 52 | 57 | )) 58 | ) : ( 59 | <> 60 | 61 | 62 | 63 | 64 | 65 | )} 66 |
67 | } 68 | >
69 | ); 70 | }; 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

Search with Lepton

3 | Build your own conversational search engine using less than 500 lines of code. 4 |
5 | Live Demo 6 |
7 | 8 |
9 | 10 | 11 | ## Features 12 | - Built-in support for LLM 13 | - Built-in support for search engine 14 | - Customizable pretty UI interface 15 | - Shareable, cached search results 16 | 17 | ## Setup Search Engine API 18 | There are two default supported search engines: Bing and Google. 19 | 20 | ### Bing Search 21 | To use the Bing Web Search API, please visit [this link](https://www.microsoft.com/en-us/bing/apis/bing-web-search-api) to obtain your Bing subscription key. 22 | 23 | ### Google Search 24 | You have two options for Google Search: you can use the [Google Search API](https://www.serper.dev) from Serper or opt for the [Programmable Search Engine](https://developers.google.com/custom-search) provided by Google. 25 | 26 | ## Setup LLM and KV 27 | 28 | > [!NOTE] 29 | > We recommend using the built-in llm and kv functions with Lepton. 30 | > Running the following commands to set up them automatically. 31 | 32 | ```shell 33 | pip install -U leptonai && lep login 34 | ``` 35 | 36 | 37 | ## Build 38 | 39 | 1. Set Bing subscription key 40 | ```shell 41 | export BING_SEARCH_V7_SUBSCRIPTION_KEY=YOUR_BING_SUBSCRIPTION_KEY 42 | ``` 43 | 2. Build web 44 | ```shell 45 | cd web && npm install && npm run build 46 | ``` 47 | 3. Run server 48 | ```shell 49 | BACKEND=BING python search_with_lepton.py 50 | ``` 51 | 52 | For Google Search using Serper: 53 | ```shell 54 | export SERPER_SEARCH_API_KEY=YOUR_SERPER_API_KEY 55 | BACKEND=SERPER python search_with_lepton.py 56 | ``` 57 | 58 | For Google Search using Programmable Search Engine: 59 | ```shell 60 | export GOOGLE_SEARCH_API_KEY=YOUR_GOOGLE_SEARCH_API_KEY 61 | export GOOGLE_SEARCH_CX=YOUR_GOOGLE_SEARCH_ENGINE_ID 62 | BACKEND=GOOGLE python search_with_lepton.py 63 | ``` 64 | 65 | 66 | 67 | ## Deploy 68 | 69 | You can deploy this to Lepton AI with one click: 70 | 71 | [![Deploy with Lepton AI](https://github.com/leptonai/search_with_lepton/assets/1506722/bbd40afa-69ee-4acb-8974-d060880a183a)](https://dashboard.lepton.ai/workspace-redirect/explore/detail/search-by-lepton) 72 | 73 | You can also deploy your own version via 74 | 75 | ```shell 76 | lep photon run -n search-with-lepton-modified -m search_with_lepton.py --env BACKEND=BING --env BING_SEARCH_V7_SUBSCRIPTION_KEY=YOUR_BING_SUBSCRIPTION_KEY 77 | ``` 78 | 79 | Learn more about `lep photon` [here](https://www.lepton.ai/docs). 80 | -------------------------------------------------------------------------------- /lepton_template/README.md: -------------------------------------------------------------------------------- 1 | # Lepton Search 2 | Build your own conversational search engine using less than 500 lines of code. 3 | 4 | See a live demo site https://search.lepton.run/ 5 | 6 | The source code of this project lives [here](https://github.com/leptonai/search_with_lepton/). This README will detail how to set up and deploy this project on Lepton's platform. 7 | 8 | ## Setup Search Engine API 9 | 10 | You have a few options for setting up your search engine API. You can use Bing or Google, or if you just want to very quickly try the demo out, use the lepton demo API directly. 11 | 12 | ### Bing 13 | 14 | If you are using Bing, you can subscribe to the bing search api [here](https://www.microsoft.com/en-us/bing/apis/bing-web-search-api). After that, write down the Bing search api subscription key. We follow the convention and name it `BING_SEARCH_V7_SUBSCRIPTION_KEY`. We recommend you store the key as a secret in Lepton. 15 | 16 | ### Google 17 | 18 | If you choose to use Google, you can follow the instructions [here](https://developers.google.com/custom-search/v1/overview) to get your Google search api key. We follow the convention and name it `GOOGLE_SEARCH_API_KEY`. We recommend you store the key as a secret in Lepton. You will also get a search engine CX id, which you will need as well. 19 | 20 | ### Lepton Demo API 21 | 22 | If you choose to use the lepton demo api, you don't need to do anything - your workspace credential will give you access to the demo api. Note that this does incur an API call cost. 23 | 24 | 25 | ## Deployment Configurations 26 | 27 | Here are the configurations you can set for your deployment: 28 | * Name: The name of your deployment, like "my-search" 29 | * Resource Shape: most of heavy lifting will be done by the LLM server and the search engine API, so you can choose a small resource shape. `cpu.small` is usually good enough. 30 | 31 | Then, set the following environmental variables. 32 | 33 | * `BACKEND`: the search backend to use. If you don't have bing or google set up, simply use `LEPTON` to try the demo. Otherwise, do `BING` or `GOOGLE`. 34 | * `LLM_MODEL`: the LLM model to run. We recommend using `mixtral-8x7b`, but if you want to experiment other models, you can try the ones hosted on LeptonAI, for example, `llama2-70b`, `llama2-13b`, `llama2-7b`. Note that small models won't work that well. 35 | * `KV_NAME`: the Lepton KV to use to store the search results. You can use the default `search-with-lepton`. 36 | * `RELATED_QUESTIONS`: whether to generate related questions. If you set this to `true`, the search engine will generate related questions for you. Otherwise, it will not. 37 | * `GOOGLE_SEARCH_CX`: if you are using google, specify the search cx. Otherwise, leave it empty. 38 | * `LEPTON_ENABLE_AUTH_BY_COOKIE`: this is to allow web UI access to the deployment. Set it to `true`. 39 | 40 | In addition, you will need to set the following secrets: 41 | * `LEPTON_WORKSPACE_TOKEN`: this is required to call Lepton's LLM and KV apis. You can find your workspace token at [Settings](https://dashboard.lepton.ai/workspace-redirect/settings). 42 | * `BING_SEARCH_V7_SUBSCRIPTION_KEY`: if you are using Bing, you need to specify the subscription key. Otherwise it is not needed. 43 | * `GOOGLE_SEARCH_API_KEY`: if you are using Google, you need to specify the search api key. Note that you should also specify the cx in the env. If you are not using Google, it is not needed. 44 | 45 | Once these fields are set, click `Deploy` button at the bottom of the page to create the deployment. You can see the deployment has now been created under [Deployments](https://dashboard.lepton.ai/workspace-redirect/deployments). Click on the deployment name to check the details. You’ll be able to see the deployment URL and status on this page. 46 | 47 | Once the status is turned into `Ready`, click the URL on the deployment card to access it. Enjoy! 48 | -------------------------------------------------------------------------------- /web/src/app/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 8 | 14 | 18 | 22 | 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | 163 | # Web related 164 | 165 | # dependencies 166 | node_modules/ 167 | /.pnp 168 | .pnp.js 169 | .yarn/install-state.gz 170 | 171 | # testing 172 | /coverage 173 | 174 | # next.js 175 | .next/ 176 | /out/ 177 | 178 | # production 179 | /build 180 | /ui 181 | 182 | # misc 183 | .DS_Store 184 | .idea 185 | *.pem 186 | 187 | # debug 188 | npm-debug.log* 189 | yarn-debug.log* 190 | yarn-error.log* 191 | 192 | # local env files 193 | .env*.local 194 | 195 | # vercel 196 | .vercel 197 | 198 | # typescript 199 | *.tsbuildinfo 200 | next-env.d.ts 201 | -------------------------------------------------------------------------------- /web/src/app/components/logo.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC } from "react"; 2 | 3 | export const Logo: FC = () => { 4 | return ( 5 |
6 |
7 | 8 | 14 | 20 | 24 | 28 | 29 |
30 |
31 | Lepton Search 32 |
33 |
34 | beta 35 |
36 |
37 | ); 38 | }; 39 | -------------------------------------------------------------------------------- /web/src/app/components/answer.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Popover, 3 | PopoverContent, 4 | PopoverTrigger, 5 | } from "@/app/components/popover"; 6 | import { Skeleton } from "@/app/components/skeleton"; 7 | import { Wrapper } from "@/app/components/wrapper"; 8 | import { Source } from "@/app/interfaces/source"; 9 | import { BookOpenText } from "lucide-react"; 10 | import { FC } from "react"; 11 | import Markdown from "react-markdown"; 12 | 13 | export const Answer: FC<{ markdown: string; sources: Source[] }> = ({ 14 | markdown, 15 | sources, 16 | }) => { 17 | return ( 18 | 21 | Answer 22 | 23 | } 24 | content={ 25 | markdown ? ( 26 |
27 | { 30 | if (!props.href) return <>; 31 | const source = sources[+props.href - 1]; 32 | if (!source) return <>; 33 | return ( 34 | 35 | 36 | 37 | 41 | {props.href} 42 | 43 | 44 | 48 |
49 | {source.name} 50 |
51 |
52 | {source.primaryImageOfPage?.thumbnailUrl && ( 53 |
54 | 60 |
61 | )} 62 |
63 |
64 | {source.snippet} 65 |
66 |
67 |
68 | 69 |
70 |
71 | 80 |
81 |
82 | {source.url} 87 |
88 |
89 |
90 |
91 |
92 | ); 93 | }, 94 | }} 95 | > 96 | {markdown} 97 |
98 |
99 | ) : ( 100 |
101 | 102 | 103 | 104 | 105 | 106 |
107 | ) 108 | } 109 | >
110 | ); 111 | }; 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /search_with_lepton.py: -------------------------------------------------------------------------------- 1 | import concurrent.futures 2 | import glob 3 | import json 4 | import os 5 | import re 6 | import threading 7 | import requests 8 | import traceback 9 | from typing import Annotated, List, Generator, Optional 10 | 11 | from fastapi import HTTPException 12 | from fastapi.responses import HTMLResponse, StreamingResponse, RedirectResponse 13 | import httpx 14 | from loguru import logger 15 | 16 | import leptonai 17 | from leptonai import Client 18 | from leptonai.kv import KV 19 | from leptonai.photon import Photon, StaticFiles 20 | from leptonai.photon.types import to_bool 21 | from leptonai.api.workspace import WorkspaceInfoLocalRecord 22 | from leptonai.util import tool 23 | 24 | ################################################################################ 25 | # Constant values for the RAG model. 26 | ################################################################################ 27 | 28 | # Search engine related. You don't really need to change this. 29 | BING_SEARCH_V7_ENDPOINT = "https://api.bing.microsoft.com/v7.0/search" 30 | BING_MKT = "en-US" 31 | GOOGLE_SEARCH_ENDPOINT = "https://customsearch.googleapis.com/customsearch/v1" 32 | SERPER_SEARCH_ENDPOINT = "https://google.serper.dev/search" 33 | 34 | # Specify the number of references from the search engine you want to use. 35 | # 8 is usually a good number. 36 | REFERENCE_COUNT = 8 37 | 38 | # Specify the default timeout for the search engine. If the search engine 39 | # does not respond within this time, we will return an error. 40 | DEFAULT_SEARCH_ENGINE_TIMEOUT = 5 41 | 42 | 43 | # If the user did not provide a query, we will use this default query. 44 | _default_query = "Who said 'live long and prosper'?" 45 | 46 | # This is really the most important part of the rag model. It gives instructions 47 | # to the model on how to generate the answer. Of course, different models may 48 | # behave differently, and we haven't tuned the prompt to make it optimal - this 49 | # is left to you, application creators, as an open problem. 50 | _rag_query_text = """ 51 | You are a large language AI assistant built by Lepton AI. You are given a user question, and please write clean, concise and accurate answer to the question. You will be given a set of related contexts to the question, each starting with a reference number like [[citation:x]], where x is a number. Please use the context and cite the context at the end of each sentence if applicable. 52 | 53 | Your answer must be correct, accurate and written by an expert using an unbiased and professional tone. Please limit to 1024 tokens. Do not give any information that is not related to the question, and do not repeat. Say "information is missing on" followed by the related topic, if the given context do not provide sufficient information. 54 | 55 | Please cite the contexts with the reference numbers, in the format [citation:x]. If a sentence comes from multiple contexts, please list all applicable citations, like [citation:3][citation:5]. Other than code and specific names and citations, your answer must be written in the same language as the question. 56 | 57 | Here are the set of contexts: 58 | 59 | {context} 60 | 61 | Remember, don't blindly repeat the contexts verbatim. And here is the user question: 62 | """ 63 | 64 | # A set of stop words to use - this is not a complete set, and you may want to 65 | # add more given your observation. 66 | stop_words = [ 67 | "<|im_end|>", 68 | "[End]", 69 | "[end]", 70 | "\nReferences:\n", 71 | "\nSources:\n", 72 | "End.", 73 | ] 74 | 75 | # This is the prompt that asks the model to generate related questions to the 76 | # original question and the contexts. 77 | # Ideally, one want to include both the original question and the answer from the 78 | # model, but we are not doing that here: if we need to wait for the answer, then 79 | # the generation of the related questions will usually have to start only after 80 | # the whole answer is generated. This creates a noticeable delay in the response 81 | # time. As a result, and as you will see in the code, we will be sending out two 82 | # consecutive requests to the model: one for the answer, and one for the related 83 | # questions. This is not ideal, but it is a good tradeoff between response time 84 | # and quality. 85 | _more_questions_prompt = """ 86 | You are a helpful assistant that helps the user to ask related questions, based on user's original question and the related contexts. Please identify worthwhile topics that can be follow-ups, and write questions no longer than 20 words each. Please make sure that specifics, like events, names, locations, are included in follow up questions so they can be asked standalone. For example, if the original question asks about "the Manhattan project", in the follow up question, do not just say "the project", but use the full name "the Manhattan project". Your related questions must be in the same language as the original question. 87 | 88 | Here are the contexts of the question: 89 | 90 | {context} 91 | 92 | Remember, based on the original question and related contexts, suggest three such further questions. Do NOT repeat the original question. Each related question should be no longer than 20 words. Here is the original question: 93 | """ 94 | 95 | 96 | def search_with_bing(query: str, subscription_key: str): 97 | """ 98 | Search with bing and return the contexts. 99 | """ 100 | params = {"q": query, "mkt": BING_MKT} 101 | response = requests.get( 102 | BING_SEARCH_V7_ENDPOINT, 103 | headers={"Ocp-Apim-Subscription-Key": subscription_key}, 104 | params=params, 105 | timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT, 106 | ) 107 | if not response.ok: 108 | logger.error(f"{response.status_code} {response.text}") 109 | raise HTTPException(response.status_code, "Search engine error.") 110 | json_content = response.json() 111 | try: 112 | contexts = json_content["webPages"]["value"][:REFERENCE_COUNT] 113 | except KeyError: 114 | logger.error(f"Error encountered: {json_content}") 115 | return [] 116 | return contexts 117 | 118 | 119 | def search_with_google(query: str, subscription_key: str, cx: str): 120 | """ 121 | Search with google and return the contexts. 122 | """ 123 | params = { 124 | "key": subscription_key, 125 | "cx": cx, 126 | "q": query, 127 | "num": REFERENCE_COUNT, 128 | } 129 | response = requests.get( 130 | GOOGLE_SEARCH_ENDPOINT, params=params, timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT 131 | ) 132 | if not response.ok: 133 | logger.error(f"{response.status_code} {response.text}") 134 | raise HTTPException(response.status_code, "Search engine error.") 135 | json_content = response.json() 136 | try: 137 | contexts = json_content["items"][:REFERENCE_COUNT] 138 | except KeyError: 139 | logger.error(f"Error encountered: {json_content}") 140 | return [] 141 | return contexts 142 | 143 | 144 | def search_with_serper(query: str, subscription_key: str): 145 | """ 146 | Search with serper and return the contexts. 147 | """ 148 | payload = json.dumps({ 149 | "q": query, 150 | "num": ( 151 | REFERENCE_COUNT 152 | if REFERENCE_COUNT % 10 == 0 153 | else (REFERENCE_COUNT // 10 + 1) * 10 154 | ), 155 | }) 156 | headers = {"X-API-KEY": subscription_key, "Content-Type": "application/json"} 157 | logger.info( 158 | f"{payload} {headers} {subscription_key} {query} {SERPER_SEARCH_ENDPOINT}" 159 | ) 160 | response = requests.post( 161 | SERPER_SEARCH_ENDPOINT, 162 | headers=headers, 163 | data=payload, 164 | timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT, 165 | ) 166 | if not response.ok: 167 | logger.error(f"{response.status_code} {response.text}") 168 | raise HTTPException(response.status_code, "Search engine error.") 169 | json_content = response.json() 170 | try: 171 | # convert to the same format as bing/google 172 | contexts = [] 173 | if json_content.get("knowledgeGraph"): 174 | url = json_content["knowledgeGraph"].get("descriptionUrl") or json_content["knowledgeGraph"].get("website") 175 | snippet = json_content["knowledgeGraph"].get("description") 176 | if url and snippet: 177 | contexts.append({ 178 | "name": json_content["knowledgeGraph"].get("title",""), 179 | "url": url, 180 | "snippet": snippet 181 | }) 182 | if json_content.get("answerBox"): 183 | url = json_content["answerBox"].get("url") 184 | snippet = json_content["answerBox"].get("snippet") or json_content["answerBox"].get("answer") 185 | if url and snippet: 186 | contexts.append({ 187 | "name": json_content["answerBox"].get("title",""), 188 | "url": url, 189 | "snippet": snippet 190 | }) 191 | contexts += [ 192 | {"name": c["title"], "url": c["link"], "snippet": c.get("snippet","")} 193 | for c in json_content["organic"] 194 | ] 195 | return contexts[:REFERENCE_COUNT] 196 | except KeyError: 197 | logger.error(f"Error encountered: {json_content}") 198 | return [] 199 | 200 | class RAG(Photon): 201 | """ 202 | Retrieval-Augmented Generation Demo from Lepton AI. 203 | 204 | This is a minimal example to show how to build a RAG engine with Lepton AI. 205 | It uses search engine to obtain results based on user queries, and then uses 206 | LLM models to generate the answer as well as related questions. The results 207 | are then stored in a KV so that it can be retrieved later. 208 | """ 209 | 210 | requirement_dependency = [ 211 | "openai", # for openai client usage. 212 | ] 213 | 214 | extra_files = glob.glob("ui/**/*", recursive=True) 215 | 216 | deployment_template = { 217 | # All actual computations are carried out via remote apis, so 218 | # we will use a cpu.small instance which is already enough for most of 219 | # the work. 220 | "resource_shape": "cpu.small", 221 | # You most likely don't need to change this. 222 | "env": { 223 | # Choose the backend. Currently, we support BING and GOOGLE. For 224 | # simplicity, in this demo, if you specify the backend as LEPTON, 225 | # we will use the hosted serverless version of lepton search api 226 | # at https://search-api.lepton.run/ to do the search and RAG, which 227 | # runs the same code (slightly modified and might contain improvements) 228 | # as this demo. 229 | "BACKEND": "LEPTON", 230 | # If you are using google, specify the search cx. 231 | "GOOGLE_SEARCH_CX": "", 232 | # Specify the LLM model you are going to use. 233 | "LLM_MODEL": "mixtral-8x7b", 234 | # For all the search queries and results, we will use the Lepton KV to 235 | # store them so that we can retrieve them later. Specify the name of the 236 | # KV here. 237 | "KV_NAME": "search-with-lepton", 238 | # If set to true, will generate related questions. Otherwise, will not. 239 | "RELATED_QUESTIONS": "true", 240 | # On the lepton platform, allow web access when you are logged in. 241 | "LEPTON_ENABLE_AUTH_BY_COOKIE": "true", 242 | }, 243 | # Secrets you need to have: search api subscription key, and lepton 244 | # workspace token to query lepton's llama models. 245 | "secret": [ 246 | # If you use BING, you need to specify the subscription key. Otherwise 247 | # it is not needed. 248 | "BING_SEARCH_V7_SUBSCRIPTION_KEY", 249 | # If you use GOOGLE, you need to specify the search api key. Note that 250 | # you should also specify the cx in the env. 251 | "GOOGLE_SEARCH_API_KEY", 252 | # If you use Serper, you need to specify the search api key. 253 | "SERPER_SEARCH_API_KEY", 254 | # You need to specify the workspace token to query lepton's LLM models. 255 | "LEPTON_WORKSPACE_TOKEN", 256 | ], 257 | } 258 | 259 | # It's just a bunch of api calls, so our own deployment can be made massively 260 | # concurrent. 261 | handler_max_concurrency = 16 262 | 263 | def local_client(self): 264 | """ 265 | Gets a thread-local client, so in case openai clients are not thread safe, 266 | each thread will have its own client. 267 | """ 268 | import openai 269 | 270 | thread_local = threading.local() 271 | try: 272 | return thread_local.client 273 | except AttributeError: 274 | thread_local.client = openai.OpenAI( 275 | base_url=f"https://{self.model}.lepton.run/api/v1/", 276 | api_key=os.environ.get("LEPTON_WORKSPACE_TOKEN") 277 | or WorkspaceInfoLocalRecord.get_current_workspace_token(), 278 | # We will set the connect timeout to be 10 seconds, and read/write 279 | # timeout to be 120 seconds, in case the inference server is 280 | # overloaded. 281 | timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10), 282 | ) 283 | return thread_local.client 284 | 285 | def init(self): 286 | """ 287 | Initializes photon configs. 288 | """ 289 | # First, log in to the workspace. 290 | leptonai.api.workspace.login() 291 | self.backend = os.environ["BACKEND"].upper() 292 | if self.backend == "LEPTON": 293 | self.leptonsearch_client = Client( 294 | "https://search-api.lepton.run/", 295 | token=os.environ.get("LEPTON_WORKSPACE_TOKEN") 296 | or WorkspaceInfoLocalRecord.get_current_workspace_token(), 297 | stream=True, 298 | timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10), 299 | ) 300 | elif self.backend == "BING": 301 | self.search_api_key = os.environ["BING_SEARCH_V7_SUBSCRIPTION_KEY"] 302 | self.search_function = lambda query: search_with_bing( 303 | query, 304 | self.search_api_key, 305 | ) 306 | elif self.backend == "GOOGLE": 307 | self.search_api_key = os.environ["GOOGLE_SEARCH_API_KEY"] 308 | self.search_function = lambda query: search_with_google( 309 | query, 310 | self.search_api_key, 311 | os.environ["GOOGLE_SEARCH_CX"], 312 | ) 313 | elif self.backend == "SERPER": 314 | self.search_api_key = os.environ["SERPER_SEARCH_API_KEY"] 315 | self.search_function = lambda query: search_with_serper( 316 | query, 317 | self.search_api_key, 318 | ) 319 | else: 320 | raise RuntimeError("Backend must be LEPTON, BING, GOOGLE or SERPER.") 321 | self.model = os.environ["LLM_MODEL"] 322 | # An executor to carry out async tasks, such as uploading to KV. 323 | self.executor = concurrent.futures.ThreadPoolExecutor( 324 | max_workers=self.handler_max_concurrency * 2 325 | ) 326 | # Create the KV to store the search results. 327 | logger.info("Creating KV. May take a while for the first time.") 328 | self.kv = KV( 329 | os.environ["KV_NAME"], create_if_not_exists=True, error_if_exists=False 330 | ) 331 | # whether we should generate related questions. 332 | self.should_do_related_questions = to_bool(os.environ["RELATED_QUESTIONS"]) 333 | 334 | def get_related_questions(self, query, contexts): 335 | """ 336 | Gets related questions based on the query and context. 337 | """ 338 | 339 | def ask_related_questions( 340 | questions: Annotated[ 341 | List[str], 342 | [( 343 | "question", 344 | Annotated[ 345 | str, "related question to the original question and context." 346 | ], 347 | )], 348 | ] 349 | ): 350 | """ 351 | ask further questions that are related to the input and output. 352 | """ 353 | pass 354 | 355 | try: 356 | response = self.local_client().chat.completions.create( 357 | model=self.model, 358 | messages=[ 359 | { 360 | "role": "system", 361 | "content": _more_questions_prompt.format( 362 | context="\n\n".join([c["snippet"] for c in contexts]) 363 | ), 364 | }, 365 | { 366 | "role": "user", 367 | "content": query, 368 | }, 369 | ], 370 | tools=[{ 371 | "type": "function", 372 | "function": tool.get_tools_spec(ask_related_questions), 373 | }], 374 | max_tokens=512, 375 | ) 376 | related = response.choices[0].message.tool_calls[0].function.arguments 377 | if isinstance(related, str): 378 | related = json.loads(related) 379 | logger.trace(f"Related questions: {related}") 380 | return related["questions"][:5] 381 | except Exception as e: 382 | # For any exceptions, we will just return an empty list. 383 | logger.error( 384 | "encountered error while generating related questions:" 385 | f" {e}\n{traceback.format_exc()}" 386 | ) 387 | return [] 388 | 389 | def _raw_stream_response( 390 | self, contexts, llm_response, related_questions_future 391 | ) -> Generator[str, None, None]: 392 | """ 393 | A generator that yields the raw stream response. You do not need to call 394 | this directly. Instead, use the stream_and_upload_to_kv which will also 395 | upload the response to KV. 396 | """ 397 | # First, yield the contexts. 398 | yield json.dumps(contexts) 399 | yield "\n\n__LLM_RESPONSE__\n\n" 400 | # Second, yield the llm response. 401 | if not contexts: 402 | # Prepend a warning to the user 403 | yield ( 404 | "(The search engine returned nothing for this query. Please take the" 405 | " answer with a grain of salt.)\n\n" 406 | ) 407 | for chunk in llm_response: 408 | if chunk.choices: 409 | yield chunk.choices[0].delta.content or "" 410 | # Third, yield the related questions. If any error happens, we will just 411 | # return an empty list. 412 | if related_questions_future is not None: 413 | related_questions = related_questions_future.result() 414 | try: 415 | result = json.dumps(related_questions) 416 | except Exception as e: 417 | logger.error(f"encountered error: {e}\n{traceback.format_exc()}") 418 | result = "[]" 419 | yield "\n\n__RELATED_QUESTIONS__\n\n" 420 | yield result 421 | 422 | def stream_and_upload_to_kv( 423 | self, contexts, llm_response, related_questions_future, search_uuid 424 | ) -> Generator[str, None, None]: 425 | """ 426 | Streams the result and uploads to KV. 427 | """ 428 | # First, stream and yield the results. 429 | all_yielded_results = [] 430 | for result in self._raw_stream_response( 431 | contexts, llm_response, related_questions_future 432 | ): 433 | all_yielded_results.append(result) 434 | yield result 435 | # Second, upload to KV. Note that if uploading to KV fails, we will silently 436 | # ignore it, because we don't want to affect the user experience. 437 | _ = self.executor.submit(self.kv.put, search_uuid, "".join(all_yielded_results)) 438 | 439 | @Photon.handler(method="POST", path="/query") 440 | def query_function( 441 | self, 442 | query: str, 443 | search_uuid: str, 444 | generate_related_questions: Optional[bool] = True, 445 | ) -> StreamingResponse: 446 | """ 447 | Query the search engine and returns the response. 448 | 449 | The query can have the following fields: 450 | - query: the user query. 451 | - search_uuid: a uuid that is used to store or retrieve the search result. If 452 | the uuid does not exist, generate and write to the kv. If the kv 453 | fails, we generate regardless, in favor of availability. If the uuid 454 | exists, return the stored result. 455 | - generate_related_questions: if set to false, will not generate related 456 | questions. Otherwise, will depend on the environment variable 457 | RELATED_QUESTIONS. Default: true. 458 | """ 459 | # Note that, if uuid exists, we don't check if the stored query is the same 460 | # as the current query, and simply return the stored result. This is to enable 461 | # the user to share a searched link to others and have others see the same result. 462 | if search_uuid: 463 | try: 464 | result = self.kv.get(search_uuid) 465 | 466 | def str_to_generator(result: str) -> Generator[str, None, None]: 467 | yield result 468 | 469 | return StreamingResponse(str_to_generator(result)) 470 | except KeyError: 471 | logger.info(f"Key {search_uuid} not found, will generate again.") 472 | except Exception as e: 473 | logger.error( 474 | f"KV error: {e}\n{traceback.format_exc()}, will generate again." 475 | ) 476 | else: 477 | raise HTTPException(status_code=400, detail="search_uuid must be provided.") 478 | 479 | if self.backend == "LEPTON": 480 | # delegate to the lepton search api. 481 | result = self.leptonsearch_client.query( 482 | query=query, 483 | search_uuid=search_uuid, 484 | generate_related_questions=generate_related_questions, 485 | ) 486 | return StreamingResponse(content=result, media_type="text/html") 487 | 488 | # First, do a search query. 489 | query = query or _default_query 490 | # Basic attack protection: remove "[INST]" or "[/INST]" from the query 491 | query = re.sub(r"\[/?INST\]", "", query) 492 | contexts = self.search_function(query) 493 | 494 | system_prompt = _rag_query_text.format( 495 | context="\n\n".join( 496 | [f"[[citation:{i+1}]] {c['snippet']}" for i, c in enumerate(contexts)] 497 | ) 498 | ) 499 | try: 500 | client = self.local_client() 501 | llm_response = client.chat.completions.create( 502 | model=self.model, 503 | messages=[ 504 | {"role": "system", "content": system_prompt}, 505 | {"role": "user", "content": query}, 506 | ], 507 | max_tokens=1024, 508 | stop=stop_words, 509 | stream=True, 510 | temperature=0.9, 511 | ) 512 | if self.should_do_related_questions and generate_related_questions: 513 | # While the answer is being generated, we can start generating 514 | # related questions as a future. 515 | related_questions_future = self.executor.submit( 516 | self.get_related_questions, query, contexts 517 | ) 518 | else: 519 | related_questions_future = None 520 | except Exception as e: 521 | logger.error(f"encountered error: {e}\n{traceback.format_exc()}") 522 | return HTMLResponse("Internal server error.", 503) 523 | 524 | return StreamingResponse( 525 | self.stream_and_upload_to_kv( 526 | contexts, llm_response, related_questions_future, search_uuid 527 | ), 528 | media_type="text/html", 529 | ) 530 | 531 | @Photon.handler(mount=True) 532 | def ui(self): 533 | return StaticFiles(directory="ui") 534 | 535 | @Photon.handler(method="GET", path="/") 536 | def index(self) -> RedirectResponse: 537 | """ 538 | Redirects "/" to the ui page. 539 | """ 540 | return RedirectResponse(url="/ui/index.html") 541 | 542 | 543 | if __name__ == "__main__": 544 | rag = RAG() 545 | rag.launch() 546 | --------------------------------------------------------------------------------