The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
├── .gitignore
├── LICENSE
├── README.md
├── lepton_template
    └── README.md
├── search_with_lepton.py
└── web
    ├── .eslintrc.json
    ├── next-env.d.ts
    ├── next.config.mjs
    ├── package-lock.json
    ├── package.json
    ├── postcss.config.js
    ├── public
        └── bg.svg
    ├── 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
        │   ├── favicon.ico
        │   ├── globals.css
        │   ├── icon.svg
        │   ├── 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


/.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 | 


--------------------------------------------------------------------------------
/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 | 


--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
 1 | <div align="center">
 2 | <h1 align="center">Search with Lepton</h1>
 3 | Build your own conversational search engine using less than 500 lines of code.
 4 | <br/>
 5 | <a href="https://search.lepton.run/" target="_blank"> Live Demo </a>
 6 | <br/>
 7 | <img width="70%" src="https://github.com/leptonai/search_with_lepton/assets/1506722/845d7057-02cd-404e-bbc7-60f4bae89680">
 8 | </div>
 9 | 
10 | 
11 | ## Features
12 | - Built-in support for LLM
13 | - Built-in support for search engine
14 | - Customizable pretty UI interface
15 | - Shareable, cached search results
16 | 
17 | ## Setup Search Engine API
18 | There are two default supported search engines: Bing and Google.
19 |  
20 | ### Bing Search
21 | To use the Bing Web Search API, please visit [this link](https://www.microsoft.com/en-us/bing/apis/bing-web-search-api) to obtain your Bing subscription key.
22 | 
23 | ### Google Search
24 | You have 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.
25 | 
26 | ## Setup LLM and KV
27 | 
28 | > [!NOTE]
29 | > We recommend using the built-in llm and kv functions with Lepton. 
30 | > Running the following commands to set up them automatically.
31 | 
32 | ```shell
33 | pip install -U leptonai openai && lep login
34 | ```
35 | 
36 | ## Obtain Your Lepton AI Workspace Token
37 | You can copy your workspace toke from the Lepton AI Dashboard &rarr; Settings &rarr; Tokens.
38 | 
39 | 
40 | ## Build
41 | 
42 | 1. Set Bing subscription key
43 | ```shell
44 | export BING_SEARCH_V7_SUBSCRIPTION_KEY=YOUR_BING_SUBSCRIPTION_KEY
45 | ```
46 | 2. Set Lepton AI workspace token
47 | ```shell
48 | export LEPTON_WORKSPACE_TOKEN=YOUR_LEPTON_WORKSPACE_TOKEN
49 | ```
50 | 3. Build web
51 | ```shell
52 | cd web && npm install && npm run build
53 | ```
54 | 4. Run server
55 | ```shell
56 | BACKEND=BING python search_with_lepton.py
57 | ```
58 | 
59 | For Google Search using SearchApi:
60 | ```shell
61 | export SEARCHAPI_API_KEY=YOUR_SEARCHAPI_API_KEY
62 | BACKEND=SEARCHAPI python search_with_lepton.py
63 | ```
64 | 
65 | For Google Search using Serper:
66 | ```shell
67 | export SERPER_SEARCH_API_KEY=YOUR_SERPER_API_KEY
68 | BACKEND=SERPER python search_with_lepton.py
69 | ```
70 | 
71 | For Google Search using Programmable Search Engine:
72 | ```shell
73 | export GOOGLE_SEARCH_API_KEY=YOUR_GOOGLE_SEARCH_API_KEY
74 | export GOOGLE_SEARCH_CX=YOUR_GOOGLE_SEARCH_ENGINE_ID
75 | BACKEND=GOOGLE python search_with_lepton.py
76 | ```
77 | 
78 | 
79 | 
80 | ## Deploy
81 | 
82 | You can deploy this to Lepton AI with one click:
83 | 
84 | [![Deploy with Lepton AI](https://github.com/leptonai/search_with_lepton/assets/1506722/bbd40afa-69ee-4acb-8974-d060880a183a)](https://dashboard.lepton.ai/workspace-redirect/explore/detail/search-by-lepton)
85 | 
86 | You can also deploy your own version via
87 | 
88 | ```shell
89 | 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
90 | ```
91 | 
92 | Learn more about `lep photon` [here](https://www.lepton.ai/docs/references/lep_photon).
93 | 


--------------------------------------------------------------------------------
/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 | 


--------------------------------------------------------------------------------
/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.v0.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.v0.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 | 


--------------------------------------------------------------------------------
/web/.eslintrc.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "plugins": ["unused-imports"],
 3 |   "extends": [
 4 |     "next/core-web-vitals",
 5 |     "plugin:prettier/recommended"
 6 |   ],
 7 |   "rules": {
 8 |     "unused-imports/no-unused-imports": "error"
 9 |   }
10 | }
11 | 


--------------------------------------------------------------------------------
/web/next-env.d.ts:
--------------------------------------------------------------------------------
1 | /// <reference types="next" />
2 | /// <reference types="next/image-types/global" />
3 | 
4 | // NOTE: This file should not be edited
5 | // see https://nextjs.org/docs/basic-features/typescript for more information.
6 | 


--------------------------------------------------------------------------------
/web/next.config.mjs:
--------------------------------------------------------------------------------
 1 | export default (phase, { defaultConfig }) => {
 2 |   const env = process.env.NODE_ENV;
 3 |   /**
 4 |    * @type {import("next").NextConfig}
 5 |    */
 6 |   if (env === "production") {
 7 |     return {
 8 |       output: "export",
 9 |       assetPrefix: "/ui/",
10 |       basePath: "/ui",
11 |       distDir: "../ui"
12 |     };
13 |   } else {
14 |     return {
15 |       async rewrites() {
16 |         return [
17 |           {
18 |             source: "/query",
19 |             destination: "http://localhost:8080/query" // Proxy to Backend
20 |           }
21 |         ];
22 |       }
23 |     };
24 |   }
25 | }
26 | 


--------------------------------------------------------------------------------
/web/package.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "name": "search",
 3 |   "version": "0.1.0",
 4 |   "private": true,
 5 |   "scripts": {
 6 |     "dev": "next dev",
 7 |     "build": "next build",
 8 |     "start": "next start",
 9 |     "lint": "next lint"
10 |   },
11 |   "dependencies": {
12 |     "@next/third-parties": "^14.0.4",
13 |     "@radix-ui/react-popover": "^1.0.7",
14 |     "@tailwindcss/forms": "^0.5.7",
15 |     "@upstash/ratelimit": "^1.0.0",
16 |     "@vercel/kv": "^1.0.1",
17 |     "clsx": "^2.1.0",
18 |     "headlessui": "^0.0.0",
19 |     "lucide-react": "^0.309.0",
20 |     "mdast-util-from-markdown": "^2.0.0",
21 |     "nanoid": "^5.0.4",
22 |     "next": "14.2.22",
23 |     "react": "^18",
24 |     "react-dom": "^18",
25 |     "react-markdown": "^9.0.1",
26 |     "tailwind-merge": "^2.2.0",
27 |     "unist-builder": "^4.0.0"
28 |   },
29 |   "devDependencies": {
30 |     "@tailwindcss/typography": "^0.5.10",
31 |     "@types/node": "^20",
32 |     "@types/react": "^18",
33 |     "@types/react-dom": "^18",
34 |     "autoprefixer": "^10.0.1",
35 |     "eslint": "^8",
36 |     "eslint-config-next": "14.0.4",
37 |     "eslint-config-prettier": "^9.0.0",
38 |     "eslint-plugin-prettier": "^5.0.1",
39 |     "eslint-plugin-unused-imports": "^3.0.0",
40 |     "postcss": "^8",
41 |     "prettier": "^3.1.0",
42 |     "tailwindcss": "^3.3.0",
43 |     "typescript": "^5"
44 |   }
45 | }
46 | 


--------------------------------------------------------------------------------
/web/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 |   plugins: {
3 |     tailwindcss: {},
4 |     autoprefixer: {},
5 |   },
6 | }
7 | 


--------------------------------------------------------------------------------
/web/public/bg.svg:
--------------------------------------------------------------------------------
1 | <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' width='8' height='8' fill='none' stroke='rgb(0 0 0 / 0.1)'><path d='M0 .5H31.5V32'/></svg>


--------------------------------------------------------------------------------
/web/src/app/components/answer.tsx:
--------------------------------------------------------------------------------
  1 | import {
  2 |   Popover,
  3 |   PopoverContent,
  4 |   PopoverTrigger,
  5 | } from "@/app/components/popover";
  6 | import { Skeleton } from "@/app/components/skeleton";
  7 | import { Wrapper } from "@/app/components/wrapper";
  8 | import { Source } from "@/app/interfaces/source";
  9 | import { BookOpenText } from "lucide-react";
 10 | import { FC } from "react";
 11 | import Markdown from "react-markdown";
 12 | 
 13 | export const Answer: FC<{ markdown: string; sources: Source[] }> = ({
 14 |   markdown,
 15 |   sources,
 16 | }) => {
 17 |   return (
 18 |     <Wrapper
 19 |       title={
 20 |         <>
 21 |           <BookOpenText></BookOpenText> Answer
 22 |         </>
 23 |       }
 24 |       content={
 25 |         markdown ? (
 26 |           <div className="prose prose-sm max-w-full">
 27 |             <Markdown
 28 |               components={{
 29 |                 a: ({ node: _, ...props }) => {
 30 |                   if (!props.href) return <></>;
 31 |                   const source = sources[+props.href - 1];
 32 |                   if (!source) return <></>;
 33 |                   return (
 34 |                     <span className="inline-block w-4">
 35 |                       <Popover>
 36 |                         <PopoverTrigger asChild>
 37 |                           <span
 38 |                             title={source.name}
 39 |                             className="inline-block cursor-pointer transform scale-[60%] no-underline font-medium bg-zinc-300 hover:bg-zinc-400 w-6 text-center h-6 rounded-full origin-top-left"
 40 |                           >
 41 |                             {props.href}
 42 |                           </span>
 43 |                         </PopoverTrigger>
 44 |                         <PopoverContent
 45 |                           align={"start"}
 46 |                           className="max-w-screen-md flex flex-col gap-2 bg-white shadow-transparent ring-zinc-50 ring-4 text-xs"
 47 |                         >
 48 |                           <div className="text-ellipsis overflow-hidden whitespace-nowrap font-medium">
 49 |                             {source.name}
 50 |                           </div>
 51 |                           <div className="flex gap-4">
 52 |                             {source.primaryImageOfPage?.thumbnailUrl && (
 53 |                               <div className="flex-none">
 54 |                                 <img
 55 |                                   className="rounded h-16 w-16"
 56 |                                   width={source.primaryImageOfPage?.width}
 57 |                                   height={source.primaryImageOfPage?.height}
 58 |                                   src={source.primaryImageOfPage?.thumbnailUrl}
 59 |                                 />
 60 |                               </div>
 61 |                             )}
 62 |                             <div className="flex-1">
 63 |                               <div className="line-clamp-4 text-zinc-500 break-words">
 64 |                                 {source.snippet}
 65 |                               </div>
 66 |                             </div>
 67 |                           </div>
 68 | 
 69 |                           <div className="flex gap-2 items-center">
 70 |                             <div className="flex-1 overflow-hidden">
 71 |                               <div className="text-ellipsis text-blue-500 overflow-hidden whitespace-nowrap">
 72 |                                 <a
 73 |                                   title={source.name}
 74 |                                   href={source.url}
 75 |                                   target="_blank"
 76 |                                 >
 77 |                                   {source.url}
 78 |                                 </a>
 79 |                               </div>
 80 |                             </div>
 81 |                             <div className="flex-none flex items-center relative">
 82 |                               <img
 83 |                                 className="h-3 w-3"
 84 |                                 alt={source.url}
 85 |                                 src={`https://www.google.com/s2/favicons?domain=${source.url}&sz=${16}`}
 86 |                               />
 87 |                             </div>
 88 |                           </div>
 89 |                         </PopoverContent>
 90 |                       </Popover>
 91 |                     </span>
 92 |                   );
 93 |                 },
 94 |               }}
 95 |             >
 96 |               {markdown}
 97 |             </Markdown>
 98 |           </div>
 99 |         ) : (
100 |           <div className="flex flex-col gap-2">
101 |             <Skeleton className="max-w-sm h-4 bg-zinc-200"></Skeleton>
102 |             <Skeleton className="max-w-lg h-4 bg-zinc-200"></Skeleton>
103 |             <Skeleton className="max-w-2xl h-4 bg-zinc-200"></Skeleton>
104 |             <Skeleton className="max-w-lg h-4 bg-zinc-200"></Skeleton>
105 |             <Skeleton className="max-w-xl h-4 bg-zinc-200"></Skeleton>
106 |           </div>
107 |         )
108 |       }
109 |     ></Wrapper>
110 |   );
111 | };
112 | 


--------------------------------------------------------------------------------
/web/src/app/components/footer.tsx:
--------------------------------------------------------------------------------
 1 | import { Mails } from "lucide-react";
 2 | import { FC } from "react";
 3 | 
 4 | export const Footer: FC = () => {
 5 |   return (
 6 |     <div className="text-center flex flex-col items-center text-xs text-zinc-700 gap-1">
 7 |       <div className="text-zinc-400">
 8 |         Answer generated by large language models, plz double check for
 9 |         correctness.
10 |       </div>
11 |       <div className="text-zinc-400">
12 |         LLM, Vector DB, and other components powered by the Lepton AI platform.
13 |       </div>
14 |       <div className="flex gap-2 justify-center">
15 |         <div>
16 |           <a
17 |             className="text-blue-500 font-medium inline-flex gap-1 items-center flex-nowrap text-nowrap"
18 |             href="mailto:info@lepton.ai"
19 |           >
20 |             <Mails size={8} />
21 |             Talk to us
22 |           </a>
23 |         </div>
24 |         <div>if you need a performant and scalable AI cloud!</div>
25 |       </div>
26 | 
27 |       <div className="flex items-center justify-center flex-wrap gap-x-4 gap-y-2 mt-2 text-zinc-400">
28 |         <a className="hover:text-zinc-950" href="https://lepton.ai/">
29 |           Lepton Home
30 |         </a>
31 |         <a
32 |           className="hover:text-zinc-950"
33 |           href="https://dashboard.lepton.ai/playground"
34 |         >
35 |           API Playground
36 |         </a>
37 |         <a
38 |           className="hover:text-zinc-950"
39 |           href="https://github.com/leptonai/leptonai"
40 |         >
41 |           Python Library
42 |         </a>
43 |         <a className="hover:text-zinc-950" href="https://twitter.com/leptonai">
44 |           Twitter
45 |         </a>
46 |         <a className="hover:text-zinc-950" href="https://leptonai.medium.com/">
47 |           Blog
48 |         </a>
49 |       </div>
50 |     </div>
51 |   );
52 | };
53 | 


--------------------------------------------------------------------------------
/web/src/app/components/logo.tsx:
--------------------------------------------------------------------------------
 1 | import React, { FC } from "react";
 2 | 
 3 | export const Logo: FC = () => {
 4 |   return (
 5 |     <div className="flex gap-4 items-center justify-center cursor-default select-none relative">
 6 |       <div className="h-10 w-10">
 7 |         <svg viewBox="0 0 85 85" className="h-full w-full">
 8 |           <path
 9 |             fillRule="evenodd"
10 |             clipRule="evenodd"
11 |             fill="#2D9CDB"
12 |             d="M75.9,48.1V36.9c0-2,0-3.1-0.1-3.9c0-0.4-0.1-0.6-0.1-0.7c-0.1-0.3-0.2-0.5-0.4-0.7c-0.1,0-0.2-0.2-0.6-0.4  c-0.7-0.5-1.6-1-3.3-2l-9.7-5.6c-1.7-1-2.7-1.5-3.4-1.9c-0.4-0.2-0.6-0.3-0.6-0.3c-0.3-0.1-0.6-0.1-0.9,0c-0.1,0-0.3,0.1-0.6,0.3  c-0.7,0.4-1.7,0.9-3.4,1.9l-9.7,5.6c-1.7,1-2.7,1.5-3.3,2c-0.3,0.2-0.5,0.4-0.6,0.4c-0.2,0.2-0.3,0.5-0.4,0.7c0,0.1,0,0.3-0.1,0.7  c0,0.8-0.1,1.9-0.1,3.9v11.2c0,2,0,3.1,0.1,3.9c0,0.4,0.1,0.6,0.1,0.7c0.1,0.3,0.2,0.5,0.4,0.7c0.1,0,0.2,0.2,0.6,0.4  c0.7,0.5,1.6,1,3.3,2l9.7,5.6c1.7,1,2.7,1.5,3.4,1.9c0.4,0.2,0.6,0.3,0.6,0.3c0.3,0.1,0.6,0.1,0.9,0c0.1,0,0.3-0.1,0.6-0.3  c0.7-0.4,1.7-0.9,3.4-1.9l9.7-5.6c1.7-1,2.7-1.5,3.3-2c0.3-0.2,0.5-0.4,0.6-0.4c0.2-0.2,0.3-0.5,0.4-0.7c0-0.1,0-0.3,0.1-0.7  C75.9,51.2,75.9,50.1,75.9,48.1z M75.7,52.7C75.7,52.7,75.7,52.7,75.7,52.7C75.7,52.7,75.7,52.7,75.7,52.7z M75.3,53.4  C75.3,53.4,75.3,53.4,75.3,53.4C75.3,53.4,75.3,53.4,75.3,53.4z M57.7,63.7C57.7,63.7,57.7,63.7,57.7,63.7  C57.7,63.7,57.7,63.7,57.7,63.7z M56.9,63.7C56.9,63.7,56.9,63.7,56.9,63.7C56.9,63.7,56.9,63.7,56.9,63.7z M39.3,53.4  C39.3,53.4,39.3,53.4,39.3,53.4C39.3,53.4,39.3,53.4,39.3,53.4z M38.9,52.7C38.9,52.7,38.9,52.7,38.9,52.7  C38.9,52.7,38.9,52.7,38.9,52.7z M38.9,32.3C38.9,32.3,38.9,32.3,38.9,32.3C38.9,32.3,38.9,32.3,38.9,32.3z M39.3,31.6  C39.3,31.6,39.3,31.6,39.3,31.6C39.3,31.6,39.3,31.6,39.3,31.6z M56.9,21.4C56.9,21.4,56.9,21.4,56.9,21.4  C56.9,21.4,56.9,21.4,56.9,21.4z M57.7,21.4C57.7,21.4,57.7,21.4,57.7,21.4C57.7,21.4,57.7,21.4,57.7,21.4z M75.3,31.6  C75.3,31.6,75.3,31.6,75.3,31.6C75.3,31.6,75.3,31.6,75.3,31.6z M75.7,32.3C75.7,32.3,75.7,32.3,75.7,32.3  C75.7,32.3,75.7,32.3,75.7,32.3z M81.9,25.6c-1.2-1.3-2.8-2.3-6-4.1l-9.7-5.6C63,14,61.3,13,59.6,12.7c-1.5-0.3-3.1-0.3-4.6,0  c-1.7,0.4-3.3,1.3-6.6,3.2l-9.7,5.6c-3.2,1.9-4.9,2.8-6,4.1c-1,1.2-1.8,2.5-2.3,4c-0.5,1.7-0.5,3.6-0.5,7.3v11.2  c0,3.8,0,5.6,0.5,7.3c0.5,1.5,1.3,2.9,2.3,4c1.2,1.3,2.8,2.3,6,4.1l9.7,5.6c3.2,1.9,4.9,2.8,6.6,3.2c1.5,0.3,3.1,0.3,4.6,0  c1.7-0.4,3.3-1.3,6.6-3.2l9.7-5.6c3.2-1.9,4.9-2.8,6-4.1c1-1.2,1.8-2.5,2.3-4c0.5-1.7,0.5-3.6,0.5-7.3V36.9c0-3.8,0-5.6-0.5-7.3  C83.7,28.1,82.9,26.7,81.9,25.6z"
13 |           ></path>
14 |           <path
15 |             fillRule="evenodd"
16 |             clipRule="evenodd"
17 |             fill="#2F80ED"
18 |             d="M46.3,48.1V36.9c0-2,0-3.1-0.1-3.9c0-0.4-0.1-0.6-0.1-0.7c-0.1-0.3-0.2-0.5-0.4-0.7c-0.1,0-0.2-0.2-0.6-0.4  c-0.7-0.5-1.6-1-3.3-2l-9.7-5.6c-1.7-1-2.7-1.5-3.4-1.9c-0.4-0.2-0.6-0.3-0.6-0.3c-0.3-0.1-0.6-0.1-0.9,0c-0.1,0-0.3,0.1-0.6,0.3  c-0.7,0.4-1.7,0.9-3.4,1.9l-9.7,5.6c-1.7,1-2.7,1.5-3.3,2c-0.3,0.2-0.5,0.4-0.6,0.4c-0.2,0.2-0.3,0.5-0.4,0.7c0,0.1,0,0.3-0.1,0.7  c0,0.8-0.1,1.9-0.1,3.9v11.2c0,2,0,3.1,0.1,3.9c0,0.4,0.1,0.6,0.1,0.7c0.1,0.3,0.2,0.5,0.4,0.7c0.1,0,0.2,0.2,0.6,0.4  c0.7,0.5,1.6,1,3.3,2l9.7,5.6c1.7,1,2.7,1.5,3.4,1.9c0.4,0.2,0.6,0.3,0.6,0.3c0.3,0.1,0.6,0.1,0.9,0c0.1,0,0.3-0.1,0.6-0.3  c0.7-0.4,1.7-0.9,3.4-1.9l9.7-5.6c1.7-1,2.7-1.5,3.3-2c0.3-0.2,0.5-0.4,0.6-0.4c0.2-0.2,0.3-0.5,0.4-0.7c0-0.1,0-0.3,0.1-0.7  C46.3,51.2,46.3,50.1,46.3,48.1z M52.3,25.6c-1.2-1.3-2.8-2.3-6-4.1l-9.7-5.6C33.4,14,31.8,13,30,12.7c-1.5-0.3-3.1-0.3-4.6,0  c-1.7,0.4-3.3,1.3-6.6,3.2l-9.7,5.6c-3.2,1.9-4.9,2.8-6,4.1c-1,1.2-1.8,2.5-2.3,4c-0.5,1.7-0.5,3.6-0.5,7.3v11.2  c0,3.8,0,5.6,0.5,7.3c0.5,1.5,1.3,2.9,2.3,4c1.2,1.3,2.8,2.3,6,4.1l9.7,5.6c3.2,1.9,4.9,2.8,6.6,3.2c1.5,0.3,3.1,0.3,4.6,0  c1.7-0.4,3.3-1.3,6.6-3.2l9.7-5.6c3.2-1.9,4.9-2.8,6-4.1c1-1.2,1.8-2.5,2.3-4c0.5-1.7,0.5-3.6,0.5-7.3V36.9c0-3.8,0-5.6-0.5-7.3  C54.2,28.1,53.4,26.7,52.3,25.6z"
19 |           ></path>
20 |           <path
21 |             fill="#2F80ED"
22 |             d="M42.5,55.5c0.2,0.1,0.4,0.3,0.7,0.4l8,4.6c-1.1,0.9-2.6,1.7-4.9,3.1l-3.8,2.2l-3.8-2.2  c-2.3-1.4-3.8-2.2-4.9-3.1l8-4.6C42.1,55.7,42.3,55.6,42.5,55.5z"
23 |           ></path>
24 |           <path
25 |             fill="#2D9CDB"
26 |             d="M51.2,24.5c-1.1-0.9-2.6-1.7-4.9-3.1l-3.8-2.2l-3.8,2.2c-2.3,1.4-3.8,2.2-4.9,3.1l8,4.6  c0.2,0.1,0.5,0.3,0.7,0.4c0.2-0.1,0.4-0.3,0.7-0.4L51.2,24.5z"
27 |           ></path>
28 |         </svg>
29 |       </div>
30 |       <div className="text-center font-medium text-2xl md:text-3xl text-zinc-950 relative text-nowrap">
31 |         Lepton Search
32 |       </div>
33 |       <div className="transform scale-75 origin-left border items-center rounded-lg bg-gray-100 px-2 py-1 text-xs font-medium text-zinc-600">
34 |         beta
35 |       </div>
36 |     </div>
37 |   );
38 | };
39 | 


--------------------------------------------------------------------------------
/web/src/app/components/popover.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | 
 3 | import * as React from "react";
 4 | import * as PopoverPrimitive from "@radix-ui/react-popover";
 5 | 
 6 | import { cn } from "@/app/utils/cn";
 7 | 
 8 | const Popover = PopoverPrimitive.Root;
 9 | 
10 | const PopoverTrigger = PopoverPrimitive.Trigger;
11 | 
12 | const PopoverContent = React.forwardRef<
13 |   React.ElementRef<typeof PopoverPrimitive.Content>,
14 |   React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
15 | >(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
16 |   <PopoverPrimitive.Portal>
17 |     <PopoverPrimitive.Content
18 |       ref={ref}
19 |       align={align}
20 |       sideOffset={sideOffset}
21 |       className={cn(
22 |         "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
23 |         className,
24 |       )}
25 |       {...props}
26 |     />
27 |   </PopoverPrimitive.Portal>
28 | ));
29 | PopoverContent.displayName = PopoverPrimitive.Content.displayName;
30 | 
31 | export { Popover, PopoverTrigger, PopoverContent };
32 | 


