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 |
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. You also need to replace the `search_with_google` function in `rag_chain.py` with `search_with_bing` in `search_with_lepton.py`. Change the service keys accordingly.
22 |
23 | ### Google Search
24 | 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://www.serper.dev) from Serper, or opt for the [Programmable Search Engine](https://developers.google.com/custom-search) provided by Google. I have implemented **Programmable Search Engine** in `rag_chain.py`. But you could change it to other ones (see section Bing Search).
25 |
26 | ## Setup LLM and Search Service
27 |
28 | > [!NOTE]
29 | > I don't get access to powerful GPUs :( so I use the [NVIDIA AI Foundation Endpoints](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/ai-foundation/models/mixtral-8x7b/api). But I recommend you replace it with [ollama](https://python.langchain.com/docs/integrations/llms/ollama) if you insist to have everthing set up locally.
30 | > Set up your service keys starting line 23 in `rag_chain.py` like this:
31 | ```python
32 | # ===========================================================
33 | # set service keys
34 | NVAPI_KEY = 'nvapi-xxx'
35 | SEARCH_API_KEY_GOOGLE = "xxx"
36 | SEARCH_ID_GOOGLE = "xxx" # cx parameter
37 | ```
38 |
39 | > Running the following commands to set up the environment.
40 |
41 | ```shell
42 | pip install langchain
43 | pip install loguru
44 | pip install --upgrade --quiet langchain-nvidia-ai-endpoints
45 | pip install fastapi
46 | pip install "uvicorn[standard]"
47 | ```
48 |
49 |
50 | ## Build
51 |
52 |
53 | 1. Build web
54 | ```shell
55 | cd web && npm install && npm run build
56 | ```
57 | 2. Run server
58 | ```shell
59 | python search_with_langchain.py
60 | ```
61 |
62 | 3. Visit your local conversational search engine at http://localhost:8080/ !
63 |
64 | ## Error Handling
65 |
66 | 1. prettier/prettier
67 |
68 | If you have encounter something like
69 | ```shell
70 | Error: Delete `␍` prettier/prettier
71 | ```
72 | during build, visit `web/.eslintrc.json` and add a line to turn prettier/prettier off like this. (That's how I get around this anyway.)
73 | ```json
74 | "rules": {
75 | "unused-imports/no-unused-imports": "error",
76 | "prettier/prettier": "off"
77 | }
78 | ```
--------------------------------------------------------------------------------
/web/src/app/icon.svg:
--------------------------------------------------------------------------------
1 |
23 |
--------------------------------------------------------------------------------
/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 | ### SearchApi
21 |
22 | 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.
23 |
24 | ### Lepton Demo API
25 |
26 | 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.
27 |
28 |
29 | ## Deployment Configurations
30 |
31 | Here are the configurations you can set for your deployment:
32 | * Name: The name of your deployment, like "my-search"
33 | * 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.
34 |
35 | Then, set the following environmental variables.
36 |
37 | * `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`.
38 | * `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.
39 | * `KV_NAME`: the Lepton KV to use to store the search results. You can use the default `search-with-lepton`.
40 | * `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.
41 | * `GOOGLE_SEARCH_CX`: if you are using google, specify the search cx. Otherwise, leave it empty.
42 | * `LEPTON_ENABLE_AUTH_BY_COOKIE`: this is to allow web UI access to the deployment. Set it to `true`.
43 |
44 | In addition, you will need to set the following secrets:
45 | * `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).
46 | * `BING_SEARCH_V7_SUBSCRIPTION_KEY`: if you are using Bing, you need to specify the subscription key. Otherwise it is not needed.
47 | * `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.
48 | * `SEARCHAPI_API_KEY`: if you are using SearchApi, a 3rd party Google Search API, you need to specify the api key.
49 |
50 | 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.
51 |
52 | Once the status is turned into `Ready`, click the URL on the deployment card to access it. Enjoy!
53 |
--------------------------------------------------------------------------------
/.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 |
107 | )
108 | }
109 | >
110 | );
111 | };
112 |
--------------------------------------------------------------------------------
/search_with_langchain.py:
--------------------------------------------------------------------------------
1 | import concurrent.futures
2 | import json
3 | import re
4 | from typing import Annotated, List, Generator, Optional
5 |
6 | from fastapi import FastAPI, HTTPException, Response
7 | from fastapi.responses import HTMLResponse, StreamingResponse, RedirectResponse
8 | from fastapi.staticfiles import StaticFiles
9 |
10 |
11 | from loguru import logger
12 |
13 | # 导入您的自定义 agent
14 | from rag_chain import search_with_llm
15 |
16 |
17 | # If the user did not provide a query, we will use this default query.
18 | _default_query = "When was breath of the wild first released?"
19 |
20 | # 创建一个 FastAPI 应用程序实例
21 |
22 |
23 |
24 | # 定义pydantic模型
25 | from pydantic import BaseModel
26 | from typing import Optional
27 | class QueryRequest(BaseModel):
28 | query: str
29 | search_uuid: str
30 | generate_related_questions: Optional[bool] = True
31 |
32 | # 定义fastapi中间件
33 | from fastapi import FastAPI, Request
34 | from starlette.middleware.base import BaseHTTPMiddleware
35 | from pydantic import ValidationError
36 |
37 | class RequestLoggingMiddleware(BaseHTTPMiddleware):
38 | async def dispatch(self, request: Request, call_next):
39 | # 打印接收到的请求信息
40 | logger.info(f"Request path: {request.url.path}")
41 | logger.info(f"Request method: {request.method}")
42 | # 打印请求头
43 | for name, value in request.headers.items():
44 | logger.info(f"Header {name}: {value}")
45 |
46 | # # 读取请求体
47 | body = await request.body()
48 | if body:
49 | # 打印请求体内容
50 | logger.info(f"Request body: \n {body}")
51 | # 尝试解析JSON内容(如果可能的话)
52 | try:
53 | body_json = json.loads(body.decode("utf-8"))
54 | logger.info(f"JSON parsed body: \n {body_json}")
55 | except json.JSONDecodeError:
56 | logger.info("Request body is not JSON")
57 |
58 | # 由于请求体已经被读取,需要将其内容放回原处
59 | request._body = body
60 |
61 | # 继续处理请求
62 | response = await call_next(request)
63 |
64 | return response
65 |
66 | app = FastAPI()
67 | app.add_middleware(RequestLoggingMiddleware)
68 | # An executor to carry out async tasks.
69 | executor = concurrent.futures.ThreadPoolExecutor(max_workers=16)
70 |
71 | # whether we should generate related questions.
72 | should_do_related_questions = True
73 |
74 |
75 | def _raw_stream_response(results) -> Generator[str, None, None]:
76 | """
77 | A generator that yields the raw stream response from processed results.
78 |
79 | Parameters:
80 | - results: A list of tuples, each containing a step name and data from the `search_with_llm` execution.
81 | """
82 | for step, data in results:
83 | if step == "contexts":
84 | # Yield the contexts as a JSON string
85 | yield json.dumps(data) + "\n\n__LLM_RESPONSE__\n\n"
86 | elif step == "llm_response":
87 | # Prepend a warning if necessary, then yield the LLM response
88 | if not data:
89 | yield "(The search engine returned nothing for this query. Please take the answer with a grain of salt.)\n\n"
90 | yield data
91 | elif step == "related_questions":
92 | # Try to dump the related questions as JSON, handle exceptions
93 | try:
94 | result = json.dumps(data)
95 | except Exception as e:
96 | result = "[]"
97 | yield "\n\n__RELATED_QUESTIONS__\n\n" + result
98 |
99 |
100 | @app.post("/query")
101 | async def query_function(body: QueryRequest) -> StreamingResponse:
102 | # def query_function(query: str, search_uuid: str, generate_related_questions: Optional[bool] = True) -> StreamingResponse:
103 | """
104 | Query the search engine and returns the response.
105 |
106 | The query can have the following fields:
107 | - query: the user query.
108 | - generate_related_questions: if set to false, will not generate related
109 | questions. Otherwise, will depend on the environment variable
110 | RELATED_QUESTIONS. Default: true.
111 | """
112 | query = body.query
113 | search_uuid = body.search_uuid
114 | generate_related_questions = body.generate_related_questions
115 | logger.info(f"Received query: {query}")
116 | logger.info(f"Received search_uuid: {search_uuid}")
117 | logger.info(f"Received generate_related_questions: {generate_related_questions}")
118 | query = query or _default_query
119 | # Basic attack protection: remove "[INST]" or "[/INST]" from the query
120 | query = re.sub(r"\[/?INST\]", "", query)
121 |
122 | results = search_with_llm(query, generate_related_questions)
123 |
124 | return StreamingResponse(_raw_stream_response(results), media_type="text/plain")
125 |
126 |
127 |
128 | app.mount("/ui", StaticFiles(directory="ui"), name="static")
129 |
130 | @app.get("/")
131 | async def index(request: Request):
132 | """
133 | Redirects "/" to the ui page.
134 | """
135 | return RedirectResponse(url="/ui/index.html")
136 |
137 |
138 | if __name__ == "__main__":
139 | import uvicorn
140 | logger.info("Running LLM Server...")
141 | uvicorn.run(app, host="0.0.0.0", port=8080)
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/rag_chain.py:
--------------------------------------------------------------------------------
1 | # get Nvidia API key
2 | import getpass
3 | import os
4 | # Google Search
5 | import requests
6 | from fastapi import HTTPException
7 | from loguru import logger
8 | from langchain.tools import Tool
9 | # Debug
10 | from langchain.callbacks.base import BaseCallbackHandler
11 | # Search Query Chain
12 | from langchain_core.prompts import ChatPromptTemplate
13 | from langchain_core.output_parsers import JsonOutputParser
14 | from langchain_core.pydantic_v1 import BaseModel, Field
15 | # Answer Chain
16 | from langchain_core.output_parsers import StrOutputParser
17 | # Related Question Chain
18 | from langchain.output_parsers import NumberedListOutputParser
19 | import json
20 |
21 | # ===========================================================
22 | # set service keys
23 | NVAPI_KEY = 'nvapi-xxx'
24 | SEARCH_API_KEY_GOOGLE = "xxx" # [Caution] Private Key here !
25 | SEARCH_ID_GOOGLE = "xxx" # cx parameter
26 |
27 |
28 | # ===========================================================
29 | # get Nvidia API key
30 |
31 | if not os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"):
32 | assert NVAPI_KEY.startswith("nvapi-"), f"{NVAPI_KEY[:5]}... is not a valid key"
33 | os.environ["NVIDIA_API_KEY"] = NVAPI_KEY
34 |
35 | # Core LC Chat Interface
36 | from langchain_nvidia_ai_endpoints import ChatNVIDIA
37 |
38 | llm = ChatNVIDIA(model="mixtral_8x7b")
39 |
40 |
41 | # ===========================================================
42 | # Google Search Tool
43 | # -----------------------------------------------------------
44 | # Constant values for the RAG model.
45 |
46 | # Search engine related. You don't really need to change this.
47 | GOOGLE_SEARCH_ENDPOINT = "https://customsearch.googleapis.com/customsearch/v1"
48 |
49 |
50 | # Specify the number of references from the search engine you want to use.
51 | # 8 is usually a good number.
52 | REFERENCE_COUNT = 8
53 |
54 | # Specify the default timeout for the search engine. If the search engine
55 | # does not respond within this time, we will return an error.
56 | DEFAULT_SEARCH_ENGINE_TIMEOUT = 5
57 | # -----------------------------------------------------------
58 | def search_with_google(query: str, subscription_key: str, cx: str):
59 | """
60 | Search with google and return the contexts.
61 | """
62 | params = {
63 | "key": subscription_key,
64 | "cx": cx,
65 | "q": query,
66 | "num": REFERENCE_COUNT,
67 | }
68 | response = requests.get(
69 | GOOGLE_SEARCH_ENDPOINT, params=params, timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT
70 | )
71 | if not response.ok:
72 | logger.error(f"{response.status_code} {response.text}")
73 | raise HTTPException(response.status_code, "Search engine error.")
74 | json_content = response.json()
75 | try:
76 | contexts = json_content["items"][:REFERENCE_COUNT]
77 | # Renaming 'link' to 'url' and 'displayLink' to 'displayUrl' for each context
78 | for context in contexts:
79 | if 'link' in context:
80 | context['url'] = context.pop('link')
81 | if 'displayLink' in context:
82 | context['displayUrl'] = context.pop('displayLink')
83 | if 'title' in context:
84 | context['name'] = context.pop('title')
85 | if 'pagemap' in context:
86 | if 'metatags' in context['pagemap']:
87 | # Extracting the og:image URL, width, and height
88 | og_image_url = context['pagemap']['metatags'][0].get('og:image', '')
89 | og_image_width = context['pagemap']['metatags'][0].get('og:image:width', '')
90 | og_image_height = context['pagemap']['metatags'][0].get('og:image:height', '')
91 |
92 | # Modifying the data structure to add primaryImageOfPage at the top level
93 | context['primaryImageOfPage'] = {
94 | 'thumbnailUrl': og_image_url,
95 | 'width': og_image_width,
96 | 'height': og_image_height,
97 | # Assuming imageId is not available in the original data, and og:image URL is used as a placeholder
98 | 'imageId': og_image_url.split('/')[-1] # Extracting the filename as an imageId
99 | }
100 | except KeyError:
101 | logger.error(f"Error encountered: {json_content}")
102 | return []
103 | return contexts
104 |
105 | def prepare_search_results(contexts, get_raw = False):
106 | """
107 | Prepare search results for the agent and frontend display.
108 |
109 | Args:
110 | contexts (list): List of search result contexts from the Bing API.
111 |
112 | Returns:
113 | tuple: A tuple containing two items:
114 | - agent_context (str): Search result contexts formatted for the agent.
115 | - frontend_contexts (list): Original search result contexts for frontend display.
116 | """
117 | # agent_context = "\n\n".join([f"[[citation: {c['title']}]] {c['snippet']}" for c in contexts])
118 | agent_context = "\n\n".join([f"[[citation:{i+1}]] {c['snippet']}" for i, c in enumerate(contexts)])
119 | frontend_contexts = contexts
120 | if get_raw:
121 | return agent_context, frontend_contexts
122 | return agent_context
123 |
124 | search_tool = Tool(
125 | name="Google Search",
126 | func=lambda query: prepare_search_results(search_with_google(query, SEARCH_API_KEY_GOOGLE, SEARCH_ID_GOOGLE)),
127 | description="A search tool that uses the Google search engine to find relevant information on the web.",
128 | # coroutine=SerpAPIWrapper()
129 | )
130 |
131 | tools = [search_tool]
132 |
133 |
134 | # ===========================================================
135 | # Debug
136 |
137 | class AgentVerbose(BaseCallbackHandler):
138 | async def on_llm_start(self, serialized, prompts, **kwargs):
139 | """Run when LLM starts running."""
140 | print(f"> LLM")
141 | # print(f"Prompt: {prompts}")
142 | for prompt in prompts:
143 | print(prompt)
144 |
145 | async def on_llm_end(self, response, **kwargs):
146 | """Run when LLM ends running."""
147 | print(f"< LLM")
148 | # print(f"response: {response}")
149 | if response.generations:
150 | for generation in response.generations:
151 | for chunk in generation:
152 | if chunk.text:
153 | print(chunk.text)
154 |
155 | async def on_chain_error(self, error, **kwargs):
156 | """Run when chain errors."""
157 | print(f"> Chain **Error**")
158 | print(f"error: {str(error)}")
159 |
160 | async def on_agent_action(self, action, **kwargs):
161 | """Run on agent action."""
162 | print(f"> Agent")
163 | print(f"action: {action}")
164 |
165 | async def on_agent_finish(self, finish, **kwargs):
166 | """Run on agent end."""
167 | print(f"< Agent")
168 | print(f"finish: {finish}")
169 |
170 | async def on_tool_start(self, serialized, input_str, **kwargs):
171 | """Run when tool starts running."""
172 | print(f"> Tool")
173 | print(f"input: {input_str}")
174 |
175 | async def on_tool_end(self, output, **kwargs):
176 | """Run when tool ends running."""
177 | print(f"< Tool")
178 | print(f"output: {output}")
179 |
180 | async def on_retriever_start(self, serialized, query, **kwargs):
181 | """Run on retriever start."""
182 | print(f"> Retriever")
183 | print(f"query: {query}")
184 |
185 | async def on_retriever_end(self, documents, **kwargs):
186 | """Run on retriever end."""
187 | print(f"< Retriever")
188 | print(f"documents: {documents}")
189 |
190 |
191 | # ===========================================================
192 | # Search with LLM
193 | def search_with_llm(search_query, generate_related_questions=True):
194 | """Search with llm"""
195 | # -------------------------------------------------------
196 | # Search Query Chain
197 | # Define your desired data structure.
198 | class SearchQuery(BaseModel):
199 | tool: str = Field(description="selected search tool name")
200 | query: str = Field(description="generate a search query")
201 | query_parser = JsonOutputParser(pydantic_object=SearchQuery)
202 |
203 | # Define prompt template
204 | search_prompt = ChatPromptTemplate.from_messages([
205 | ("system", "Given the following user instructions, select a search tool and generate a search query to look up in order to get information relevant to the conversation. Use the same language as `Human`. You have access to the following tools: \n{tools}\n\n{format_instructions}"),
206 | ("user", "{input}")
207 | ])
208 | # Partially fill the prompt with search tool info
209 | search_tools = "Google Search: A search tool that uses the Google search engine to find relevant information on the web."
210 | search_prompt = search_prompt.partial(
211 | tools=search_tools
212 | )
213 | # Partially fill the prompt with format instructions.
214 | search_prompt = search_prompt.partial(format_instructions=query_parser.get_format_instructions())
215 | # print(prompt.messages)
216 |
217 | query_gen_chain = search_prompt | llm | query_parser
218 | result_query = query_gen_chain.invoke({"input": search_query}, config={'callbacks': [AgentVerbose()]})
219 |
220 | # -------------------------------------------------------
221 | # Search the web
222 | agent_context, frontend_contexts = prepare_search_results(search_with_google(result_query['query'], SEARCH_API_KEY_GOOGLE, SEARCH_ID_GOOGLE), get_raw=True)
223 | yield "contexts", frontend_contexts
224 | # -------------------------------------------------------
225 | # Answer Chain
226 |
227 | # Define prompt template
228 | answer_prompt = ChatPromptTemplate.from_messages([
229 | ("system", """
230 | You are a large language AI assistant built by Neutrino 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.
231 |
232 | Your answer must be correct, accurate and written by an expert using an unbiased and professional tone. 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.
233 |
234 | 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.
235 |
236 | Here are the set of contexts:
237 | ```
238 | {context}
239 | ```
240 | """),
241 | ("user", "{input}")
242 | ])
243 |
244 | # Partially fill the prompt with context
245 | answer_prompt = answer_prompt.partial(
246 | context=agent_context
247 | )
248 |
249 | str_parser = StrOutputParser()
250 |
251 | answer_chain = answer_prompt | llm | str_parser
252 | result = answer_chain.invoke({"input": search_query}, config={'callbacks': [AgentVerbose()]})
253 | yield "llm_response", result
254 | # -------------------------------------------------------
255 | # Generate Related Questions
256 | if generate_related_questions:
257 | # Define prompt template
258 | related_q_prompt = ChatPromptTemplate.from_messages([
259 | ("system", """
260 | 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 `Human`.
261 |
262 | Here are the contexts of the question:
263 | ```
264 | {context}
265 | ```
266 | 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. Do NOT include comma in each question. \n\n{format_instructions}
267 | """),
268 | ("user", "{input}")
269 | ])
270 |
271 | # Partially fill the prompt with context
272 | related_q_prompt = related_q_prompt.partial(
273 | context=agent_context
274 | )
275 |
276 | # "hi, bye" → ['hi', 'bye']
277 | num_parser = NumberedListOutputParser()
278 | # Partially fill the prompt with format instructions.
279 | related_q_prompt = related_q_prompt.partial(format_instructions=num_parser.get_format_instructions())
280 |
281 | associate_chain = related_q_prompt | llm | num_parser
282 |
283 | try:
284 | questions_list = associate_chain.invoke({"input": search_query}, config={'callbacks': [AgentVerbose()]})
285 | # questions_list = associate_chain.invoke({"input": search_query})
286 | # 将每个问题转换为一个字典,键为"question"
287 | related_questions = [{"question": question} for question in questions_list]
288 | # 转换为JSON格式的字符串
289 | # related_questions = json.dumps(questions_json)
290 | except Exception as e:
291 | related_questions = '[]'
292 | yield "related_questions", related_questions
293 | # return frontend_contexts, result, related_questions
294 |
295 | # return frontend_contexts, result
296 |
297 | if __name__ == "__main__":
298 | def print_test_sub(test_sub):
299 | """Print test infomations."""
300 | print("\n===========================================================")
301 | print(f"> Test {test_sub}...")
302 | print("-----------------------------------------------------------")
303 |
304 | # -------------------------------------------------
305 | # Test llm
306 | print_test_sub("NVIDIA AI Foundation Endpoints Connection")
307 | llm_query = "tell me a joke."
308 | print("> Query: ", llm_query)
309 | for chunks in llm.stream(llm_query):
310 | print(chunks.content, end="")
311 |
312 | # -------------------------------------------------
313 | # Test Search
314 | print_test_sub("Google Search Tool")
315 | search_query = "what year was breath of the wild released?"
316 | contexts = prepare_search_results(search_with_google(search_query, SEARCH_API_KEY_GOOGLE, SEARCH_ID_GOOGLE))
317 | # contexts = "\n\n".join([f"[[citation: {c['title']}]] {c['snippet']}" for i, c in enumerate(results)])
318 | print("> Query: ", search_query)
319 | print()
320 | print(contexts)
321 |
322 | # --------------------------------------------------
323 | # Test Answer Chain
324 | print_test_sub("Answer Chain")
325 | search_query = "when was breath of the wild first released?"
326 | frontend_contexts, result, related_questions = search_with_llm(search_query)
327 | print("> frontend_contexts:\n", frontend_contexts)
328 | print("> frontend_contexts:\n", result)
329 | print("> frontend_contexts:\n", related_questions)
330 |
331 |
--------------------------------------------------------------------------------
/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 | SEARCHAPI_SEARCH_ENDPOINT = "https://www.searchapi.io/api/v1/search"
34 |
35 | # Specify the number of references from the search engine you want to use.
36 | # 8 is usually a good number.
37 | REFERENCE_COUNT = 8
38 |
39 | # Specify the default timeout for the search engine. If the search engine
40 | # does not respond within this time, we will return an error.
41 | DEFAULT_SEARCH_ENGINE_TIMEOUT = 5
42 |
43 |
44 | # If the user did not provide a query, we will use this default query.
45 | _default_query = "Who said 'live long and prosper'?"
46 |
47 | # This is really the most important part of the rag model. It gives instructions
48 | # to the model on how to generate the answer. Of course, different models may
49 | # behave differently, and we haven't tuned the prompt to make it optimal - this
50 | # is left to you, application creators, as an open problem.
51 | _rag_query_text = """
52 | 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.
53 |
54 | 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.
55 |
56 | 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.
57 |
58 | Here are the set of contexts:
59 |
60 | {context}
61 |
62 | Remember, don't blindly repeat the contexts verbatim. And here is the user question:
63 | """
64 |
65 | # A set of stop words to use - this is not a complete set, and you may want to
66 | # add more given your observation.
67 | stop_words = [
68 | "<|im_end|>",
69 | "[End]",
70 | "[end]",
71 | "\nReferences:\n",
72 | "\nSources:\n",
73 | "End.",
74 | ]
75 |
76 | # This is the prompt that asks the model to generate related questions to the
77 | # original question and the contexts.
78 | # Ideally, one want to include both the original question and the answer from the
79 | # model, but we are not doing that here: if we need to wait for the answer, then
80 | # the generation of the related questions will usually have to start only after
81 | # the whole answer is generated. This creates a noticeable delay in the response
82 | # time. As a result, and as you will see in the code, we will be sending out two
83 | # consecutive requests to the model: one for the answer, and one for the related
84 | # questions. This is not ideal, but it is a good tradeoff between response time
85 | # and quality.
86 | _more_questions_prompt = """
87 | 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.
88 |
89 | Here are the contexts of the question:
90 |
91 | {context}
92 |
93 | 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:
94 | """
95 |
96 |
97 | def search_with_bing(query: str, subscription_key: str):
98 | """
99 | Search with bing and return the contexts.
100 | """
101 | params = {"q": query, "mkt": BING_MKT}
102 | response = requests.get(
103 | BING_SEARCH_V7_ENDPOINT,
104 | headers={"Ocp-Apim-Subscription-Key": subscription_key},
105 | params=params,
106 | timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,
107 | )
108 | if not response.ok:
109 | logger.error(f"{response.status_code} {response.text}")
110 | raise HTTPException(response.status_code, "Search engine error.")
111 | json_content = response.json()
112 | try:
113 | contexts = json_content["webPages"]["value"][:REFERENCE_COUNT]
114 | except KeyError:
115 | logger.error(f"Error encountered: {json_content}")
116 | return []
117 | return contexts
118 |
119 |
120 | def search_with_google(query: str, subscription_key: str, cx: str):
121 | """
122 | Search with google and return the contexts.
123 | """
124 | params = {
125 | "key": subscription_key,
126 | "cx": cx,
127 | "q": query,
128 | "num": REFERENCE_COUNT,
129 | }
130 | response = requests.get(
131 | GOOGLE_SEARCH_ENDPOINT, params=params, timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT
132 | )
133 | if not response.ok:
134 | logger.error(f"{response.status_code} {response.text}")
135 | raise HTTPException(response.status_code, "Search engine error.")
136 | json_content = response.json()
137 | try:
138 | contexts = json_content["items"][:REFERENCE_COUNT]
139 | except KeyError:
140 | logger.error(f"Error encountered: {json_content}")
141 | return []
142 | return contexts
143 |
144 |
145 | def search_with_serper(query: str, subscription_key: str):
146 | """
147 | Search with serper and return the contexts.
148 | """
149 | payload = json.dumps({
150 | "q": query,
151 | "num": (
152 | REFERENCE_COUNT
153 | if REFERENCE_COUNT % 10 == 0
154 | else (REFERENCE_COUNT // 10 + 1) * 10
155 | ),
156 | })
157 | headers = {"X-API-KEY": subscription_key, "Content-Type": "application/json"}
158 | logger.info(
159 | f"{payload} {headers} {subscription_key} {query} {SERPER_SEARCH_ENDPOINT}"
160 | )
161 | response = requests.post(
162 | SERPER_SEARCH_ENDPOINT,
163 | headers=headers,
164 | data=payload,
165 | timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,
166 | )
167 | if not response.ok:
168 | logger.error(f"{response.status_code} {response.text}")
169 | raise HTTPException(response.status_code, "Search engine error.")
170 | json_content = response.json()
171 | try:
172 | # convert to the same format as bing/google
173 | contexts = []
174 | if json_content.get("knowledgeGraph"):
175 | url = json_content["knowledgeGraph"].get("descriptionUrl") or json_content["knowledgeGraph"].get("website")
176 | snippet = json_content["knowledgeGraph"].get("description")
177 | if url and snippet:
178 | contexts.append({
179 | "name": json_content["knowledgeGraph"].get("title",""),
180 | "url": url,
181 | "snippet": snippet
182 | })
183 | if json_content.get("answerBox"):
184 | url = json_content["answerBox"].get("url")
185 | snippet = json_content["answerBox"].get("snippet") or json_content["answerBox"].get("answer")
186 | if url and snippet:
187 | contexts.append({
188 | "name": json_content["answerBox"].get("title",""),
189 | "url": url,
190 | "snippet": snippet
191 | })
192 | contexts += [
193 | {"name": c["title"], "url": c["link"], "snippet": c.get("snippet","")}
194 | for c in json_content["organic"]
195 | ]
196 | return contexts[:REFERENCE_COUNT]
197 | except KeyError:
198 | logger.error(f"Error encountered: {json_content}")
199 | return []
200 |
201 | def search_with_searchapi(query: str, subscription_key: str):
202 | """
203 | Search with SearchApi.io and return the contexts.
204 | """
205 | payload = {
206 | "q": query,
207 | "engine": "google",
208 | "num": (
209 | REFERENCE_COUNT
210 | if REFERENCE_COUNT % 10 == 0
211 | else (REFERENCE_COUNT // 10 + 1) * 10
212 | ),
213 | }
214 | headers = {"Authorization": f"Bearer {subscription_key}", "Content-Type": "application/json"}
215 | logger.info(
216 | f"{payload} {headers} {subscription_key} {query} {SEARCHAPI_SEARCH_ENDPOINT}"
217 | )
218 | response = requests.get(
219 | SEARCHAPI_SEARCH_ENDPOINT,
220 | headers=headers,
221 | params=payload,
222 | timeout=30,
223 | )
224 | if not response.ok:
225 | logger.error(f"{response.status_code} {response.text}")
226 | raise HTTPException(response.status_code, "Search engine error.")
227 | json_content = response.json()
228 | try:
229 | # convert to the same format as bing/google
230 | contexts = []
231 |
232 | if json_content.get("answer_box"):
233 | if json_content["answer_box"].get("organic_result"):
234 | title = json_content["answer_box"].get("organic_result").get("title", "")
235 | url = json_content["answer_box"].get("organic_result").get("link", "")
236 | if json_content["answer_box"].get("type") == "population_graph":
237 | title = json_content["answer_box"].get("place", "")
238 | url = json_content["answer_box"].get("explore_more_link", "")
239 |
240 | title = json_content["answer_box"].get("title", "")
241 | url = json_content["answer_box"].get("link")
242 | snippet = json_content["answer_box"].get("answer") or json_content["answer_box"].get("snippet")
243 |
244 | if url and snippet:
245 | contexts.append({
246 | "name": title,
247 | "url": url,
248 | "snippet": snippet
249 | })
250 |
251 | if json_content.get("knowledge_graph"):
252 | if json_content["knowledge_graph"].get("source"):
253 | url = json_content["knowledge_graph"].get("source").get("link", "")
254 |
255 | url = json_content["knowledge_graph"].get("website", "")
256 | snippet = json_content["knowledge_graph"].get("description")
257 |
258 | if url and snippet:
259 | contexts.append({
260 | "name": json_content["knowledge_graph"].get("title", ""),
261 | "url": url,
262 | "snippet": snippet
263 | })
264 |
265 | contexts += [
266 | {"name": c["title"], "url": c["link"], "snippet": c.get("snippet", "")}
267 | for c in json_content["organic_results"]
268 | ]
269 |
270 | if json_content.get("related_questions"):
271 | for question in json_content["related_questions"]:
272 | if question.get("source"):
273 | url = question.get("source").get("link", "")
274 | else:
275 | url = ""
276 |
277 | snippet = question.get("answer", "")
278 |
279 | if url and snippet:
280 | contexts.append({
281 | "name": question.get("question", ""),
282 | "url": url,
283 | "snippet": snippet
284 | })
285 |
286 | return contexts[:REFERENCE_COUNT]
287 | except KeyError:
288 | logger.error(f"Error encountered: {json_content}")
289 | return []
290 |
291 | class RAG(Photon):
292 | """
293 | Retrieval-Augmented Generation Demo from Lepton AI.
294 |
295 | This is a minimal example to show how to build a RAG engine with Lepton AI.
296 | It uses search engine to obtain results based on user queries, and then uses
297 | LLM models to generate the answer as well as related questions. The results
298 | are then stored in a KV so that it can be retrieved later.
299 | """
300 |
301 | requirement_dependency = [
302 | "openai", # for openai client usage.
303 | ]
304 |
305 | extra_files = glob.glob("ui/**/*", recursive=True)
306 |
307 | deployment_template = {
308 | # All actual computations are carried out via remote apis, so
309 | # we will use a cpu.small instance which is already enough for most of
310 | # the work.
311 | "resource_shape": "cpu.small",
312 | # You most likely don't need to change this.
313 | "env": {
314 | # Choose the backend. Currently, we support BING and GOOGLE. For
315 | # simplicity, in this demo, if you specify the backend as LEPTON,
316 | # we will use the hosted serverless version of lepton search api
317 | # at https://search-api.lepton.run/ to do the search and RAG, which
318 | # runs the same code (slightly modified and might contain improvements)
319 | # as this demo.
320 | "BACKEND": "LEPTON",
321 | # If you are using google, specify the search cx.
322 | "GOOGLE_SEARCH_CX": "",
323 | # Specify the LLM model you are going to use.
324 | "LLM_MODEL": "mixtral-8x7b",
325 | # For all the search queries and results, we will use the Lepton KV to
326 | # store them so that we can retrieve them later. Specify the name of the
327 | # KV here.
328 | "KV_NAME": "search-with-lepton",
329 | # If set to true, will generate related questions. Otherwise, will not.
330 | "RELATED_QUESTIONS": "true",
331 | # On the lepton platform, allow web access when you are logged in.
332 | "LEPTON_ENABLE_AUTH_BY_COOKIE": "true",
333 | },
334 | # Secrets you need to have: search api subscription key, and lepton
335 | # workspace token to query lepton's llama models.
336 | "secret": [
337 | # If you use BING, you need to specify the subscription key. Otherwise
338 | # it is not needed.
339 | "BING_SEARCH_V7_SUBSCRIPTION_KEY",
340 | # If you use GOOGLE, you need to specify the search api key. Note that
341 | # you should also specify the cx in the env.
342 | "GOOGLE_SEARCH_API_KEY",
343 | # If you use Serper, you need to specify the search api key.
344 | "SERPER_SEARCH_API_KEY",
345 | # If you use SearchApi, you need to specify the search api key.
346 | "SEARCHAPI_API_KEY",
347 | # You need to specify the workspace token to query lepton's LLM models.
348 | "LEPTON_WORKSPACE_TOKEN",
349 | ],
350 | }
351 |
352 | # It's just a bunch of api calls, so our own deployment can be made massively
353 | # concurrent.
354 | handler_max_concurrency = 16
355 |
356 | def local_client(self):
357 | """
358 | Gets a thread-local client, so in case openai clients are not thread safe,
359 | each thread will have its own client.
360 | """
361 | import openai
362 |
363 | thread_local = threading.local()
364 | try:
365 | return thread_local.client
366 | except AttributeError:
367 | thread_local.client = openai.OpenAI(
368 | base_url=f"https://{self.model}.lepton.run/api/v1/",
369 | api_key=os.environ.get("LEPTON_WORKSPACE_TOKEN")
370 | or WorkspaceInfoLocalRecord.get_current_workspace_token(),
371 | # We will set the connect timeout to be 10 seconds, and read/write
372 | # timeout to be 120 seconds, in case the inference server is
373 | # overloaded.
374 | timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),
375 | )
376 | return thread_local.client
377 |
378 | def init(self):
379 | """
380 | Initializes photon configs.
381 | """
382 | # First, log in to the workspace.
383 | leptonai.api.workspace.login()
384 | self.backend = os.environ["BACKEND"].upper()
385 | if self.backend == "LEPTON":
386 | self.leptonsearch_client = Client(
387 | "https://search-api.lepton.run/",
388 | token=os.environ.get("LEPTON_WORKSPACE_TOKEN")
389 | or WorkspaceInfoLocalRecord.get_current_workspace_token(),
390 | stream=True,
391 | timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),
392 | )
393 | elif self.backend == "BING":
394 | self.search_api_key = os.environ["BING_SEARCH_V7_SUBSCRIPTION_KEY"]
395 | self.search_function = lambda query: search_with_bing(
396 | query,
397 | self.search_api_key,
398 | )
399 | elif self.backend == "GOOGLE":
400 | self.search_api_key = os.environ["GOOGLE_SEARCH_API_KEY"]
401 | self.search_function = lambda query: search_with_google(
402 | query,
403 | self.search_api_key,
404 | os.environ["GOOGLE_SEARCH_CX"],
405 | )
406 | elif self.backend == "SERPER":
407 | self.search_api_key = os.environ["SERPER_SEARCH_API_KEY"]
408 | self.search_function = lambda query: search_with_serper(
409 | query,
410 | self.search_api_key,
411 | )
412 | elif self.backend == "SEARCHAPI":
413 | self.search_api_key = os.environ["SEARCHAPI_API_KEY"]
414 | self.search_function = lambda query: search_with_searchapi(
415 | query,
416 | self.search_api_key,
417 | )
418 | else:
419 | raise RuntimeError("Backend must be LEPTON, BING, GOOGLE, SERPER or SEARCHAPI.")
420 | self.model = os.environ["LLM_MODEL"]
421 | # An executor to carry out async tasks, such as uploading to KV.
422 | self.executor = concurrent.futures.ThreadPoolExecutor(
423 | max_workers=self.handler_max_concurrency * 2
424 | )
425 | # Create the KV to store the search results.
426 | logger.info("Creating KV. May take a while for the first time.")
427 | self.kv = KV(
428 | os.environ["KV_NAME"], create_if_not_exists=True, error_if_exists=False
429 | )
430 | # whether we should generate related questions.
431 | self.should_do_related_questions = to_bool(os.environ["RELATED_QUESTIONS"])
432 |
433 | def get_related_questions(self, query, contexts):
434 | """
435 | Gets related questions based on the query and context.
436 | """
437 |
438 | def ask_related_questions(
439 | questions: Annotated[
440 | List[str],
441 | [(
442 | "question",
443 | Annotated[
444 | str, "related question to the original question and context."
445 | ],
446 | )],
447 | ]
448 | ):
449 | """
450 | ask further questions that are related to the input and output.
451 | """
452 | pass
453 |
454 | try:
455 | response = self.local_client().chat.completions.create(
456 | model=self.model,
457 | messages=[
458 | {
459 | "role": "system",
460 | "content": _more_questions_prompt.format(
461 | context="\n\n".join([c["snippet"] for c in contexts])
462 | ),
463 | },
464 | {
465 | "role": "user",
466 | "content": query,
467 | },
468 | ],
469 | tools=[{
470 | "type": "function",
471 | "function": tool.get_tools_spec(ask_related_questions),
472 | }],
473 | max_tokens=512,
474 | )
475 | related = response.choices[0].message.tool_calls[0].function.arguments
476 | if isinstance(related, str):
477 | related = json.loads(related)
478 | logger.trace(f"Related questions: {related}")
479 | return related["questions"][:5]
480 | except Exception as e:
481 | # For any exceptions, we will just return an empty list.
482 | logger.error(
483 | "encountered error while generating related questions:"
484 | f" {e}\n{traceback.format_exc()}"
485 | )
486 | return []
487 |
488 | def _raw_stream_response(
489 | self, contexts, llm_response, related_questions_future
490 | ) -> Generator[str, None, None]:
491 | """
492 | A generator that yields the raw stream response. You do not need to call
493 | this directly. Instead, use the stream_and_upload_to_kv which will also
494 | upload the response to KV.
495 | """
496 | # First, yield the contexts.
497 | yield json.dumps(contexts)
498 | yield "\n\n__LLM_RESPONSE__\n\n"
499 | # Second, yield the llm response.
500 | if not contexts:
501 | # Prepend a warning to the user
502 | yield (
503 | "(The search engine returned nothing for this query. Please take the"
504 | " answer with a grain of salt.)\n\n"
505 | )
506 | for chunk in llm_response:
507 | if chunk.choices:
508 | yield chunk.choices[0].delta.content or ""
509 | # Third, yield the related questions. If any error happens, we will just
510 | # return an empty list.
511 | if related_questions_future is not None:
512 | related_questions = related_questions_future.result()
513 | try:
514 | result = json.dumps(related_questions)
515 | except Exception as e:
516 | logger.error(f"encountered error: {e}\n{traceback.format_exc()}")
517 | result = "[]"
518 | yield "\n\n__RELATED_QUESTIONS__\n\n"
519 | yield result
520 |
521 | def stream_and_upload_to_kv(
522 | self, contexts, llm_response, related_questions_future, search_uuid
523 | ) -> Generator[str, None, None]:
524 | """
525 | Streams the result and uploads to KV.
526 | """
527 | # First, stream and yield the results.
528 | all_yielded_results = []
529 | for result in self._raw_stream_response(
530 | contexts, llm_response, related_questions_future
531 | ):
532 | all_yielded_results.append(result)
533 | yield result
534 | # Second, upload to KV. Note that if uploading to KV fails, we will silently
535 | # ignore it, because we don't want to affect the user experience.
536 | _ = self.executor.submit(self.kv.put, search_uuid, "".join(all_yielded_results))
537 |
538 | @Photon.handler(method="POST", path="/query")
539 | def query_function(
540 | self,
541 | query: str,
542 | search_uuid: str,
543 | generate_related_questions: Optional[bool] = True,
544 | ) -> StreamingResponse:
545 | """
546 | Query the search engine and returns the response.
547 |
548 | The query can have the following fields:
549 | - query: the user query.
550 | - search_uuid: a uuid that is used to store or retrieve the search result. If
551 | the uuid does not exist, generate and write to the kv. If the kv
552 | fails, we generate regardless, in favor of availability. If the uuid
553 | exists, return the stored result.
554 | - generate_related_questions: if set to false, will not generate related
555 | questions. Otherwise, will depend on the environment variable
556 | RELATED_QUESTIONS. Default: true.
557 | """
558 | # Note that, if uuid exists, we don't check if the stored query is the same
559 | # as the current query, and simply return the stored result. This is to enable
560 | # the user to share a searched link to others and have others see the same result.
561 | if search_uuid:
562 | try:
563 | result = self.kv.get(search_uuid)
564 |
565 | def str_to_generator(result: str) -> Generator[str, None, None]:
566 | yield result
567 |
568 | return StreamingResponse(str_to_generator(result))
569 | except KeyError:
570 | logger.info(f"Key {search_uuid} not found, will generate again.")
571 | except Exception as e:
572 | logger.error(
573 | f"KV error: {e}\n{traceback.format_exc()}, will generate again."
574 | )
575 | else:
576 | raise HTTPException(status_code=400, detail="search_uuid must be provided.")
577 |
578 | if self.backend == "LEPTON":
579 | # delegate to the lepton search api.
580 | result = self.leptonsearch_client.query(
581 | query=query,
582 | search_uuid=search_uuid,
583 | generate_related_questions=generate_related_questions,
584 | )
585 | return StreamingResponse(content=result, media_type="text/html")
586 |
587 | # First, do a search query.
588 | query = query or _default_query
589 | # Basic attack protection: remove "[INST]" or "[/INST]" from the query
590 | query = re.sub(r"\[/?INST\]", "", query)
591 | contexts = self.search_function(query)
592 |
593 | system_prompt = _rag_query_text.format(
594 | context="\n\n".join(
595 | [f"[[citation:{i+1}]] {c['snippet']}" for i, c in enumerate(contexts)]
596 | )
597 | )
598 | try:
599 | client = self.local_client()
600 | llm_response = client.chat.completions.create(
601 | model=self.model,
602 | messages=[
603 | {"role": "system", "content": system_prompt},
604 | {"role": "user", "content": query},
605 | ],
606 | max_tokens=1024,
607 | stop=stop_words,
608 | stream=True,
609 | temperature=0.9,
610 | )
611 | if self.should_do_related_questions and generate_related_questions:
612 | # While the answer is being generated, we can start generating
613 | # related questions as a future.
614 | related_questions_future = self.executor.submit(
615 | self.get_related_questions, query, contexts
616 | )
617 | else:
618 | related_questions_future = None
619 | except Exception as e:
620 | logger.error(f"encountered error: {e}\n{traceback.format_exc()}")
621 | return HTMLResponse("Internal server error.", 503)
622 |
623 | return StreamingResponse(
624 | self.stream_and_upload_to_kv(
625 | contexts, llm_response, related_questions_future, search_uuid
626 | ),
627 | media_type="text/html",
628 | )
629 |
630 | @Photon.handler(mount=True)
631 | def ui(self):
632 | return StaticFiles(directory="ui")
633 |
634 | @Photon.handler(method="GET", path="/")
635 | def index(self) -> RedirectResponse:
636 | """
637 | Redirects "/" to the ui page.
638 | """
639 | return RedirectResponse(url="/ui/index.html")
640 |
641 |
642 | if __name__ == "__main__":
643 | rag = RAG()
644 | rag.launch()
645 |
--------------------------------------------------------------------------------