Repository: leptonai/search_with_lepton
Branch: main
Commit: 0a2fe3713ee4
Files: 33
Total size: 77.5 KB
Directory structure:
gitextract_s5boz8oq/
├── .gitignore
├── LICENSE
├── README.md
├── lepton_template/
│ └── README.md
├── search_with_lepton.py
└── web/
├── .eslintrc.json
├── next.config.mjs
├── package.json
├── postcss.config.js
├── src/
│ └── app/
│ ├── components/
│ │ ├── answer.tsx
│ │ ├── footer.tsx
│ │ ├── logo.tsx
│ │ ├── popover.tsx
│ │ ├── preset-query.tsx
│ │ ├── relates.tsx
│ │ ├── result.tsx
│ │ ├── search.tsx
│ │ ├── skeleton.tsx
│ │ ├── sources.tsx
│ │ ├── title.tsx
│ │ └── wrapper.tsx
│ ├── globals.css
│ ├── interfaces/
│ │ ├── relate.ts
│ │ └── source.ts
│ ├── layout.tsx
│ ├── page.tsx
│ ├── search/
│ │ └── page.tsx
│ └── utils/
│ ├── cn.ts
│ ├── fetch-stream.ts
│ ├── get-search-url.ts
│ └── parse-streaming.ts
├── tailwind.config.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Web related
# dependencies
node_modules/
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
.next/
/out/
# production
/build
/ui
# misc
.DS_Store
.idea
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
Search with Lepton
Build your own conversational search engine using less than 500 lines of code.
Live Demo
## Features
- Built-in support for LLM
- Built-in support for search engine
- Customizable pretty UI interface
- Shareable, cached search results
## Setup Search Engine API
There are two default supported search engines: Bing and Google.
### Bing Search
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.
### Google Search
You have three options for Google Search: you can use the [SearchApi Google Search API](https://www.searchapi.io/) from SearchApi, [Serper Google Search API](https://serper.dev) from Serper, or opt for the [Programmable Search Engine](https://developers.google.com/custom-search) provided by Google.
## Setup LLM and KV
> [!NOTE]
> We recommend using the built-in llm and kv functions with Lepton.
> Running the following commands to set up them automatically.
```shell
pip install -U leptonai openai && lep login
```
## Obtain Your Lepton AI Workspace Token
You can copy your workspace toke from the Lepton AI Dashboard → Settings → Tokens.
## Build
1. Set Bing subscription key
```shell
export BING_SEARCH_V7_SUBSCRIPTION_KEY=YOUR_BING_SUBSCRIPTION_KEY
```
2. Set Lepton AI workspace token
```shell
export LEPTON_WORKSPACE_TOKEN=YOUR_LEPTON_WORKSPACE_TOKEN
```
3. Build web
```shell
cd web && npm install && npm run build
```
4. Run server
```shell
BACKEND=BING python search_with_lepton.py
```
For Google Search using SearchApi:
```shell
export SEARCHAPI_API_KEY=YOUR_SEARCHAPI_API_KEY
BACKEND=SEARCHAPI python search_with_lepton.py
```
For Google Search using Serper:
```shell
export SERPER_SEARCH_API_KEY=YOUR_SERPER_API_KEY
BACKEND=SERPER python search_with_lepton.py
```
For Google Search using Programmable Search Engine:
```shell
export GOOGLE_SEARCH_API_KEY=YOUR_GOOGLE_SEARCH_API_KEY
export GOOGLE_SEARCH_CX=YOUR_GOOGLE_SEARCH_ENGINE_ID
BACKEND=GOOGLE python search_with_lepton.py
```
## Deploy
You can deploy this to Lepton AI with one click:
[](https://dashboard.lepton.ai/workspace-redirect/explore/detail/search-by-lepton)
You can also deploy your own version via
```shell
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
```
Learn more about `lep photon` [here](https://www.lepton.ai/docs/references/lep_photon).
================================================
FILE: lepton_template/README.md
================================================
# Lepton Search
Build your own conversational search engine using less than 500 lines of code.
See a live demo site https://search.lepton.run/
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.
## Setup Search Engine API
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.
### Bing
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.
### Google
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.
### SearchApi
If you want to use SearchApi, a 3rd party Google Search API, you can retrieve the API key by registering [here](https://www.searchapi.io/). We follow the convention and name it `SEARCHAPI_API_KEY`. We recommend you store the key as a secret in Lepton.
### Lepton Demo API
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.
## Deployment Configurations
Here are the configurations you can set for your deployment:
* Name: The name of your deployment, like "my-search"
* 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.
Then, set the following environmental variables.
* `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`, `GOOGLE` or `SEARCHAPI`.
* `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.
* `KV_NAME`: the Lepton KV to use to store the search results. You can use the default `search-with-lepton`.
* `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.
* `GOOGLE_SEARCH_CX`: if you are using google, specify the search cx. Otherwise, leave it empty.
* `LEPTON_ENABLE_AUTH_BY_COOKIE`: this is to allow web UI access to the deployment. Set it to `true`.
In addition, you will need to set the following secrets:
* `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).
* `BING_SEARCH_V7_SUBSCRIPTION_KEY`: if you are using Bing, you need to specify the subscription key. Otherwise it is not needed.
* `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.
* `SEARCHAPI_API_KEY`: if you are using SearchApi, a 3rd party Google Search API, you need to specify the api key.
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.
Once the status is turned into `Ready`, click the URL on the deployment card to access it. Enjoy!
================================================
FILE: search_with_lepton.py
================================================
import concurrent.futures
import glob
import json
import os
import re
import threading
import requests
import traceback
from typing import Annotated, List, Generator, Optional
from fastapi import HTTPException
from fastapi.responses import HTMLResponse, StreamingResponse, RedirectResponse
import httpx
from loguru import logger
import leptonai
from leptonai import Client
from leptonai.kv import KV
from leptonai.photon import Photon, StaticFiles
from leptonai.photon.types import to_bool
from leptonai.api.v0.workspace import WorkspaceInfoLocalRecord
from leptonai.util import tool
################################################################################
# Constant values for the RAG model.
################################################################################
# Search engine related. You don't really need to change this.
BING_SEARCH_V7_ENDPOINT = "https://api.bing.microsoft.com/v7.0/search"
BING_MKT = "en-US"
GOOGLE_SEARCH_ENDPOINT = "https://customsearch.googleapis.com/customsearch/v1"
SERPER_SEARCH_ENDPOINT = "https://google.serper.dev/search"
SEARCHAPI_SEARCH_ENDPOINT = "https://www.searchapi.io/api/v1/search"
# Specify the number of references from the search engine you want to use.
# 8 is usually a good number.
REFERENCE_COUNT = 8
# Specify the default timeout for the search engine. If the search engine
# does not respond within this time, we will return an error.
DEFAULT_SEARCH_ENGINE_TIMEOUT = 5
# If the user did not provide a query, we will use this default query.
_default_query = "Who said 'live long and prosper'?"
# This is really the most important part of the rag model. It gives instructions
# to the model on how to generate the answer. Of course, different models may
# behave differently, and we haven't tuned the prompt to make it optimal - this
# is left to you, application creators, as an open problem.
_rag_query_text = """
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.
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.
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.
Here are the set of contexts:
{context}
Remember, don't blindly repeat the contexts verbatim. And here is the user question:
"""
# A set of stop words to use - this is not a complete set, and you may want to
# add more given your observation.
stop_words = [
"<|im_end|>",
"[End]",
"[end]",
"\nReferences:\n",
"\nSources:\n",
"End.",
]
# This is the prompt that asks the model to generate related questions to the
# original question and the contexts.
# Ideally, one want to include both the original question and the answer from the
# model, but we are not doing that here: if we need to wait for the answer, then
# the generation of the related questions will usually have to start only after
# the whole answer is generated. This creates a noticeable delay in the response
# time. As a result, and as you will see in the code, we will be sending out two
# consecutive requests to the model: one for the answer, and one for the related
# questions. This is not ideal, but it is a good tradeoff between response time
# and quality.
_more_questions_prompt = """
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.
Here are the contexts of the question:
{context}
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:
"""
def search_with_bing(query: str, subscription_key: str):
"""
Search with bing and return the contexts.
"""
params = {"q": query, "mkt": BING_MKT}
response = requests.get(
BING_SEARCH_V7_ENDPOINT,
headers={"Ocp-Apim-Subscription-Key": subscription_key},
params=params,
timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,
)
if not response.ok:
logger.error(f"{response.status_code} {response.text}")
raise HTTPException(response.status_code, "Search engine error.")
json_content = response.json()
try:
contexts = json_content["webPages"]["value"][:REFERENCE_COUNT]
except KeyError:
logger.error(f"Error encountered: {json_content}")
return []
return contexts
def search_with_google(query: str, subscription_key: str, cx: str):
"""
Search with google and return the contexts.
"""
params = {
"key": subscription_key,
"cx": cx,
"q": query,
"num": REFERENCE_COUNT,
}
response = requests.get(
GOOGLE_SEARCH_ENDPOINT, params=params, timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT
)
if not response.ok:
logger.error(f"{response.status_code} {response.text}")
raise HTTPException(response.status_code, "Search engine error.")
json_content = response.json()
try:
contexts = json_content["items"][:REFERENCE_COUNT]
except KeyError:
logger.error(f"Error encountered: {json_content}")
return []
return contexts
def search_with_serper(query: str, subscription_key: str):
"""
Search with serper and return the contexts.
"""
payload = json.dumps({
"q": query,
"num": (
REFERENCE_COUNT
if REFERENCE_COUNT % 10 == 0
else (REFERENCE_COUNT // 10 + 1) * 10
),
})
headers = {"X-API-KEY": subscription_key, "Content-Type": "application/json"}
logger.info(
f"{payload} {headers} {subscription_key} {query} {SERPER_SEARCH_ENDPOINT}"
)
response = requests.post(
SERPER_SEARCH_ENDPOINT,
headers=headers,
data=payload,
timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,
)
if not response.ok:
logger.error(f"{response.status_code} {response.text}")
raise HTTPException(response.status_code, "Search engine error.")
json_content = response.json()
try:
# convert to the same format as bing/google
contexts = []
if json_content.get("knowledgeGraph"):
url = json_content["knowledgeGraph"].get("descriptionUrl") or json_content["knowledgeGraph"].get("website")
snippet = json_content["knowledgeGraph"].get("description")
if url and snippet:
contexts.append({
"name": json_content["knowledgeGraph"].get("title",""),
"url": url,
"snippet": snippet
})
if json_content.get("answerBox"):
url = json_content["answerBox"].get("url")
snippet = json_content["answerBox"].get("snippet") or json_content["answerBox"].get("answer")
if url and snippet:
contexts.append({
"name": json_content["answerBox"].get("title",""),
"url": url,
"snippet": snippet
})
contexts += [
{"name": c["title"], "url": c["link"], "snippet": c.get("snippet","")}
for c in json_content["organic"]
]
return contexts[:REFERENCE_COUNT]
except KeyError:
logger.error(f"Error encountered: {json_content}")
return []
def search_with_searchapi(query: str, subscription_key: str):
"""
Search with SearchApi.io and return the contexts.
"""
payload = {
"q": query,
"engine": "google",
"num": (
REFERENCE_COUNT
if REFERENCE_COUNT % 10 == 0
else (REFERENCE_COUNT // 10 + 1) * 10
),
}
headers = {"Authorization": f"Bearer {subscription_key}", "Content-Type": "application/json"}
logger.info(
f"{payload} {headers} {subscription_key} {query} {SEARCHAPI_SEARCH_ENDPOINT}"
)
response = requests.get(
SEARCHAPI_SEARCH_ENDPOINT,
headers=headers,
params=payload,
timeout=30,
)
if not response.ok:
logger.error(f"{response.status_code} {response.text}")
raise HTTPException(response.status_code, "Search engine error.")
json_content = response.json()
try:
# convert to the same format as bing/google
contexts = []
if json_content.get("answer_box"):
if json_content["answer_box"].get("organic_result"):
title = json_content["answer_box"].get("organic_result").get("title", "")
url = json_content["answer_box"].get("organic_result").get("link", "")
if json_content["answer_box"].get("type") == "population_graph":
title = json_content["answer_box"].get("place", "")
url = json_content["answer_box"].get("explore_more_link", "")
title = json_content["answer_box"].get("title", "")
url = json_content["answer_box"].get("link")
snippet = json_content["answer_box"].get("answer") or json_content["answer_box"].get("snippet")
if url and snippet:
contexts.append({
"name": title,
"url": url,
"snippet": snippet
})
if json_content.get("knowledge_graph"):
if json_content["knowledge_graph"].get("source"):
url = json_content["knowledge_graph"].get("source").get("link", "")
url = json_content["knowledge_graph"].get("website", "")
snippet = json_content["knowledge_graph"].get("description")
if url and snippet:
contexts.append({
"name": json_content["knowledge_graph"].get("title", ""),
"url": url,
"snippet": snippet
})
contexts += [
{"name": c["title"], "url": c["link"], "snippet": c.get("snippet", "")}
for c in json_content["organic_results"]
]
if json_content.get("related_questions"):
for question in json_content["related_questions"]:
if question.get("source"):
url = question.get("source").get("link", "")
else:
url = ""
snippet = question.get("answer", "")
if url and snippet:
contexts.append({
"name": question.get("question", ""),
"url": url,
"snippet": snippet
})
return contexts[:REFERENCE_COUNT]
except KeyError:
logger.error(f"Error encountered: {json_content}")
return []
class RAG(Photon):
"""
Retrieval-Augmented Generation Demo from Lepton AI.
This is a minimal example to show how to build a RAG engine with Lepton AI.
It uses search engine to obtain results based on user queries, and then uses
LLM models to generate the answer as well as related questions. The results
are then stored in a KV so that it can be retrieved later.
"""
requirement_dependency = [
"openai", # for openai client usage.
]
extra_files = glob.glob("ui/**/*", recursive=True)
deployment_template = {
# All actual computations are carried out via remote apis, so
# we will use a cpu.small instance which is already enough for most of
# the work.
"resource_shape": "cpu.small",
# You most likely don't need to change this.
"env": {
# Choose the backend. Currently, we support BING and GOOGLE. For
# simplicity, in this demo, if you specify the backend as LEPTON,
# we will use the hosted serverless version of lepton search api
# at https://search-api.lepton.run/ to do the search and RAG, which
# runs the same code (slightly modified and might contain improvements)
# as this demo.
"BACKEND": "LEPTON",
# If you are using google, specify the search cx.
"GOOGLE_SEARCH_CX": "",
# Specify the LLM model you are going to use.
"LLM_MODEL": "mixtral-8x7b",
# For all the search queries and results, we will use the Lepton KV to
# store them so that we can retrieve them later. Specify the name of the
# KV here.
"KV_NAME": "search-with-lepton",
# If set to true, will generate related questions. Otherwise, will not.
"RELATED_QUESTIONS": "true",
# On the lepton platform, allow web access when you are logged in.
"LEPTON_ENABLE_AUTH_BY_COOKIE": "true",
},
# Secrets you need to have: search api subscription key, and lepton
# workspace token to query lepton's llama models.
"secret": [
# If you use BING, you need to specify the subscription key. Otherwise
# it is not needed.
"BING_SEARCH_V7_SUBSCRIPTION_KEY",
# If you use GOOGLE, you need to specify the search api key. Note that
# you should also specify the cx in the env.
"GOOGLE_SEARCH_API_KEY",
# If you use Serper, you need to specify the search api key.
"SERPER_SEARCH_API_KEY",
# If you use SearchApi, you need to specify the search api key.
"SEARCHAPI_API_KEY",
# You need to specify the workspace token to query lepton's LLM models.
"LEPTON_WORKSPACE_TOKEN",
],
}
# It's just a bunch of api calls, so our own deployment can be made massively
# concurrent.
handler_max_concurrency = 16
def local_client(self):
"""
Gets a thread-local client, so in case openai clients are not thread safe,
each thread will have its own client.
"""
import openai
thread_local = threading.local()
try:
return thread_local.client
except AttributeError:
thread_local.client = openai.OpenAI(
base_url=f"https://{self.model}.lepton.run/api/v1/",
api_key=os.environ.get("LEPTON_WORKSPACE_TOKEN")
or WorkspaceInfoLocalRecord.get_current_workspace_token(),
# We will set the connect timeout to be 10 seconds, and read/write
# timeout to be 120 seconds, in case the inference server is
# overloaded.
timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),
)
return thread_local.client
def init(self):
"""
Initializes photon configs.
"""
# First, log in to the workspace.
leptonai.api.v0.workspace.login()
self.backend = os.environ["BACKEND"].upper()
if self.backend == "LEPTON":
self.leptonsearch_client = Client(
"https://search-api.lepton.run/",
token=os.environ.get("LEPTON_WORKSPACE_TOKEN")
or WorkspaceInfoLocalRecord.get_current_workspace_token(),
stream=True,
timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),
)
elif self.backend == "BING":
self.search_api_key = os.environ["BING_SEARCH_V7_SUBSCRIPTION_KEY"]
self.search_function = lambda query: search_with_bing(
query,
self.search_api_key,
)
elif self.backend == "GOOGLE":
self.search_api_key = os.environ["GOOGLE_SEARCH_API_KEY"]
self.search_function = lambda query: search_with_google(
query,
self.search_api_key,
os.environ["GOOGLE_SEARCH_CX"],
)
elif self.backend == "SERPER":
self.search_api_key = os.environ["SERPER_SEARCH_API_KEY"]
self.search_function = lambda query: search_with_serper(
query,
self.search_api_key,
)
elif self.backend == "SEARCHAPI":
self.search_api_key = os.environ["SEARCHAPI_API_KEY"]
self.search_function = lambda query: search_with_searchapi(
query,
self.search_api_key,
)
else:
raise RuntimeError("Backend must be LEPTON, BING, GOOGLE, SERPER or SEARCHAPI.")
self.model = os.environ["LLM_MODEL"]
# An executor to carry out async tasks, such as uploading to KV.
self.executor = concurrent.futures.ThreadPoolExecutor(
max_workers=self.handler_max_concurrency * 2
)
# Create the KV to store the search results.
logger.info("Creating KV. May take a while for the first time.")
self.kv = KV(
os.environ["KV_NAME"], create_if_not_exists=True, error_if_exists=False
)
# whether we should generate related questions.
self.should_do_related_questions = to_bool(os.environ["RELATED_QUESTIONS"])
def get_related_questions(self, query, contexts):
"""
Gets related questions based on the query and context.
"""
def ask_related_questions(
questions: Annotated[
List[str],
[(
"question",
Annotated[
str, "related question to the original question and context."
],
)],
]
):
"""
ask further questions that are related to the input and output.
"""
pass
try:
response = self.local_client().chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": _more_questions_prompt.format(
context="\n\n".join([c["snippet"] for c in contexts])
),
},
{
"role": "user",
"content": query,
},
],
tools=[{
"type": "function",
"function": tool.get_tools_spec(ask_related_questions),
}],
max_tokens=512,
)
related = response.choices[0].message.tool_calls[0].function.arguments
if isinstance(related, str):
related = json.loads(related)
logger.trace(f"Related questions: {related}")
return related["questions"][:5]
except Exception as e:
# For any exceptions, we will just return an empty list.
logger.error(
"encountered error while generating related questions:"
f" {e}\n{traceback.format_exc()}"
)
return []
def _raw_stream_response(
self, contexts, llm_response, related_questions_future
) -> Generator[str, None, None]:
"""
A generator that yields the raw stream response. You do not need to call
this directly. Instead, use the stream_and_upload_to_kv which will also
upload the response to KV.
"""
# First, yield the contexts.
yield json.dumps(contexts)
yield "\n\n__LLM_RESPONSE__\n\n"
# Second, yield the llm response.
if not contexts:
# Prepend a warning to the user
yield (
"(The search engine returned nothing for this query. Please take the"
" answer with a grain of salt.)\n\n"
)
for chunk in llm_response:
if chunk.choices:
yield chunk.choices[0].delta.content or ""
# Third, yield the related questions. If any error happens, we will just
# return an empty list.
if related_questions_future is not None:
related_questions = related_questions_future.result()
try:
result = json.dumps(related_questions)
except Exception as e:
logger.error(f"encountered error: {e}\n{traceback.format_exc()}")
result = "[]"
yield "\n\n__RELATED_QUESTIONS__\n\n"
yield result
def stream_and_upload_to_kv(
self, contexts, llm_response, related_questions_future, search_uuid
) -> Generator[str, None, None]:
"""
Streams the result and uploads to KV.
"""
# First, stream and yield the results.
all_yielded_results = []
for result in self._raw_stream_response(
contexts, llm_response, related_questions_future
):
all_yielded_results.append(result)
yield result
# Second, upload to KV. Note that if uploading to KV fails, we will silently
# ignore it, because we don't want to affect the user experience.
_ = self.executor.submit(self.kv.put, search_uuid, "".join(all_yielded_results))
@Photon.handler(method="POST", path="/query")
def query_function(
self,
query: str,
search_uuid: str,
generate_related_questions: Optional[bool] = True,
) -> StreamingResponse:
"""
Query the search engine and returns the response.
The query can have the following fields:
- query: the user query.
- search_uuid: a uuid that is used to store or retrieve the search result. If
the uuid does not exist, generate and write to the kv. If the kv
fails, we generate regardless, in favor of availability. If the uuid
exists, return the stored result.
- generate_related_questions: if set to false, will not generate related
questions. Otherwise, will depend on the environment variable
RELATED_QUESTIONS. Default: true.
"""
# Note that, if uuid exists, we don't check if the stored query is the same
# as the current query, and simply return the stored result. This is to enable
# the user to share a searched link to others and have others see the same result.
if search_uuid:
try:
result = self.kv.get(search_uuid)
def str_to_generator(result: str) -> Generator[str, None, None]:
yield result
return StreamingResponse(str_to_generator(result))
except KeyError:
logger.info(f"Key {search_uuid} not found, will generate again.")
except Exception as e:
logger.error(
f"KV error: {e}\n{traceback.format_exc()}, will generate again."
)
else:
raise HTTPException(status_code=400, detail="search_uuid must be provided.")
if self.backend == "LEPTON":
# delegate to the lepton search api.
result = self.leptonsearch_client.query(
query=query,
search_uuid=search_uuid,
generate_related_questions=generate_related_questions,
)
return StreamingResponse(content=result, media_type="text/html")
# First, do a search query.
query = query or _default_query
# Basic attack protection: remove "[INST]" or "[/INST]" from the query
query = re.sub(r"\[/?INST\]", "", query)
contexts = self.search_function(query)
system_prompt = _rag_query_text.format(
context="\n\n".join(
[f"[[citation:{i+1}]] {c['snippet']}" for i, c in enumerate(contexts)]
)
)
try:
client = self.local_client()
llm_response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query},
],
max_tokens=1024,
stop=stop_words,
stream=True,
temperature=0.9,
)
if self.should_do_related_questions and generate_related_questions:
# While the answer is being generated, we can start generating
# related questions as a future.
related_questions_future = self.executor.submit(
self.get_related_questions, query, contexts
)
else:
related_questions_future = None
except Exception as e:
logger.error(f"encountered error: {e}\n{traceback.format_exc()}")
return HTMLResponse("Internal server error.", 503)
return StreamingResponse(
self.stream_and_upload_to_kv(
contexts, llm_response, related_questions_future, search_uuid
),
media_type="text/html",
)
@Photon.handler(mount=True)
def ui(self):
return StaticFiles(directory="ui")
@Photon.handler(method="GET", path="/")
def index(self) -> RedirectResponse:
"""
Redirects "/" to the ui page.
"""
return RedirectResponse(url="/ui/index.html")
if __name__ == "__main__":
rag = RAG()
rag.launch()
================================================
FILE: web/.eslintrc.json
================================================
{
"plugins": ["unused-imports"],
"extends": [
"next/core-web-vitals",
"plugin:prettier/recommended"
],
"rules": {
"unused-imports/no-unused-imports": "error"
}
}
================================================
FILE: web/next.config.mjs
================================================
export default (phase, { defaultConfig }) => {
const env = process.env.NODE_ENV;
/**
* @type {import("next").NextConfig}
*/
if (env === "production") {
return {
output: "export",
assetPrefix: "/ui/",
basePath: "/ui",
distDir: "../ui"
};
} else {
return {
async rewrites() {
return [
{
source: "/query",
destination: "http://localhost:8080/query" // Proxy to Backend
}
];
}
};
}
}
================================================
FILE: web/package.json
================================================
{
"name": "search",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@next/third-parties": "^14.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@tailwindcss/forms": "^0.5.7",
"@upstash/ratelimit": "^1.0.0",
"@vercel/kv": "^1.0.1",
"clsx": "^2.1.0",
"headlessui": "^0.0.0",
"lucide-react": "^0.309.0",
"mdast-util-from-markdown": "^2.0.0",
"nanoid": "^5.0.4",
"next": "14.2.22",
"react": "^18",
"react-dom": "^18",
"react-markdown": "^9.0.1",
"tailwind-merge": "^2.2.0",
"unist-builder": "^4.0.0"
},
"devDependencies": {
"@tailwindcss/typography": "^0.5.10",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.0.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-unused-imports": "^3.0.0",
"postcss": "^8",
"prettier": "^3.1.0",
"tailwindcss": "^3.3.0",
"typescript": "^5"
}
}
================================================
FILE: web/postcss.config.js
================================================
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
================================================
FILE: web/src/app/components/answer.tsx
================================================
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/app/components/popover";
import { Skeleton } from "@/app/components/skeleton";
import { Wrapper } from "@/app/components/wrapper";
import { Source } from "@/app/interfaces/source";
import { BookOpenText } from "lucide-react";
import { FC } from "react";
import Markdown from "react-markdown";
export const Answer: FC<{ markdown: string; sources: Source[] }> = ({
markdown,
sources,
}) => {
return (
Answer
>
}
content={
markdown ? (
{
if (!props.href) return <>>;
const source = sources[+props.href - 1];
if (!source) return <>>;
return (
{props.href}