--------------------------------------------------------------------------------
/web/src/app/components/preset-query.tsx:
--------------------------------------------------------------------------------
 1 | import { getSearchUrl } from "@/app/utils/get-search-url";
 2 | import { nanoid } from "nanoid";
 3 | import Link from "next/link";
 4 | import React, { FC, useMemo } from "react";
 5 | 
 6 | export const PresetQuery: FC<{ query: string }> = ({ query }) => {
 7 |   const rid = useMemo(() => nanoid(), [query]);
 8 | 
 9 |   return (
10 |     <Link
11 |       prefetch={false}
12 |       title={query}
13 |       href={getSearchUrl(query, rid)}
14 |       className="border border-zinc-200/50 text-ellipsis overflow-hidden text-nowrap items-center rounded-lg bg-zinc-100 hover:bg-zinc-200/80 hover:text-zinc-950 px-2 py-1 text-xs font-medium text-zinc-600"
15 |     >
16 |       {query}
17 |     </Link>
18 |   );
19 | };
20 | 


--------------------------------------------------------------------------------
/web/src/app/components/relates.tsx:
--------------------------------------------------------------------------------
 1 | import { PresetQuery } from "@/app/components/preset-query";
 2 | import { Skeleton } from "@/app/components/skeleton";
 3 | import { Wrapper } from "@/app/components/wrapper";
 4 | import { Relate } from "@/app/interfaces/relate";
 5 | import { MessageSquareQuote } from "lucide-react";
 6 | import React, { FC } from "react";
 7 | 
 8 | export const Relates: FC<{ relates: Relate[] | null }> = ({ relates }) => {
 9 |   return (
10 |     <Wrapper
11 |       title={
12 |         <>
13 |           <MessageSquareQuote></MessageSquareQuote> Related
14 |         </>
15 |       }
16 |       content={
17 |         <div className="flex gap-2 flex-col">
18 |           {relates !== null ? (
19 |             relates.length > 0 ? (
20 |               relates.map(({ question }) => (
21 |                 <PresetQuery key={question} query={question}></PresetQuery>
22 |               ))
23 |             ) : (
24 |               <div className="text-sm">No related questions.</div>
25 |             )
26 |           ) : (
27 |             <>
28 |               <Skeleton className="w-full h-5 bg-zinc-200/80"></Skeleton>
29 |               <Skeleton className="w-full h-5 bg-zinc-200/80"></Skeleton>
30 |               <Skeleton className="w-full h-5 bg-zinc-200/80"></Skeleton>
31 |             </>
32 |           )}
33 |         </div>
34 |       }
35 |     ></Wrapper>
36 |   );
37 | };
38 | 


--------------------------------------------------------------------------------
/web/src/app/components/result.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | import { Answer } from "@/app/components/answer";
 3 | import { Relates } from "@/app/components/relates";
 4 | import { Sources } from "@/app/components/sources";
 5 | import { Relate } from "@/app/interfaces/relate";
 6 | import { Source } from "@/app/interfaces/source";
 7 | import { parseStreaming } from "@/app/utils/parse-streaming";
 8 | import { Annoyed } from "lucide-react";
 9 | import { FC, useEffect, useState } from "react";
10 | 
11 | export const Result: FC<{ query: string; rid: string }> = ({ query, rid }) => {
12 |   const [sources, setSources] = useState<Source[]>([]);
13 |   const [markdown, setMarkdown] = useState<string>("");
14 |   const [relates, setRelates] = useState<Relate[] | null>(null);
15 |   const [error, setError] = useState<number | null>(null);
16 |   useEffect(() => {
17 |     const controller = new AbortController();
18 |     void parseStreaming(
19 |       controller,
20 |       query,
21 |       rid,
22 |       setSources,
23 |       setMarkdown,
24 |       setRelates,
25 |       setError,
26 |     );
27 |     return () => {
28 |       controller.abort();
29 |     };
30 |   }, [query]);
31 |   return (
32 |     <div className="flex flex-col gap-8">
33 |       <Answer markdown={markdown} sources={sources}></Answer>
34 |       <Sources sources={sources}></Sources>
35 |       <Relates relates={relates}></Relates>
36 |       {error && (
37 |         <div className="absolute inset-4 flex items-center justify-center bg-white/40 backdrop-blur-sm">
38 |           <div className="p-4 bg-white shadow-2xl rounded text-blue-500 font-medium flex gap-4">
39 |             <Annoyed></Annoyed>
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 |           </div>
44 |         </div>
45 |       )}
46 |     </div>
47 |   );
48 | };
49 | 


--------------------------------------------------------------------------------
/web/src/app/components/search.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | import { getSearchUrl } from "@/app/utils/get-search-url";
 3 | import { ArrowRight } from "lucide-react";
 4 | import { nanoid } from "nanoid";
 5 | import { useRouter } from "next/navigation";
 6 | import React, { FC, useState } from "react";
 7 | 
 8 | export const Search: FC = () => {
 9 |   const [value, setValue] = useState("");
10 |   const router = useRouter();
11 |   return (
12 |     <form
13 |       onSubmit={(e) => {
14 |         e.preventDefault();
15 |         if (value) {
16 |           setValue("");
17 |           router.push(getSearchUrl(encodeURIComponent(value), nanoid()));
18 |         }
19 |       }}
20 |     >
21 |       <label
22 |         className="relative bg-white flex items-center justify-center border ring-8 ring-zinc-300/20 py-2 px-2 rounded-lg gap-2 focus-within:border-zinc-300"
23 |         htmlFor="search-bar"
24 |       >
25 |         <input
26 |           id="search-bar"
27 |           value={value}
28 |           onChange={(e) => setValue(e.target.value)}
29 |           autoFocus
30 |           placeholder="Ask Lepton AI anything ..."
31 |           className="px-2 pr-6 w-full rounded-md flex-1 outline-none bg-white"
32 |         />
33 |         <button
34 |           type="submit"
35 |           className="w-auto py-1 px-2 bg-black border-black text-white fill-white active:scale-95 border overflow-hidden relative rounded-xl"
36 |         >
37 |           <ArrowRight size={16} />
38 |         </button>
39 |       </label>
40 |     </form>
41 |   );
42 | };
43 | 


--------------------------------------------------------------------------------
/web/src/app/components/skeleton.tsx:
--------------------------------------------------------------------------------
 1 | import { cn } from "@/app/utils/cn";
 2 | import { HTMLAttributes } from "react";
 3 | 
 4 | function Skeleton({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
 5 |   return (
 6 |     <div
 7 |       className={cn("animate-pulse rounded-md bg-muted", className)}
 8 |       {...props}
 9 |     />
10 |   );
11 | }
12 | 
13 | export { Skeleton };
14 | 


--------------------------------------------------------------------------------
/web/src/app/components/sources.tsx:
--------------------------------------------------------------------------------
 1 | import { Skeleton } from "@/app/components/skeleton";
 2 | import { Wrapper } from "@/app/components/wrapper";
 3 | import { Source } from "@/app/interfaces/source";
 4 | import { BookText } from "lucide-react";
 5 | import { FC } from "react";
 6 | 
 7 | const SourceItem: FC<{ source: Source; index: number }> = ({
 8 |   source,
 9 |   index,
10 | }) => {
11 |   const { id, name, url } = source;
12 |   const domain = new URL(url).hostname;
13 |   return (
14 |     <div
15 |       className="relative text-xs py-3 px-3 bg-zinc-100 hover:bg-zinc-200 rounded-lg flex flex-col gap-2"
16 |       key={id}
17 |     >
18 |       <a href={url} target="_blank" className="absolute inset-0"></a>
19 |       <div className="font-medium text-zinc-950 text-ellipsis overflow-hidden whitespace-nowrap break-words">
20 |         {name}
21 |       </div>
22 |       <div className="flex gap-2 items-center">
23 |         <div className="flex-1 overflow-hidden">
24 |           <div className="text-ellipsis whitespace-nowrap break-all text-zinc-400 overflow-hidden w-full">
25 |             {index + 1} - {domain}
26 |           </div>
27 |         </div>
28 |         <div className="flex-none flex items-center">
29 |           <img
30 |             className="h-3 w-3"
31 |             alt={domain}
32 |             src={`https://www.google.com/s2/favicons?domain=${domain}&sz=${16}`}
33 |           />
34 |         </div>
35 |       </div>
36 |     </div>
37 |   );
38 | };
39 | 
40 | export const Sources: FC<{ sources: Source[] }> = ({ sources }) => {
41 |   return (
42 |     <Wrapper
43 |       title={
44 |         <>
45 |           <BookText></BookText> Sources
46 |         </>
47 |       }
48 |       content={
49 |         <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
50 |           {sources.length > 0 ? (
51 |             sources.map((item, index) => (
52 |               <SourceItem
53 |                 key={item.id}
54 |                 index={index}
55 |                 source={item}
56 |               ></SourceItem>
57 |             ))
58 |           ) : (
59 |             <>
60 |               <Skeleton className="max-w-sm h-16 bg-zinc-200/80"></Skeleton>
61 |               <Skeleton className="max-w-sm h-16 bg-zinc-200/80"></Skeleton>
62 |               <Skeleton className="max-w-sm h-16 bg-zinc-200/80"></Skeleton>
63 |               <Skeleton className="max-w-sm h-16 bg-zinc-200/80"></Skeleton>
64 |             </>
65 |           )}
66 |         </div>
67 |       }
68 |     ></Wrapper>
69 |   );
70 | };
71 | 


--------------------------------------------------------------------------------
/web/src/app/components/title.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | import { getSearchUrl } from "@/app/utils/get-search-url";
 3 | import { RefreshCcw } from "lucide-react";
 4 | import { nanoid } from "nanoid";
 5 | import { useRouter } from "next/navigation";
 6 | 
 7 | export const Title = ({ query }: { query: string }) => {
 8 |   const router = useRouter();
 9 |   return (
10 |     <div className="flex items-center pb-4 mb-6 border-b gap-4">
11 |       <div
12 |         className="flex-1 text-lg sm:text-xl text-black text-ellipsis overflow-hidden whitespace-nowrap"
13 |         title={query}
14 |       >
15 |         {query}
16 |       </div>
17 |       <div className="flex-none">
18 |         <button
19 |           onClick={() => {
20 |             router.push(getSearchUrl(encodeURIComponent(query), nanoid()));
21 |           }}
22 |           type="button"
23 |           className="rounded flex gap-2 items-center bg-transparent px-2 py-1 text-xs font-semibold text-blue-500 hover:bg-zinc-100"
24 |         >
25 |           <RefreshCcw size={12}></RefreshCcw>Rewrite
26 |         </button>
27 |       </div>
28 |     </div>
29 |   );
30 | };
31 | 


--------------------------------------------------------------------------------
/web/src/app/components/wrapper.tsx:
--------------------------------------------------------------------------------
 1 | import { FC, ReactNode } from "react";
 2 | 
 3 | export const Wrapper: FC<{
 4 |   title: ReactNode;
 5 |   content: ReactNode;
 6 | }> = ({ title, content }) => {
 7 |   return (
 8 |     <div className="flex flex-col gap-4 w-full">
 9 |       <div className="flex gap-2 text-blue-500">{title}</div>
10 |       {content}
11 |     </div>
12 |   );
13 | };
14 | 


--------------------------------------------------------------------------------
/web/src/app/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/leptonai/search_with_lepton/0a2fe3713ee42c4c0c6da1bb56d3cbbeccf431d5/web/src/app/favicon.ico


--------------------------------------------------------------------------------
/web/src/app/globals.css:
--------------------------------------------------------------------------------
 1 | @tailwind base;
 2 | @tailwind components;
 3 | @tailwind utilities;
 4 | 
 5 | input:-webkit-autofill,
 6 | input:-webkit-autofill:hover,
 7 | input:-webkit-autofill:focus,
 8 | textarea:-webkit-autofill,
 9 | textarea:-webkit-autofill:hover,
10 | textarea:-webkit-autofill:focus,
11 | select:-webkit-autofill,
12 | select:-webkit-autofill:hover,
13 | select:-webkit-autofill:focus {
14 |   -webkit-background-clip: text;
15 | }
16 | 


--------------------------------------------------------------------------------
/web/src/app/icon.svg:
--------------------------------------------------------------------------------
 1 | <svg xmlns="http://www.w3.org/2000/svg" width="85" height="85" viewBox="0 0 85 85">
 2 |     <path
 3 |             fill-rule="evenodd"
 4 |             clip-rule="evenodd"
 5 |             fill="#2D9CDB"
 6 |             d="M75.9,48.1V36.9c0-2,0-3.1-0.1-3.9c0-0.4-0.1-0.6-0.1-0.7c-0.1-0.3-0.2-0.5-0.4-0.7c-0.1,0-0.2-0.2-0.6-0.4  c-0.7-0.5-1.6-1-3.3-2l-9.7-5.6c-1.7-1-2.7-1.5-3.4-1.9c-0.4-0.2-0.6-0.3-0.6-0.3c-0.3-0.1-0.6-0.1-0.9,0c-0.1,0-0.3,0.1-0.6,0.3  c-0.7,0.4-1.7,0.9-3.4,1.9l-9.7,5.6c-1.7,1-2.7,1.5-3.3,2c-0.3,0.2-0.5,0.4-0.6,0.4c-0.2,0.2-0.3,0.5-0.4,0.7c0,0.1,0,0.3-0.1,0.7  c0,0.8-0.1,1.9-0.1,3.9v11.2c0,2,0,3.1,0.1,3.9c0,0.4,0.1,0.6,0.1,0.7c0.1,0.3,0.2,0.5,0.4,0.7c0.1,0,0.2,0.2,0.6,0.4  c0.7,0.5,1.6,1,3.3,2l9.7,5.6c1.7,1,2.7,1.5,3.4,1.9c0.4,0.2,0.6,0.3,0.6,0.3c0.3,0.1,0.6,0.1,0.9,0c0.1,0,0.3-0.1,0.6-0.3  c0.7-0.4,1.7-0.9,3.4-1.9l9.7-5.6c1.7-1,2.7-1.5,3.3-2c0.3-0.2,0.5-0.4,0.6-0.4c0.2-0.2,0.3-0.5,0.4-0.7c0-0.1,0-0.3,0.1-0.7  C75.9,51.2,75.9,50.1,75.9,48.1z M75.7,52.7C75.7,52.7,75.7,52.7,75.7,52.7C75.7,52.7,75.7,52.7,75.7,52.7z M75.3,53.4  C75.3,53.4,75.3,53.4,75.3,53.4C75.3,53.4,75.3,53.4,75.3,53.4z M57.7,63.7C57.7,63.7,57.7,63.7,57.7,63.7  C57.7,63.7,57.7,63.7,57.7,63.7z M56.9,63.7C56.9,63.7,56.9,63.7,56.9,63.7C56.9,63.7,56.9,63.7,56.9,63.7z M39.3,53.4  C39.3,53.4,39.3,53.4,39.3,53.4C39.3,53.4,39.3,53.4,39.3,53.4z M38.9,52.7C38.9,52.7,38.9,52.7,38.9,52.7  C38.9,52.7,38.9,52.7,38.9,52.7z M38.9,32.3C38.9,32.3,38.9,32.3,38.9,32.3C38.9,32.3,38.9,32.3,38.9,32.3z M39.3,31.6  C39.3,31.6,39.3,31.6,39.3,31.6C39.3,31.6,39.3,31.6,39.3,31.6z M56.9,21.4C56.9,21.4,56.9,21.4,56.9,21.4  C56.9,21.4,56.9,21.4,56.9,21.4z M57.7,21.4C57.7,21.4,57.7,21.4,57.7,21.4C57.7,21.4,57.7,21.4,57.7,21.4z M75.3,31.6  C75.3,31.6,75.3,31.6,75.3,31.6C75.3,31.6,75.3,31.6,75.3,31.6z M75.7,32.3C75.7,32.3,75.7,32.3,75.7,32.3  C75.7,32.3,75.7,32.3,75.7,32.3z M81.9,25.6c-1.2-1.3-2.8-2.3-6-4.1l-9.7-5.6C63,14,61.3,13,59.6,12.7c-1.5-0.3-3.1-0.3-4.6,0  c-1.7,0.4-3.3,1.3-6.6,3.2l-9.7,5.6c-3.2,1.9-4.9,2.8-6,4.1c-1,1.2-1.8,2.5-2.3,4c-0.5,1.7-0.5,3.6-0.5,7.3v11.2  c0,3.8,0,5.6,0.5,7.3c0.5,1.5,1.3,2.9,2.3,4c1.2,1.3,2.8,2.3,6,4.1l9.7,5.6c3.2,1.9,4.9,2.8,6.6,3.2c1.5,0.3,3.1,0.3,4.6,0  c1.7-0.4,3.3-1.3,6.6-3.2l9.7-5.6c3.2-1.9,4.9-2.8,6-4.1c1-1.2,1.8-2.5,2.3-4c0.5-1.7,0.5-3.6,0.5-7.3V36.9c0-3.8,0-5.6-0.5-7.3  C83.7,28.1,82.9,26.7,81.9,25.6z"
 7 |     />
 8 |     <path
 9 |             fill-rule="evenodd"
10 |             clip-rule="evenodd"
11 |             fill="#2F80ED"
12 |             d="M46.3,48.1V36.9c0-2,0-3.1-0.1-3.9c0-0.4-0.1-0.6-0.1-0.7c-0.1-0.3-0.2-0.5-0.4-0.7c-0.1,0-0.2-0.2-0.6-0.4  c-0.7-0.5-1.6-1-3.3-2l-9.7-5.6c-1.7-1-2.7-1.5-3.4-1.9c-0.4-0.2-0.6-0.3-0.6-0.3c-0.3-0.1-0.6-0.1-0.9,0c-0.1,0-0.3,0.1-0.6,0.3  c-0.7,0.4-1.7,0.9-3.4,1.9l-9.7,5.6c-1.7,1-2.7,1.5-3.3,2c-0.3,0.2-0.5,0.4-0.6,0.4c-0.2,0.2-0.3,0.5-0.4,0.7c0,0.1,0,0.3-0.1,0.7  c0,0.8-0.1,1.9-0.1,3.9v11.2c0,2,0,3.1,0.1,3.9c0,0.4,0.1,0.6,0.1,0.7c0.1,0.3,0.2,0.5,0.4,0.7c0.1,0,0.2,0.2,0.6,0.4  c0.7,0.5,1.6,1,3.3,2l9.7,5.6c1.7,1,2.7,1.5,3.4,1.9c0.4,0.2,0.6,0.3,0.6,0.3c0.3,0.1,0.6,0.1,0.9,0c0.1,0,0.3-0.1,0.6-0.3  c0.7-0.4,1.7-0.9,3.4-1.9l9.7-5.6c1.7-1,2.7-1.5,3.3-2c0.3-0.2,0.5-0.4,0.6-0.4c0.2-0.2,0.3-0.5,0.4-0.7c0-0.1,0-0.3,0.1-0.7  C46.3,51.2,46.3,50.1,46.3,48.1z M52.3,25.6c-1.2-1.3-2.8-2.3-6-4.1l-9.7-5.6C33.4,14,31.8,13,30,12.7c-1.5-0.3-3.1-0.3-4.6,0  c-1.7,0.4-3.3,1.3-6.6,3.2l-9.7,5.6c-3.2,1.9-4.9,2.8-6,4.1c-1,1.2-1.8,2.5-2.3,4c-0.5,1.7-0.5,3.6-0.5,7.3v11.2  c0,3.8,0,5.6,0.5,7.3c0.5,1.5,1.3,2.9,2.3,4c1.2,1.3,2.8,2.3,6,4.1l9.7,5.6c3.2,1.9,4.9,2.8,6.6,3.2c1.5,0.3,3.1,0.3,4.6,0  c1.7-0.4,3.3-1.3,6.6-3.2l9.7-5.6c3.2-1.9,4.9-2.8,6-4.1c1-1.2,1.8-2.5,2.3-4c0.5-1.7,0.5-3.6,0.5-7.3V36.9c0-3.8,0-5.6-0.5-7.3  C54.2,28.1,53.4,26.7,52.3,25.6z"
13 |     />
14 |     <path
15 |             fill="#2F80ED"
16 |             d="M42.5,55.5c0.2,0.1,0.4,0.3,0.7,0.4l8,4.6c-1.1,0.9-2.6,1.7-4.9,3.1l-3.8,2.2l-3.8-2.2  c-2.3-1.4-3.8-2.2-4.9-3.1l8-4.6C42.1,55.7,42.3,55.6,42.5,55.5z"
17 |     />
18 |     <path
19 |             fill="#2D9CDB"
20 |             d="M51.2,24.5c-1.1-0.9-2.6-1.7-4.9-3.1l-3.8-2.2l-3.8,2.2c-2.3,1.4-3.8,2.2-4.9,3.1l8,4.6  c0.2,0.1,0.5,0.3,0.7,0.4c0.2-0.1,0.4-0.3,0.7-0.4L51.2,24.5z"
21 |     />
22 | </svg>
23 | 


--------------------------------------------------------------------------------
/web/src/app/interfaces/relate.ts:
--------------------------------------------------------------------------------
1 | export interface Relate {
2 |   question: string;
3 | }
4 | 


--------------------------------------------------------------------------------
/web/src/app/interfaces/source.ts:
--------------------------------------------------------------------------------
 1 | export interface Source {
 2 |   id: string;
 3 |   name: string;
 4 |   url: string;
 5 |   isFamilyFriendly: boolean;
 6 |   displayUrl: string;
 7 |   snippet: string;
 8 |   deepLinks: { snippet: string; name: string; url: string }[];
 9 |   dateLastCrawled: string;
10 |   cachedPageUrl: string;
11 |   language: string;
12 |   primaryImageOfPage?: {
13 |     thumbnailUrl: string;
14 |     width: number;
15 |     height: number;
16 |     imageId: string;
17 |   };
18 |   isNavigational: boolean;
19 | }
20 | 


--------------------------------------------------------------------------------
/web/src/app/layout.tsx:
--------------------------------------------------------------------------------
 1 | import type { Metadata } from "next";
 2 | import { Inter } from "next/font/google";
 3 | import "./globals.css";
 4 | import { ReactNode } from "react";
 5 | 
 6 | const inter = Inter({ subsets: ["latin"] });
 7 | 
 8 | export const metadata: Metadata = {
 9 |   title: "Lepton Search",
10 |   description:
11 |     "Answer generated by large language models (LLMs). Double check for correctness.",
12 | };
13 | 
14 | export default function RootLayout({ children }: { children: ReactNode }) {
15 |   return (
16 |     <html lang="en">
17 |       <body className={inter.className}>{children}</body>
18 |     </html>
19 |   );
20 | }
21 | 


--------------------------------------------------------------------------------
/web/src/app/page.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | import { Footer } from "@/app/components/footer";
 3 | import { Logo } from "@/app/components/logo";
 4 | import { PresetQuery } from "@/app/components/preset-query";
 5 | import { Search } from "@/app/components/search";
 6 | import React from "react";
 7 | 
 8 | export default function Home() {
 9 |   return (
10 |     <div className="absolute inset-0 min-h-[500px] flex items-center justify-center">
11 |       <div className="relative flex flex-col gap-8 px-4 -mt-24">
12 |         <Logo></Logo>
13 |         <Search></Search>
14 |         <div className="flex gap-2 flex-wrap justify-center">
15 |           <PresetQuery query="Who said live long and prosper?"></PresetQuery>
16 |           <PresetQuery query="Why do we only see one side of the moon?"></PresetQuery>
17 |         </div>
18 |         <Footer></Footer>
19 |       </div>
20 |     </div>
21 |   );
22 | }
23 | 


--------------------------------------------------------------------------------
/web/src/app/search/page.tsx:
--------------------------------------------------------------------------------
 1 | "use client";
 2 | import { Result } from "@/app/components/result";
 3 | import { Search } from "@/app/components/search";
 4 | import { Title } from "@/app/components/title";
 5 | import { useSearchParams } from "next/navigation";
 6 | export default function SearchPage() {
 7 |   const searchParams = useSearchParams();
 8 |   const query = decodeURIComponent(searchParams.get("q") || "");
 9 |   const rid = decodeURIComponent(searchParams.get("rid") || "");
10 |   return (
11 |     <div className="absolute inset-0 bg-[url('/ui/bg.svg')]">
12 |       <div className="mx-auto max-w-3xl absolute inset-4 md:inset-8 bg-white">
13 |         <div className="h-20 pointer-events-none rounded-t-2xl w-full backdrop-filter absolute top-0 bg-gradient-to-t from-transparent to-white [mask-image:linear-gradient(to_bottom,white,transparent)]"></div>
14 |         <div className="px-4 md:px-8 pt-6 pb-24 rounded-2xl ring-8 ring-zinc-300/20 border border-zinc-200 h-full overflow-auto">
15 |           <Title query={query}></Title>
16 |           <Result key={rid} query={query} rid={rid}></Result>
17 |         </div>
18 |         <div className="h-80 pointer-events-none w-full rounded-b-2xl backdrop-filter absolute bottom-0 bg-gradient-to-b from-transparent to-white [mask-image:linear-gradient(to_top,white,transparent)]"></div>
19 |         <div className="absolute z-10 flex items-center justify-center bottom-6 px-4 md:px-8 w-full">
20 |           <div className="w-full">
21 |             <Search></Search>
22 |           </div>
23 |         </div>
24 |       </div>
25 |     </div>
26 |   );
27 | }
28 | 


--------------------------------------------------------------------------------
/web/src/app/utils/cn.ts:
--------------------------------------------------------------------------------
1 | import { type ClassValue, clsx } from "clsx";
2 | import { twMerge } from "tailwind-merge";
3 | 
4 | export function cn(...inputs: ClassValue[]) {
5 |   return twMerge(clsx(inputs));
6 | }
7 | 


--------------------------------------------------------------------------------
/web/src/app/utils/fetch-stream.ts:
--------------------------------------------------------------------------------
 1 | async function pump(
 2 |   reader: ReadableStreamDefaultReader<Uint8Array>,
 3 |   controller: ReadableStreamDefaultController,
 4 |   onChunk?: (chunk: Uint8Array) => void,
 5 |   onDone?: () => void,
 6 | ): Promise<ReadableStreamReadResult<Uint8Array> | undefined> {
 7 |   const { done, value } = await reader.read();
 8 |   if (done) {
 9 |     onDone && onDone();
10 |     controller.close();
11 |     return;
12 |   }
13 |   onChunk && onChunk(value);
14 |   controller.enqueue(value);
15 |   return pump(reader, controller, onChunk, onDone);
16 | }
17 | export const fetchStream = (
18 |   response: Response,
19 |   onChunk?: (chunk: Uint8Array) => void,
20 |   onDone?: () => void,
21 | ): ReadableStream<string> => {
22 |   const reader = response.body!.getReader();
23 |   return new ReadableStream({
24 |     start: (controller) => pump(reader, controller, onChunk, onDone),
25 |   });
26 | };
27 | 


--------------------------------------------------------------------------------
/web/src/app/utils/get-search-url.ts:
--------------------------------------------------------------------------------
1 | export const getSearchUrl = (query: string, search_uuid: string) => {
2 |   const prefix =
3 |     process.env.NODE_ENV === "production" ? "/search.html" : "/search";
4 |   return `${prefix}?q=${encodeURIComponent(query)}&rid=${search_uuid}`;
5 | };
6 | 


--------------------------------------------------------------------------------
/web/src/app/utils/parse-streaming.ts:
--------------------------------------------------------------------------------
 1 | import { Relate } from "@/app/interfaces/relate";
 2 | import { Source } from "@/app/interfaces/source";
 3 | import { fetchStream } from "@/app/utils/fetch-stream";
 4 | 
 5 | const LLM_SPLIT = "__LLM_RESPONSE__";
 6 | const RELATED_SPLIT = "__RELATED_QUESTIONS__";
 7 | 
 8 | export const parseStreaming = async (
 9 |   controller: AbortController,
10 |   query: string,
11 |   search_uuid: string,
12 |   onSources: (value: Source[]) => void,
13 |   onMarkdown: (value: string) => void,
14 |   onRelates: (value: Relate[]) => void,
15 |   onError?: (status: number) => void,
16 | ) => {
17 |   const decoder = new TextDecoder();
18 |   let uint8Array = new Uint8Array();
19 |   let chunks = "";
20 |   let sourcesEmitted = false;
21 |   const response = await fetch(`/query`, {
22 |     method: "POST",
23 |     headers: {
24 |       "Content-Type": "application/json",
25 |       Accept: "*./*",
26 |     },
27 |     signal: controller.signal,
28 |     body: JSON.stringify({
29 |       query,
30 |       search_uuid,
31 |     }),
32 |   });
33 |   if (response.status !== 200) {
34 |     onError?.(response.status);
35 |     return;
36 |   }
37 |   const markdownParse = (text: string) => {
38 |     onMarkdown(
39 |       text
40 |         .replace(/\[\[([cC])itation/g, "[citation")
41 |         .replace(/[cC]itation:(\d+)]]/g, "citation:$1]")
42 |         .replace(/\[\[([cC]itation:\d+)]](?!])/g, `[$1]`)
43 |         .replace(/\[[cC]itation:(\d+)]/g, "[citation]($1)"),
44 |     );
45 |   };
46 |   fetchStream(
47 |     response,
48 |     (chunk) => {
49 |       uint8Array = new Uint8Array([...uint8Array, ...chunk]);
50 |       chunks = decoder.decode(uint8Array, { stream: true });
51 |       if (chunks.includes(LLM_SPLIT)) {
52 |         const [sources, rest] = chunks.split(LLM_SPLIT);
53 |         if (!sourcesEmitted) {
54 |           try {
55 |             onSources(JSON.parse(sources));
56 |           } catch (e) {
57 |             onSources([]);
58 |           }
59 |         }
60 |         sourcesEmitted = true;
61 |         if (rest.includes(RELATED_SPLIT)) {
62 |           const [md] = rest.split(RELATED_SPLIT);
63 |           markdownParse(md);
64 |         } else {
65 |           markdownParse(rest);
66 |         }
67 |       }
68 |     },
69 |     () => {
70 |       const [_, relates] = chunks.split(RELATED_SPLIT);
71 |       try {
72 |         onRelates(JSON.parse(relates));
73 |       } catch (e) {
74 |         onRelates([]);
75 |       }
76 |     },
77 |   );
78 | };
79 | 


--------------------------------------------------------------------------------
/web/tailwind.config.ts:
--------------------------------------------------------------------------------
 1 | import type { Config } from "tailwindcss";
 2 | 
 3 | const config: Config = {
 4 |   content: [
 5 |     "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
 6 |     "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
 7 |     "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
 8 |   ],
 9 |   theme: {
10 |     extend: {
11 |       backgroundImage: {
12 |         "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
13 |         "gradient-conic":
14 |           "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
15 |       },
16 |       colors: {
17 |         blue: {
18 |           500: "#2F80ED",
19 |         },
20 |       },
21 |     },
22 |   },
23 |   plugins: [require("@tailwindcss/typography")],
24 | };
25 | export default config;
26 | 


--------------------------------------------------------------------------------
/web/tsconfig.json:
--------------------------------------------------------------------------------
 1 | {
 2 |   "compilerOptions": {
 3 |     "target": "es2015",
 4 |     "lib": [
 5 |       "dom",
 6 |       "dom.iterable",
 7 |       "esnext"
 8 |     ],
 9 |     "allowJs": true,
10 |     "skipLibCheck": true,
11 |     "strict": true,
12 |     "noEmit": true,
13 |     "esModuleInterop": true,
14 |     "module": "esnext",
15 |     "moduleResolution": "bundler",
16 |     "resolveJsonModule": true,
17 |     "isolatedModules": true,
18 |     "jsx": "preserve",
19 |     "incremental": true,
20 |     "plugins": [
21 |       {
22 |         "name": "next"
23 |       }
24 |     ],
25 |     "paths": {
26 |       "@/*": [
27 |         "./src/*"
28 |       ]
29 |     }
30 |   },
31 |   "include": [
32 |     "next-env.d.ts",
33 |     "**/*.ts",
34 |     "**/*.tsx",
35 |     ".next/types/**/*.ts",
36 |     "../ui/types/**/*.ts"
37 |   ],
38 |   "exclude": [
39 |     "node_modules"
40 |   ]
41 | }
42 | 


--------------------------------------------------------------------------------