[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n\n\n# Web related\n\n# dependencies\nnode_modules/\n/.pnp\n.pnp.js\n.yarn/install-state.gz\n\n# testing\n/coverage\n\n# next.js\n.next/\n/out/\n\n# production\n/build\n/ui\n\n# misc\n.DS_Store\n.idea\n*.pem\n\n# debug\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# local env files\n.env*.local\n\n# vercel\n.vercel\n\n# typescript\n*.tsbuildinfo\nnext-env.d.ts\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n<h1 align=\"center\">Search with Lepton</h1>\nBuild your own conversational search engine using less than 500 lines of code.\n<br/>\n<a href=\"https://search.lepton.run/\" target=\"_blank\"> Live Demo </a>\n<br/>\n<img width=\"70%\" src=\"https://github.com/leptonai/search_with_lepton/assets/1506722/845d7057-02cd-404e-bbc7-60f4bae89680\">\n</div>\n\n\n## Features\n- Built-in support for LLM\n- Built-in support for search engine\n- Customizable pretty UI interface\n- Shareable, cached search results\n\n## Setup Search Engine API\nThere are two default supported search engines: Bing and Google.\n \n### Bing Search\nTo 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.\n\n### Google Search\nYou 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.\n\n## Setup LLM and KV\n\n> [!NOTE]\n> We recommend using the built-in llm and kv functions with Lepton. \n> Running the following commands to set up them automatically.\n\n```shell\npip install -U leptonai openai && lep login\n```\n\n## Obtain Your Lepton AI Workspace Token\nYou can copy your workspace toke from the Lepton AI Dashboard &rarr; Settings &rarr; Tokens.\n\n\n## Build\n\n1. Set Bing subscription key\n```shell\nexport BING_SEARCH_V7_SUBSCRIPTION_KEY=YOUR_BING_SUBSCRIPTION_KEY\n```\n2. Set Lepton AI workspace token\n```shell\nexport LEPTON_WORKSPACE_TOKEN=YOUR_LEPTON_WORKSPACE_TOKEN\n```\n3. Build web\n```shell\ncd web && npm install && npm run build\n```\n4. Run server\n```shell\nBACKEND=BING python search_with_lepton.py\n```\n\nFor Google Search using SearchApi:\n```shell\nexport SEARCHAPI_API_KEY=YOUR_SEARCHAPI_API_KEY\nBACKEND=SEARCHAPI python search_with_lepton.py\n```\n\nFor Google Search using Serper:\n```shell\nexport SERPER_SEARCH_API_KEY=YOUR_SERPER_API_KEY\nBACKEND=SERPER python search_with_lepton.py\n```\n\nFor Google Search using Programmable Search Engine:\n```shell\nexport GOOGLE_SEARCH_API_KEY=YOUR_GOOGLE_SEARCH_API_KEY\nexport GOOGLE_SEARCH_CX=YOUR_GOOGLE_SEARCH_ENGINE_ID\nBACKEND=GOOGLE python search_with_lepton.py\n```\n\n\n\n## Deploy\n\nYou can deploy this to Lepton AI with one click:\n\n[![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)\n\nYou can also deploy your own version via\n\n```shell\nlep 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\n```\n\nLearn more about `lep photon` [here](https://www.lepton.ai/docs/references/lep_photon).\n"
  },
  {
    "path": "lepton_template/README.md",
    "content": "# Lepton Search\nBuild your own conversational search engine using less than 500 lines of code.\n\nSee a live demo site https://search.lepton.run/\n\nThe 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.\n\n## Setup Search Engine API\n\nYou 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.\n\n### Bing\n\nIf 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.\n\n### Google\n\nIf 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.\n\n### SearchApi\n\nIf 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.\n\n### Lepton Demo API\n\nIf 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.\n\n\n## Deployment Configurations\n\nHere are the configurations you can set for your deployment:\n* Name: The name of your deployment, like \"my-search\"\n* 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.\n\nThen, set the following environmental variables.\n\n* `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`.\n* `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.\n* `KV_NAME`: the Lepton KV to use to store the search results. You can use the default `search-with-lepton`.\n* `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.\n* `GOOGLE_SEARCH_CX`: if you are using google, specify the search cx. Otherwise, leave it empty.\n* `LEPTON_ENABLE_AUTH_BY_COOKIE`: this is to allow web UI access to the deployment. Set it to `true`.\n\nIn addition, you will need to set the following secrets:\n* `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).\n* `BING_SEARCH_V7_SUBSCRIPTION_KEY`: if you are using Bing, you need to specify the subscription key. Otherwise it is not needed.\n* `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.\n* `SEARCHAPI_API_KEY`: if you are using SearchApi, a 3rd party Google Search API, you need to specify the api key.\n\nOnce 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.\n\nOnce the status is turned into `Ready`, click the URL on the deployment card to access it. Enjoy!\n"
  },
  {
    "path": "search_with_lepton.py",
    "content": "import concurrent.futures\nimport glob\nimport json\nimport os\nimport re\nimport threading\nimport requests\nimport traceback\nfrom typing import Annotated, List, Generator, Optional\n\nfrom fastapi import HTTPException\nfrom fastapi.responses import HTMLResponse, StreamingResponse, RedirectResponse\nimport httpx\nfrom loguru import logger\n\nimport leptonai\nfrom leptonai import Client\nfrom leptonai.kv import KV\nfrom leptonai.photon import Photon, StaticFiles\nfrom leptonai.photon.types import to_bool\nfrom leptonai.api.v0.workspace import WorkspaceInfoLocalRecord\nfrom leptonai.util import tool\n\n################################################################################\n# Constant values for the RAG model.\n################################################################################\n\n# Search engine related. You don't really need to change this.\nBING_SEARCH_V7_ENDPOINT = \"https://api.bing.microsoft.com/v7.0/search\"\nBING_MKT = \"en-US\"\nGOOGLE_SEARCH_ENDPOINT = \"https://customsearch.googleapis.com/customsearch/v1\"\nSERPER_SEARCH_ENDPOINT = \"https://google.serper.dev/search\"\nSEARCHAPI_SEARCH_ENDPOINT = \"https://www.searchapi.io/api/v1/search\"\n\n# Specify the number of references from the search engine you want to use.\n# 8 is usually a good number.\nREFERENCE_COUNT = 8\n\n# Specify the default timeout for the search engine. If the search engine\n# does not respond within this time, we will return an error.\nDEFAULT_SEARCH_ENGINE_TIMEOUT = 5\n\n\n# If the user did not provide a query, we will use this default query.\n_default_query = \"Who said 'live long and prosper'?\"\n\n# This is really the most important part of the rag model. It gives instructions\n# to the model on how to generate the answer. Of course, different models may\n# behave differently, and we haven't tuned the prompt to make it optimal - this\n# is left to you, application creators, as an open problem.\n_rag_query_text = \"\"\"\nYou 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.\n\nYour 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.\n\nPlease 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.\n\nHere are the set of contexts:\n\n{context}\n\nRemember, don't blindly repeat the contexts verbatim. And here is the user question:\n\"\"\"\n\n# A set of stop words to use - this is not a complete set, and you may want to\n# add more given your observation.\nstop_words = [\n    \"<|im_end|>\",\n    \"[End]\",\n    \"[end]\",\n    \"\\nReferences:\\n\",\n    \"\\nSources:\\n\",\n    \"End.\",\n]\n\n# This is the prompt that asks the model to generate related questions to the\n# original question and the contexts.\n# Ideally, one want to include both the original question and the answer from the\n# model, but we are not doing that here: if we need to wait for the answer, then\n# the generation of the related questions will usually have to start only after\n# the whole answer is generated. This creates a noticeable delay in the response\n# time. As a result, and as you will see in the code, we will be sending out two\n# consecutive requests to the model: one for the answer, and one for the related\n# questions. This is not ideal, but it is a good tradeoff between response time\n# and quality.\n_more_questions_prompt = \"\"\"\nYou 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.\n\nHere are the contexts of the question:\n\n{context}\n\nRemember, 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:\n\"\"\"\n\n\ndef search_with_bing(query: str, subscription_key: str):\n    \"\"\"\n    Search with bing and return the contexts.\n    \"\"\"\n    params = {\"q\": query, \"mkt\": BING_MKT}\n    response = requests.get(\n        BING_SEARCH_V7_ENDPOINT,\n        headers={\"Ocp-Apim-Subscription-Key\": subscription_key},\n        params=params,\n        timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,\n    )\n    if not response.ok:\n        logger.error(f\"{response.status_code} {response.text}\")\n        raise HTTPException(response.status_code, \"Search engine error.\")\n    json_content = response.json()\n    try:\n        contexts = json_content[\"webPages\"][\"value\"][:REFERENCE_COUNT]\n    except KeyError:\n        logger.error(f\"Error encountered: {json_content}\")\n        return []\n    return contexts\n\n\ndef search_with_google(query: str, subscription_key: str, cx: str):\n    \"\"\"\n    Search with google and return the contexts.\n    \"\"\"\n    params = {\n        \"key\": subscription_key,\n        \"cx\": cx,\n        \"q\": query,\n        \"num\": REFERENCE_COUNT,\n    }\n    response = requests.get(\n        GOOGLE_SEARCH_ENDPOINT, params=params, timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT\n    )\n    if not response.ok:\n        logger.error(f\"{response.status_code} {response.text}\")\n        raise HTTPException(response.status_code, \"Search engine error.\")\n    json_content = response.json()\n    try:\n        contexts = json_content[\"items\"][:REFERENCE_COUNT]\n    except KeyError:\n        logger.error(f\"Error encountered: {json_content}\")\n        return []\n    return contexts\n\n\ndef search_with_serper(query: str, subscription_key: str):\n    \"\"\"\n    Search with serper and return the contexts.\n    \"\"\"\n    payload = json.dumps({\n        \"q\": query,\n        \"num\": (\n            REFERENCE_COUNT\n            if REFERENCE_COUNT % 10 == 0\n            else (REFERENCE_COUNT // 10 + 1) * 10\n        ),\n    })\n    headers = {\"X-API-KEY\": subscription_key, \"Content-Type\": \"application/json\"}\n    logger.info(\n        f\"{payload} {headers} {subscription_key} {query} {SERPER_SEARCH_ENDPOINT}\"\n    )\n    response = requests.post(\n        SERPER_SEARCH_ENDPOINT,\n        headers=headers,\n        data=payload,\n        timeout=DEFAULT_SEARCH_ENGINE_TIMEOUT,\n    )\n    if not response.ok:\n        logger.error(f\"{response.status_code} {response.text}\")\n        raise HTTPException(response.status_code, \"Search engine error.\")\n    json_content = response.json()\n    try:\n        # convert to the same format as bing/google\n        contexts = []\n        if json_content.get(\"knowledgeGraph\"):\n            url = json_content[\"knowledgeGraph\"].get(\"descriptionUrl\") or json_content[\"knowledgeGraph\"].get(\"website\")\n            snippet = json_content[\"knowledgeGraph\"].get(\"description\")\n            if url and snippet:\n                contexts.append({\n                    \"name\": json_content[\"knowledgeGraph\"].get(\"title\",\"\"),\n                    \"url\": url,\n                    \"snippet\": snippet\n                })\n        if json_content.get(\"answerBox\"):\n            url = json_content[\"answerBox\"].get(\"url\")\n            snippet = json_content[\"answerBox\"].get(\"snippet\") or json_content[\"answerBox\"].get(\"answer\")\n            if url and snippet:\n                contexts.append({\n                    \"name\": json_content[\"answerBox\"].get(\"title\",\"\"),\n                    \"url\": url,\n                    \"snippet\": snippet\n                })\n        contexts += [\n            {\"name\": c[\"title\"], \"url\": c[\"link\"], \"snippet\": c.get(\"snippet\",\"\")}\n            for c in json_content[\"organic\"]\n        ]\n        return contexts[:REFERENCE_COUNT]\n    except KeyError:\n        logger.error(f\"Error encountered: {json_content}\")\n        return []\n\ndef search_with_searchapi(query: str, subscription_key: str):\n    \"\"\"\n    Search with SearchApi.io and return the contexts.\n    \"\"\"\n    payload = {\n        \"q\": query,\n        \"engine\": \"google\",\n        \"num\": (\n            REFERENCE_COUNT\n            if REFERENCE_COUNT % 10 == 0\n            else (REFERENCE_COUNT // 10 + 1) * 10\n        ),\n    }\n    headers = {\"Authorization\": f\"Bearer {subscription_key}\", \"Content-Type\": \"application/json\"}\n    logger.info(\n        f\"{payload} {headers} {subscription_key} {query} {SEARCHAPI_SEARCH_ENDPOINT}\"\n    )\n    response = requests.get(\n        SEARCHAPI_SEARCH_ENDPOINT,\n        headers=headers,\n        params=payload,\n        timeout=30,\n    )\n    if not response.ok:\n        logger.error(f\"{response.status_code} {response.text}\")\n        raise HTTPException(response.status_code, \"Search engine error.\")\n    json_content = response.json()\n    try:\n        # convert to the same format as bing/google\n        contexts = []\n\n        if json_content.get(\"answer_box\"):\n            if json_content[\"answer_box\"].get(\"organic_result\"):\n                title = json_content[\"answer_box\"].get(\"organic_result\").get(\"title\", \"\")\n                url = json_content[\"answer_box\"].get(\"organic_result\").get(\"link\", \"\")\n            if json_content[\"answer_box\"].get(\"type\") == \"population_graph\":\n                title = json_content[\"answer_box\"].get(\"place\", \"\")\n                url = json_content[\"answer_box\"].get(\"explore_more_link\", \"\")\n\n            title = json_content[\"answer_box\"].get(\"title\", \"\")\n            url = json_content[\"answer_box\"].get(\"link\")\n            snippet =  json_content[\"answer_box\"].get(\"answer\") or json_content[\"answer_box\"].get(\"snippet\")\n\n            if url and snippet:\n                contexts.append({\n                    \"name\": title,\n                    \"url\": url,\n                    \"snippet\": snippet\n                })\n\n        if json_content.get(\"knowledge_graph\"):\n            if json_content[\"knowledge_graph\"].get(\"source\"):\n                url = json_content[\"knowledge_graph\"].get(\"source\").get(\"link\", \"\")\n\n            url = json_content[\"knowledge_graph\"].get(\"website\", \"\")\n            snippet = json_content[\"knowledge_graph\"].get(\"description\")\n\n            if url and snippet:\n                contexts.append({\n                    \"name\": json_content[\"knowledge_graph\"].get(\"title\", \"\"),\n                    \"url\": url,\n                    \"snippet\": snippet\n                })\n\n        contexts += [\n            {\"name\": c[\"title\"], \"url\": c[\"link\"], \"snippet\": c.get(\"snippet\", \"\")}\n            for c in json_content[\"organic_results\"]\n        ]\n        \n        if json_content.get(\"related_questions\"):\n            for question in json_content[\"related_questions\"]:\n                if question.get(\"source\"):\n                    url = question.get(\"source\").get(\"link\", \"\")\n                else:\n                    url = \"\"  \n                    \n                snippet = question.get(\"answer\", \"\")\n\n                if url and snippet:\n                    contexts.append({\n                        \"name\": question.get(\"question\", \"\"),\n                        \"url\": url,\n                        \"snippet\": snippet\n                    })\n\n        return contexts[:REFERENCE_COUNT]\n    except KeyError:\n        logger.error(f\"Error encountered: {json_content}\")\n        return []\n\nclass RAG(Photon):\n    \"\"\"\n    Retrieval-Augmented Generation Demo from Lepton AI.\n\n    This is a minimal example to show how to build a RAG engine with Lepton AI.\n    It uses search engine to obtain results based on user queries, and then uses\n    LLM models to generate the answer as well as related questions. The results\n    are then stored in a KV so that it can be retrieved later.\n    \"\"\"\n\n    requirement_dependency = [\n        \"openai\",  # for openai client usage.\n    ]\n\n    extra_files = glob.glob(\"ui/**/*\", recursive=True)\n\n    deployment_template = {\n        # All actual computations are carried out via remote apis, so\n        # we will use a cpu.small instance which is already enough for most of\n        # the work.\n        \"resource_shape\": \"cpu.small\",\n        # You most likely don't need to change this.\n        \"env\": {\n            # Choose the backend. Currently, we support BING and GOOGLE. For\n            # simplicity, in this demo, if you specify the backend as LEPTON,\n            # we will use the hosted serverless version of lepton search api\n            # at https://search-api.lepton.run/ to do the search and RAG, which\n            # runs the same code (slightly modified and might contain improvements)\n            # as this demo.\n            \"BACKEND\": \"LEPTON\",\n            # If you are using google, specify the search cx.\n            \"GOOGLE_SEARCH_CX\": \"\",\n            # Specify the LLM model you are going to use.\n            \"LLM_MODEL\": \"mixtral-8x7b\",\n            # For all the search queries and results, we will use the Lepton KV to\n            # store them so that we can retrieve them later. Specify the name of the\n            # KV here.\n            \"KV_NAME\": \"search-with-lepton\",\n            # If set to true, will generate related questions. Otherwise, will not.\n            \"RELATED_QUESTIONS\": \"true\",\n            # On the lepton platform, allow web access when you are logged in.\n            \"LEPTON_ENABLE_AUTH_BY_COOKIE\": \"true\",\n        },\n        # Secrets you need to have: search api subscription key, and lepton\n        # workspace token to query lepton's llama models.\n        \"secret\": [\n            # If you use BING, you need to specify the subscription key. Otherwise\n            # it is not needed.\n            \"BING_SEARCH_V7_SUBSCRIPTION_KEY\",\n            # If you use GOOGLE, you need to specify the search api key. Note that\n            # you should also specify the cx in the env.\n            \"GOOGLE_SEARCH_API_KEY\",\n            # If you use Serper, you need to specify the search api key.\n            \"SERPER_SEARCH_API_KEY\",\n            # If you use SearchApi, you need to specify the search api key.\n            \"SEARCHAPI_API_KEY\",\n            # You need to specify the workspace token to query lepton's LLM models.\n            \"LEPTON_WORKSPACE_TOKEN\",\n        ],\n    }\n\n    # It's just a bunch of api calls, so our own deployment can be made massively\n    # concurrent.\n    handler_max_concurrency = 16\n\n    def local_client(self):\n        \"\"\"\n        Gets a thread-local client, so in case openai clients are not thread safe,\n        each thread will have its own client.\n        \"\"\"\n        import openai\n\n        thread_local = threading.local()\n        try:\n            return thread_local.client\n        except AttributeError:\n            thread_local.client = openai.OpenAI(\n                base_url=f\"https://{self.model}.lepton.run/api/v1/\",\n                api_key=os.environ.get(\"LEPTON_WORKSPACE_TOKEN\")\n                or WorkspaceInfoLocalRecord.get_current_workspace_token(),\n                # We will set the connect timeout to be 10 seconds, and read/write\n                # timeout to be 120 seconds, in case the inference server is\n                # overloaded.\n                timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),\n            )\n            return thread_local.client\n\n    def init(self):\n        \"\"\"\n        Initializes photon configs.\n        \"\"\"\n        # First, log in to the workspace.\n        leptonai.api.v0.workspace.login()\n        self.backend = os.environ[\"BACKEND\"].upper()\n        if self.backend == \"LEPTON\":\n            self.leptonsearch_client = Client(\n                \"https://search-api.lepton.run/\",\n                token=os.environ.get(\"LEPTON_WORKSPACE_TOKEN\")\n                or WorkspaceInfoLocalRecord.get_current_workspace_token(),\n                stream=True,\n                timeout=httpx.Timeout(connect=10, read=120, write=120, pool=10),\n            )\n        elif self.backend == \"BING\":\n            self.search_api_key = os.environ[\"BING_SEARCH_V7_SUBSCRIPTION_KEY\"]\n            self.search_function = lambda query: search_with_bing(\n                query,\n                self.search_api_key,\n            )\n        elif self.backend == \"GOOGLE\":\n            self.search_api_key = os.environ[\"GOOGLE_SEARCH_API_KEY\"]\n            self.search_function = lambda query: search_with_google(\n                query,\n                self.search_api_key,\n                os.environ[\"GOOGLE_SEARCH_CX\"],\n            )\n        elif self.backend == \"SERPER\":\n            self.search_api_key = os.environ[\"SERPER_SEARCH_API_KEY\"]\n            self.search_function = lambda query: search_with_serper(\n                query,\n                self.search_api_key,\n            )\n        elif self.backend == \"SEARCHAPI\":\n            self.search_api_key = os.environ[\"SEARCHAPI_API_KEY\"]\n            self.search_function = lambda query: search_with_searchapi(\n                query,\n                self.search_api_key,\n            )\n        else:\n            raise RuntimeError(\"Backend must be LEPTON, BING, GOOGLE, SERPER or SEARCHAPI.\")\n        self.model = os.environ[\"LLM_MODEL\"]\n        # An executor to carry out async tasks, such as uploading to KV.\n        self.executor = concurrent.futures.ThreadPoolExecutor(\n            max_workers=self.handler_max_concurrency * 2\n        )\n        # Create the KV to store the search results.\n        logger.info(\"Creating KV. May take a while for the first time.\")\n        self.kv = KV(\n            os.environ[\"KV_NAME\"], create_if_not_exists=True, error_if_exists=False\n        )\n        # whether we should generate related questions.\n        self.should_do_related_questions = to_bool(os.environ[\"RELATED_QUESTIONS\"])\n\n    def get_related_questions(self, query, contexts):\n        \"\"\"\n        Gets related questions based on the query and context.\n        \"\"\"\n\n        def ask_related_questions(\n            questions: Annotated[\n                List[str],\n                [(\n                    \"question\",\n                    Annotated[\n                        str, \"related question to the original question and context.\"\n                    ],\n                )],\n            ]\n        ):\n            \"\"\"\n            ask further questions that are related to the input and output.\n            \"\"\"\n            pass\n\n        try:\n            response = self.local_client().chat.completions.create(\n                model=self.model,\n                messages=[\n                    {\n                        \"role\": \"system\",\n                        \"content\": _more_questions_prompt.format(\n                            context=\"\\n\\n\".join([c[\"snippet\"] for c in contexts])\n                        ),\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": query,\n                    },\n                ],\n                tools=[{\n                    \"type\": \"function\",\n                    \"function\": tool.get_tools_spec(ask_related_questions),\n                }],\n                max_tokens=512,\n            )\n            related = response.choices[0].message.tool_calls[0].function.arguments\n            if isinstance(related, str):\n                related = json.loads(related)\n            logger.trace(f\"Related questions: {related}\")\n            return related[\"questions\"][:5]\n        except Exception as e:\n            # For any exceptions, we will just return an empty list.\n            logger.error(\n                \"encountered error while generating related questions:\"\n                f\" {e}\\n{traceback.format_exc()}\"\n            )\n            return []\n\n    def _raw_stream_response(\n        self, contexts, llm_response, related_questions_future\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        A generator that yields the raw stream response. You do not need to call\n        this directly. Instead, use the stream_and_upload_to_kv which will also\n        upload the response to KV.\n        \"\"\"\n        # First, yield the contexts.\n        yield json.dumps(contexts)\n        yield \"\\n\\n__LLM_RESPONSE__\\n\\n\"\n        # Second, yield the llm response.\n        if not contexts:\n            # Prepend a warning to the user\n            yield (\n                \"(The search engine returned nothing for this query. Please take the\"\n                \" answer with a grain of salt.)\\n\\n\"\n            )\n        for chunk in llm_response:\n            if chunk.choices:\n                yield chunk.choices[0].delta.content or \"\"\n        # Third, yield the related questions. If any error happens, we will just\n        # return an empty list.\n        if related_questions_future is not None:\n            related_questions = related_questions_future.result()\n            try:\n                result = json.dumps(related_questions)\n            except Exception as e:\n                logger.error(f\"encountered error: {e}\\n{traceback.format_exc()}\")\n                result = \"[]\"\n            yield \"\\n\\n__RELATED_QUESTIONS__\\n\\n\"\n            yield result\n\n    def stream_and_upload_to_kv(\n        self, contexts, llm_response, related_questions_future, search_uuid\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        Streams the result and uploads to KV.\n        \"\"\"\n        # First, stream and yield the results.\n        all_yielded_results = []\n        for result in self._raw_stream_response(\n            contexts, llm_response, related_questions_future\n        ):\n            all_yielded_results.append(result)\n            yield result\n        # Second, upload to KV. Note that if uploading to KV fails, we will silently\n        # ignore it, because we don't want to affect the user experience.\n        _ = self.executor.submit(self.kv.put, search_uuid, \"\".join(all_yielded_results))\n\n    @Photon.handler(method=\"POST\", path=\"/query\")\n    def query_function(\n        self,\n        query: str,\n        search_uuid: str,\n        generate_related_questions: Optional[bool] = True,\n    ) -> StreamingResponse:\n        \"\"\"\n        Query the search engine and returns the response.\n\n        The query can have the following fields:\n            - query: the user query.\n            - search_uuid: a uuid that is used to store or retrieve the search result. If\n                the uuid does not exist, generate and write to the kv. If the kv\n                fails, we generate regardless, in favor of availability. If the uuid\n                exists, return the stored result.\n            - generate_related_questions: if set to false, will not generate related\n                questions. Otherwise, will depend on the environment variable\n                RELATED_QUESTIONS. Default: true.\n        \"\"\"\n        # Note that, if uuid exists, we don't check if the stored query is the same\n        # as the current query, and simply return the stored result. This is to enable\n        # the user to share a searched link to others and have others see the same result.\n        if search_uuid:\n            try:\n                result = self.kv.get(search_uuid)\n\n                def str_to_generator(result: str) -> Generator[str, None, None]:\n                    yield result\n\n                return StreamingResponse(str_to_generator(result))\n            except KeyError:\n                logger.info(f\"Key {search_uuid} not found, will generate again.\")\n            except Exception as e:\n                logger.error(\n                    f\"KV error: {e}\\n{traceback.format_exc()}, will generate again.\"\n                )\n        else:\n            raise HTTPException(status_code=400, detail=\"search_uuid must be provided.\")\n\n        if self.backend == \"LEPTON\":\n            # delegate to the lepton search api.\n            result = self.leptonsearch_client.query(\n                query=query,\n                search_uuid=search_uuid,\n                generate_related_questions=generate_related_questions,\n            )\n            return StreamingResponse(content=result, media_type=\"text/html\")\n\n        # First, do a search query.\n        query = query or _default_query\n        # Basic attack protection: remove \"[INST]\" or \"[/INST]\" from the query\n        query = re.sub(r\"\\[/?INST\\]\", \"\", query)\n        contexts = self.search_function(query)\n\n        system_prompt = _rag_query_text.format(\n            context=\"\\n\\n\".join(\n                [f\"[[citation:{i+1}]] {c['snippet']}\" for i, c in enumerate(contexts)]\n            )\n        )\n        try:\n            client = self.local_client()\n            llm_response = client.chat.completions.create(\n                model=self.model,\n                messages=[\n                    {\"role\": \"system\", \"content\": system_prompt},\n                    {\"role\": \"user\", \"content\": query},\n                ],\n                max_tokens=1024,\n                stop=stop_words,\n                stream=True,\n                temperature=0.9,\n            )\n            if self.should_do_related_questions and generate_related_questions:\n                # While the answer is being generated, we can start generating\n                # related questions as a future.\n                related_questions_future = self.executor.submit(\n                    self.get_related_questions, query, contexts\n                )\n            else:\n                related_questions_future = None\n        except Exception as e:\n            logger.error(f\"encountered error: {e}\\n{traceback.format_exc()}\")\n            return HTMLResponse(\"Internal server error.\", 503)\n\n        return StreamingResponse(\n            self.stream_and_upload_to_kv(\n                contexts, llm_response, related_questions_future, search_uuid\n            ),\n            media_type=\"text/html\",\n        )\n\n    @Photon.handler(mount=True)\n    def ui(self):\n        return StaticFiles(directory=\"ui\")\n\n    @Photon.handler(method=\"GET\", path=\"/\")\n    def index(self) -> RedirectResponse:\n        \"\"\"\n        Redirects \"/\" to the ui page.\n        \"\"\"\n        return RedirectResponse(url=\"/ui/index.html\")\n\n\nif __name__ == \"__main__\":\n    rag = RAG()\n    rag.launch()\n"
  },
  {
    "path": "web/.eslintrc.json",
    "content": "{\n  \"plugins\": [\"unused-imports\"],\n  \"extends\": [\n    \"next/core-web-vitals\",\n    \"plugin:prettier/recommended\"\n  ],\n  \"rules\": {\n    \"unused-imports/no-unused-imports\": \"error\"\n  }\n}\n"
  },
  {
    "path": "web/next.config.mjs",
    "content": "export default (phase, { defaultConfig }) => {\n  const env = process.env.NODE_ENV;\n  /**\n   * @type {import(\"next\").NextConfig}\n   */\n  if (env === \"production\") {\n    return {\n      output: \"export\",\n      assetPrefix: \"/ui/\",\n      basePath: \"/ui\",\n      distDir: \"../ui\"\n    };\n  } else {\n    return {\n      async rewrites() {\n        return [\n          {\n            source: \"/query\",\n            destination: \"http://localhost:8080/query\" // Proxy to Backend\n          }\n        ];\n      }\n    };\n  }\n}\n"
  },
  {
    "path": "web/package.json",
    "content": "{\n  \"name\": \"search\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"lint\": \"next lint\"\n  },\n  \"dependencies\": {\n    \"@next/third-parties\": \"^14.0.4\",\n    \"@radix-ui/react-popover\": \"^1.0.7\",\n    \"@tailwindcss/forms\": \"^0.5.7\",\n    \"@upstash/ratelimit\": \"^1.0.0\",\n    \"@vercel/kv\": \"^1.0.1\",\n    \"clsx\": \"^2.1.0\",\n    \"headlessui\": \"^0.0.0\",\n    \"lucide-react\": \"^0.309.0\",\n    \"mdast-util-from-markdown\": \"^2.0.0\",\n    \"nanoid\": \"^5.0.4\",\n    \"next\": \"14.2.22\",\n    \"react\": \"^18\",\n    \"react-dom\": \"^18\",\n    \"react-markdown\": \"^9.0.1\",\n    \"tailwind-merge\": \"^2.2.0\",\n    \"unist-builder\": \"^4.0.0\"\n  },\n  \"devDependencies\": {\n    \"@tailwindcss/typography\": \"^0.5.10\",\n    \"@types/node\": \"^20\",\n    \"@types/react\": \"^18\",\n    \"@types/react-dom\": \"^18\",\n    \"autoprefixer\": \"^10.0.1\",\n    \"eslint\": \"^8\",\n    \"eslint-config-next\": \"14.0.4\",\n    \"eslint-config-prettier\": \"^9.0.0\",\n    \"eslint-plugin-prettier\": \"^5.0.1\",\n    \"eslint-plugin-unused-imports\": \"^3.0.0\",\n    \"postcss\": \"^8\",\n    \"prettier\": \"^3.1.0\",\n    \"tailwindcss\": \"^3.3.0\",\n    \"typescript\": \"^5\"\n  }\n}\n"
  },
  {
    "path": "web/postcss.config.js",
    "content": "module.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n"
  },
  {
    "path": "web/src/app/components/answer.tsx",
    "content": "import {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/app/components/popover\";\nimport { Skeleton } from \"@/app/components/skeleton\";\nimport { Wrapper } from \"@/app/components/wrapper\";\nimport { Source } from \"@/app/interfaces/source\";\nimport { BookOpenText } from \"lucide-react\";\nimport { FC } from \"react\";\nimport Markdown from \"react-markdown\";\n\nexport const Answer: FC<{ markdown: string; sources: Source[] }> = ({\n  markdown,\n  sources,\n}) => {\n  return (\n    <Wrapper\n      title={\n        <>\n          <BookOpenText></BookOpenText> Answer\n        </>\n      }\n      content={\n        markdown ? (\n          <div className=\"prose prose-sm max-w-full\">\n            <Markdown\n              components={{\n                a: ({ node: _, ...props }) => {\n                  if (!props.href) return <></>;\n                  const source = sources[+props.href - 1];\n                  if (!source) return <></>;\n                  return (\n                    <span className=\"inline-block w-4\">\n                      <Popover>\n                        <PopoverTrigger asChild>\n                          <span\n                            title={source.name}\n                            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\"\n                          >\n                            {props.href}\n                          </span>\n                        </PopoverTrigger>\n                        <PopoverContent\n                          align={\"start\"}\n                          className=\"max-w-screen-md flex flex-col gap-2 bg-white shadow-transparent ring-zinc-50 ring-4 text-xs\"\n                        >\n                          <div className=\"text-ellipsis overflow-hidden whitespace-nowrap font-medium\">\n                            {source.name}\n                          </div>\n                          <div className=\"flex gap-4\">\n                            {source.primaryImageOfPage?.thumbnailUrl && (\n                              <div className=\"flex-none\">\n                                <img\n                                  className=\"rounded h-16 w-16\"\n                                  width={source.primaryImageOfPage?.width}\n                                  height={source.primaryImageOfPage?.height}\n                                  src={source.primaryImageOfPage?.thumbnailUrl}\n                                />\n                              </div>\n                            )}\n                            <div className=\"flex-1\">\n                              <div className=\"line-clamp-4 text-zinc-500 break-words\">\n                                {source.snippet}\n                              </div>\n                            </div>\n                          </div>\n\n                          <div className=\"flex gap-2 items-center\">\n                            <div className=\"flex-1 overflow-hidden\">\n                              <div className=\"text-ellipsis text-blue-500 overflow-hidden whitespace-nowrap\">\n                                <a\n                                  title={source.name}\n                                  href={source.url}\n                                  target=\"_blank\"\n                                >\n                                  {source.url}\n                                </a>\n                              </div>\n                            </div>\n                            <div className=\"flex-none flex items-center relative\">\n                              <img\n                                className=\"h-3 w-3\"\n                                alt={source.url}\n                                src={`https://www.google.com/s2/favicons?domain=${source.url}&sz=${16}`}\n                              />\n                            </div>\n                          </div>\n                        </PopoverContent>\n                      </Popover>\n                    </span>\n                  );\n                },\n              }}\n            >\n              {markdown}\n            </Markdown>\n          </div>\n        ) : (\n          <div className=\"flex flex-col gap-2\">\n            <Skeleton className=\"max-w-sm h-4 bg-zinc-200\"></Skeleton>\n            <Skeleton className=\"max-w-lg h-4 bg-zinc-200\"></Skeleton>\n            <Skeleton className=\"max-w-2xl h-4 bg-zinc-200\"></Skeleton>\n            <Skeleton className=\"max-w-lg h-4 bg-zinc-200\"></Skeleton>\n            <Skeleton className=\"max-w-xl h-4 bg-zinc-200\"></Skeleton>\n          </div>\n        )\n      }\n    ></Wrapper>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/footer.tsx",
    "content": "import { Mails } from \"lucide-react\";\nimport { FC } from \"react\";\n\nexport const Footer: FC = () => {\n  return (\n    <div className=\"text-center flex flex-col items-center text-xs text-zinc-700 gap-1\">\n      <div className=\"text-zinc-400\">\n        Answer generated by large language models, plz double check for\n        correctness.\n      </div>\n      <div className=\"text-zinc-400\">\n        LLM, Vector DB, and other components powered by the Lepton AI platform.\n      </div>\n      <div className=\"flex gap-2 justify-center\">\n        <div>\n          <a\n            className=\"text-blue-500 font-medium inline-flex gap-1 items-center flex-nowrap text-nowrap\"\n            href=\"mailto:info@lepton.ai\"\n          >\n            <Mails size={8} />\n            Talk to us\n          </a>\n        </div>\n        <div>if you need a performant and scalable AI cloud!</div>\n      </div>\n\n      <div className=\"flex items-center justify-center flex-wrap gap-x-4 gap-y-2 mt-2 text-zinc-400\">\n        <a className=\"hover:text-zinc-950\" href=\"https://lepton.ai/\">\n          Lepton Home\n        </a>\n        <a\n          className=\"hover:text-zinc-950\"\n          href=\"https://dashboard.lepton.ai/playground\"\n        >\n          API Playground\n        </a>\n        <a\n          className=\"hover:text-zinc-950\"\n          href=\"https://github.com/leptonai/leptonai\"\n        >\n          Python Library\n        </a>\n        <a className=\"hover:text-zinc-950\" href=\"https://twitter.com/leptonai\">\n          Twitter\n        </a>\n        <a className=\"hover:text-zinc-950\" href=\"https://leptonai.medium.com/\">\n          Blog\n        </a>\n      </div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/logo.tsx",
    "content": "import React, { FC } from \"react\";\n\nexport const Logo: FC = () => {\n  return (\n    <div className=\"flex gap-4 items-center justify-center cursor-default select-none relative\">\n      <div className=\"h-10 w-10\">\n        <svg viewBox=\"0 0 85 85\" className=\"h-full w-full\">\n          <path\n            fillRule=\"evenodd\"\n            clipRule=\"evenodd\"\n            fill=\"#2D9CDB\"\n            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\"\n          ></path>\n          <path\n            fillRule=\"evenodd\"\n            clipRule=\"evenodd\"\n            fill=\"#2F80ED\"\n            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\"\n          ></path>\n          <path\n            fill=\"#2F80ED\"\n            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\"\n          ></path>\n          <path\n            fill=\"#2D9CDB\"\n            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\"\n          ></path>\n        </svg>\n      </div>\n      <div className=\"text-center font-medium text-2xl md:text-3xl text-zinc-950 relative text-nowrap\">\n        Lepton Search\n      </div>\n      <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\">\n        beta\n      </div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/popover.tsx",
    "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\n\nimport { cn } from \"@/app/utils/cn\";\n\nconst Popover = PopoverPrimitive.Root;\n\nconst PopoverTrigger = PopoverPrimitive.Trigger;\n\nconst PopoverContent = React.forwardRef<\n  React.ElementRef<typeof PopoverPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n  <PopoverPrimitive.Portal>\n    <PopoverPrimitive.Content\n      ref={ref}\n      align={align}\n      sideOffset={sideOffset}\n      className={cn(\n        \"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\",\n        className,\n      )}\n      {...props}\n    />\n  </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = PopoverPrimitive.Content.displayName;\n\nexport { Popover, PopoverTrigger, PopoverContent };\n"
  },
  {
    "path": "web/src/app/components/preset-query.tsx",
    "content": "import { getSearchUrl } from \"@/app/utils/get-search-url\";\nimport { nanoid } from \"nanoid\";\nimport Link from \"next/link\";\nimport React, { FC, useMemo } from \"react\";\n\nexport const PresetQuery: FC<{ query: string }> = ({ query }) => {\n  const rid = useMemo(() => nanoid(), [query]);\n\n  return (\n    <Link\n      prefetch={false}\n      title={query}\n      href={getSearchUrl(query, rid)}\n      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\"\n    >\n      {query}\n    </Link>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/relates.tsx",
    "content": "import { PresetQuery } from \"@/app/components/preset-query\";\nimport { Skeleton } from \"@/app/components/skeleton\";\nimport { Wrapper } from \"@/app/components/wrapper\";\nimport { Relate } from \"@/app/interfaces/relate\";\nimport { MessageSquareQuote } from \"lucide-react\";\nimport React, { FC } from \"react\";\n\nexport const Relates: FC<{ relates: Relate[] | null }> = ({ relates }) => {\n  return (\n    <Wrapper\n      title={\n        <>\n          <MessageSquareQuote></MessageSquareQuote> Related\n        </>\n      }\n      content={\n        <div className=\"flex gap-2 flex-col\">\n          {relates !== null ? (\n            relates.length > 0 ? (\n              relates.map(({ question }) => (\n                <PresetQuery key={question} query={question}></PresetQuery>\n              ))\n            ) : (\n              <div className=\"text-sm\">No related questions.</div>\n            )\n          ) : (\n            <>\n              <Skeleton className=\"w-full h-5 bg-zinc-200/80\"></Skeleton>\n              <Skeleton className=\"w-full h-5 bg-zinc-200/80\"></Skeleton>\n              <Skeleton className=\"w-full h-5 bg-zinc-200/80\"></Skeleton>\n            </>\n          )}\n        </div>\n      }\n    ></Wrapper>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/result.tsx",
    "content": "\"use client\";\nimport { Answer } from \"@/app/components/answer\";\nimport { Relates } from \"@/app/components/relates\";\nimport { Sources } from \"@/app/components/sources\";\nimport { Relate } from \"@/app/interfaces/relate\";\nimport { Source } from \"@/app/interfaces/source\";\nimport { parseStreaming } from \"@/app/utils/parse-streaming\";\nimport { Annoyed } from \"lucide-react\";\nimport { FC, useEffect, useState } from \"react\";\n\nexport const Result: FC<{ query: string; rid: string }> = ({ query, rid }) => {\n  const [sources, setSources] = useState<Source[]>([]);\n  const [markdown, setMarkdown] = useState<string>(\"\");\n  const [relates, setRelates] = useState<Relate[] | null>(null);\n  const [error, setError] = useState<number | null>(null);\n  useEffect(() => {\n    const controller = new AbortController();\n    void parseStreaming(\n      controller,\n      query,\n      rid,\n      setSources,\n      setMarkdown,\n      setRelates,\n      setError,\n    );\n    return () => {\n      controller.abort();\n    };\n  }, [query]);\n  return (\n    <div className=\"flex flex-col gap-8\">\n      <Answer markdown={markdown} sources={sources}></Answer>\n      <Sources sources={sources}></Sources>\n      <Relates relates={relates}></Relates>\n      {error && (\n        <div className=\"absolute inset-4 flex items-center justify-center bg-white/40 backdrop-blur-sm\">\n          <div className=\"p-4 bg-white shadow-2xl rounded text-blue-500 font-medium flex gap-4\">\n            <Annoyed></Annoyed>\n            {error === 429\n              ? \"Sorry, you have made too many requests recently, try again later.\"\n              : \"Sorry, we might be overloaded, try again later.\"}\n          </div>\n        </div>\n      )}\n    </div>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/search.tsx",
    "content": "\"use client\";\nimport { getSearchUrl } from \"@/app/utils/get-search-url\";\nimport { ArrowRight } from \"lucide-react\";\nimport { nanoid } from \"nanoid\";\nimport { useRouter } from \"next/navigation\";\nimport React, { FC, useState } from \"react\";\n\nexport const Search: FC = () => {\n  const [value, setValue] = useState(\"\");\n  const router = useRouter();\n  return (\n    <form\n      onSubmit={(e) => {\n        e.preventDefault();\n        if (value) {\n          setValue(\"\");\n          router.push(getSearchUrl(encodeURIComponent(value), nanoid()));\n        }\n      }}\n    >\n      <label\n        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\"\n        htmlFor=\"search-bar\"\n      >\n        <input\n          id=\"search-bar\"\n          value={value}\n          onChange={(e) => setValue(e.target.value)}\n          autoFocus\n          placeholder=\"Ask Lepton AI anything ...\"\n          className=\"px-2 pr-6 w-full rounded-md flex-1 outline-none bg-white\"\n        />\n        <button\n          type=\"submit\"\n          className=\"w-auto py-1 px-2 bg-black border-black text-white fill-white active:scale-95 border overflow-hidden relative rounded-xl\"\n        >\n          <ArrowRight size={16} />\n        </button>\n      </label>\n    </form>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/skeleton.tsx",
    "content": "import { cn } from \"@/app/utils/cn\";\nimport { HTMLAttributes } from \"react\";\n\nfunction Skeleton({ className, ...props }: HTMLAttributes<HTMLDivElement>) {\n  return (\n    <div\n      className={cn(\"animate-pulse rounded-md bg-muted\", className)}\n      {...props}\n    />\n  );\n}\n\nexport { Skeleton };\n"
  },
  {
    "path": "web/src/app/components/sources.tsx",
    "content": "import { Skeleton } from \"@/app/components/skeleton\";\nimport { Wrapper } from \"@/app/components/wrapper\";\nimport { Source } from \"@/app/interfaces/source\";\nimport { BookText } from \"lucide-react\";\nimport { FC } from \"react\";\n\nconst SourceItem: FC<{ source: Source; index: number }> = ({\n  source,\n  index,\n}) => {\n  const { id, name, url } = source;\n  const domain = new URL(url).hostname;\n  return (\n    <div\n      className=\"relative text-xs py-3 px-3 bg-zinc-100 hover:bg-zinc-200 rounded-lg flex flex-col gap-2\"\n      key={id}\n    >\n      <a href={url} target=\"_blank\" className=\"absolute inset-0\"></a>\n      <div className=\"font-medium text-zinc-950 text-ellipsis overflow-hidden whitespace-nowrap break-words\">\n        {name}\n      </div>\n      <div className=\"flex gap-2 items-center\">\n        <div className=\"flex-1 overflow-hidden\">\n          <div className=\"text-ellipsis whitespace-nowrap break-all text-zinc-400 overflow-hidden w-full\">\n            {index + 1} - {domain}\n          </div>\n        </div>\n        <div className=\"flex-none flex items-center\">\n          <img\n            className=\"h-3 w-3\"\n            alt={domain}\n            src={`https://www.google.com/s2/favicons?domain=${domain}&sz=${16}`}\n          />\n        </div>\n      </div>\n    </div>\n  );\n};\n\nexport const Sources: FC<{ sources: Source[] }> = ({ sources }) => {\n  return (\n    <Wrapper\n      title={\n        <>\n          <BookText></BookText> Sources\n        </>\n      }\n      content={\n        <div className=\"grid grid-cols-2 sm:grid-cols-4 gap-2\">\n          {sources.length > 0 ? (\n            sources.map((item, index) => (\n              <SourceItem\n                key={item.id}\n                index={index}\n                source={item}\n              ></SourceItem>\n            ))\n          ) : (\n            <>\n              <Skeleton className=\"max-w-sm h-16 bg-zinc-200/80\"></Skeleton>\n              <Skeleton className=\"max-w-sm h-16 bg-zinc-200/80\"></Skeleton>\n              <Skeleton className=\"max-w-sm h-16 bg-zinc-200/80\"></Skeleton>\n              <Skeleton className=\"max-w-sm h-16 bg-zinc-200/80\"></Skeleton>\n            </>\n          )}\n        </div>\n      }\n    ></Wrapper>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/title.tsx",
    "content": "\"use client\";\nimport { getSearchUrl } from \"@/app/utils/get-search-url\";\nimport { RefreshCcw } from \"lucide-react\";\nimport { nanoid } from \"nanoid\";\nimport { useRouter } from \"next/navigation\";\n\nexport const Title = ({ query }: { query: string }) => {\n  const router = useRouter();\n  return (\n    <div className=\"flex items-center pb-4 mb-6 border-b gap-4\">\n      <div\n        className=\"flex-1 text-lg sm:text-xl text-black text-ellipsis overflow-hidden whitespace-nowrap\"\n        title={query}\n      >\n        {query}\n      </div>\n      <div className=\"flex-none\">\n        <button\n          onClick={() => {\n            router.push(getSearchUrl(encodeURIComponent(query), nanoid()));\n          }}\n          type=\"button\"\n          className=\"rounded flex gap-2 items-center bg-transparent px-2 py-1 text-xs font-semibold text-blue-500 hover:bg-zinc-100\"\n        >\n          <RefreshCcw size={12}></RefreshCcw>Rewrite\n        </button>\n      </div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "web/src/app/components/wrapper.tsx",
    "content": "import { FC, ReactNode } from \"react\";\n\nexport const Wrapper: FC<{\n  title: ReactNode;\n  content: ReactNode;\n}> = ({ title, content }) => {\n  return (\n    <div className=\"flex flex-col gap-4 w-full\">\n      <div className=\"flex gap-2 text-blue-500\">{title}</div>\n      {content}\n    </div>\n  );\n};\n"
  },
  {
    "path": "web/src/app/globals.css",
    "content": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\ninput:-webkit-autofill,\ninput:-webkit-autofill:hover,\ninput:-webkit-autofill:focus,\ntextarea:-webkit-autofill,\ntextarea:-webkit-autofill:hover,\ntextarea:-webkit-autofill:focus,\nselect:-webkit-autofill,\nselect:-webkit-autofill:hover,\nselect:-webkit-autofill:focus {\n  -webkit-background-clip: text;\n}\n"
  },
  {
    "path": "web/src/app/interfaces/relate.ts",
    "content": "export interface Relate {\n  question: string;\n}\n"
  },
  {
    "path": "web/src/app/interfaces/source.ts",
    "content": "export interface Source {\n  id: string;\n  name: string;\n  url: string;\n  isFamilyFriendly: boolean;\n  displayUrl: string;\n  snippet: string;\n  deepLinks: { snippet: string; name: string; url: string }[];\n  dateLastCrawled: string;\n  cachedPageUrl: string;\n  language: string;\n  primaryImageOfPage?: {\n    thumbnailUrl: string;\n    width: number;\n    height: number;\n    imageId: string;\n  };\n  isNavigational: boolean;\n}\n"
  },
  {
    "path": "web/src/app/layout.tsx",
    "content": "import type { Metadata } from \"next\";\nimport { Inter } from \"next/font/google\";\nimport \"./globals.css\";\nimport { ReactNode } from \"react\";\n\nconst inter = Inter({ subsets: [\"latin\"] });\n\nexport const metadata: Metadata = {\n  title: \"Lepton Search\",\n  description:\n    \"Answer generated by large language models (LLMs). Double check for correctness.\",\n};\n\nexport default function RootLayout({ children }: { children: ReactNode }) {\n  return (\n    <html lang=\"en\">\n      <body className={inter.className}>{children}</body>\n    </html>\n  );\n}\n"
  },
  {
    "path": "web/src/app/page.tsx",
    "content": "\"use client\";\nimport { Footer } from \"@/app/components/footer\";\nimport { Logo } from \"@/app/components/logo\";\nimport { PresetQuery } from \"@/app/components/preset-query\";\nimport { Search } from \"@/app/components/search\";\nimport React from \"react\";\n\nexport default function Home() {\n  return (\n    <div className=\"absolute inset-0 min-h-[500px] flex items-center justify-center\">\n      <div className=\"relative flex flex-col gap-8 px-4 -mt-24\">\n        <Logo></Logo>\n        <Search></Search>\n        <div className=\"flex gap-2 flex-wrap justify-center\">\n          <PresetQuery query=\"Who said live long and prosper?\"></PresetQuery>\n          <PresetQuery query=\"Why do we only see one side of the moon?\"></PresetQuery>\n        </div>\n        <Footer></Footer>\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "web/src/app/search/page.tsx",
    "content": "\"use client\";\nimport { Result } from \"@/app/components/result\";\nimport { Search } from \"@/app/components/search\";\nimport { Title } from \"@/app/components/title\";\nimport { useSearchParams } from \"next/navigation\";\nexport default function SearchPage() {\n  const searchParams = useSearchParams();\n  const query = decodeURIComponent(searchParams.get(\"q\") || \"\");\n  const rid = decodeURIComponent(searchParams.get(\"rid\") || \"\");\n  return (\n    <div className=\"absolute inset-0 bg-[url('/ui/bg.svg')]\">\n      <div className=\"mx-auto max-w-3xl absolute inset-4 md:inset-8 bg-white\">\n        <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>\n        <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\">\n          <Title query={query}></Title>\n          <Result key={rid} query={query} rid={rid}></Result>\n        </div>\n        <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>\n        <div className=\"absolute z-10 flex items-center justify-center bottom-6 px-4 md:px-8 w-full\">\n          <div className=\"w-full\">\n            <Search></Search>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "web/src/app/utils/cn.ts",
    "content": "import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n"
  },
  {
    "path": "web/src/app/utils/fetch-stream.ts",
    "content": "async function pump(\n  reader: ReadableStreamDefaultReader<Uint8Array>,\n  controller: ReadableStreamDefaultController,\n  onChunk?: (chunk: Uint8Array) => void,\n  onDone?: () => void,\n): Promise<ReadableStreamReadResult<Uint8Array> | undefined> {\n  const { done, value } = await reader.read();\n  if (done) {\n    onDone && onDone();\n    controller.close();\n    return;\n  }\n  onChunk && onChunk(value);\n  controller.enqueue(value);\n  return pump(reader, controller, onChunk, onDone);\n}\nexport const fetchStream = (\n  response: Response,\n  onChunk?: (chunk: Uint8Array) => void,\n  onDone?: () => void,\n): ReadableStream<string> => {\n  const reader = response.body!.getReader();\n  return new ReadableStream({\n    start: (controller) => pump(reader, controller, onChunk, onDone),\n  });\n};\n"
  },
  {
    "path": "web/src/app/utils/get-search-url.ts",
    "content": "export const getSearchUrl = (query: string, search_uuid: string) => {\n  const prefix =\n    process.env.NODE_ENV === \"production\" ? \"/search.html\" : \"/search\";\n  return `${prefix}?q=${encodeURIComponent(query)}&rid=${search_uuid}`;\n};\n"
  },
  {
    "path": "web/src/app/utils/parse-streaming.ts",
    "content": "import { Relate } from \"@/app/interfaces/relate\";\nimport { Source } from \"@/app/interfaces/source\";\nimport { fetchStream } from \"@/app/utils/fetch-stream\";\n\nconst LLM_SPLIT = \"__LLM_RESPONSE__\";\nconst RELATED_SPLIT = \"__RELATED_QUESTIONS__\";\n\nexport const parseStreaming = async (\n  controller: AbortController,\n  query: string,\n  search_uuid: string,\n  onSources: (value: Source[]) => void,\n  onMarkdown: (value: string) => void,\n  onRelates: (value: Relate[]) => void,\n  onError?: (status: number) => void,\n) => {\n  const decoder = new TextDecoder();\n  let uint8Array = new Uint8Array();\n  let chunks = \"\";\n  let sourcesEmitted = false;\n  const response = await fetch(`/query`, {\n    method: \"POST\",\n    headers: {\n      \"Content-Type\": \"application/json\",\n      Accept: \"*./*\",\n    },\n    signal: controller.signal,\n    body: JSON.stringify({\n      query,\n      search_uuid,\n    }),\n  });\n  if (response.status !== 200) {\n    onError?.(response.status);\n    return;\n  }\n  const markdownParse = (text: string) => {\n    onMarkdown(\n      text\n        .replace(/\\[\\[([cC])itation/g, \"[citation\")\n        .replace(/[cC]itation:(\\d+)]]/g, \"citation:$1]\")\n        .replace(/\\[\\[([cC]itation:\\d+)]](?!])/g, `[$1]`)\n        .replace(/\\[[cC]itation:(\\d+)]/g, \"[citation]($1)\"),\n    );\n  };\n  fetchStream(\n    response,\n    (chunk) => {\n      uint8Array = new Uint8Array([...uint8Array, ...chunk]);\n      chunks = decoder.decode(uint8Array, { stream: true });\n      if (chunks.includes(LLM_SPLIT)) {\n        const [sources, rest] = chunks.split(LLM_SPLIT);\n        if (!sourcesEmitted) {\n          try {\n            onSources(JSON.parse(sources));\n          } catch (e) {\n            onSources([]);\n          }\n        }\n        sourcesEmitted = true;\n        if (rest.includes(RELATED_SPLIT)) {\n          const [md] = rest.split(RELATED_SPLIT);\n          markdownParse(md);\n        } else {\n          markdownParse(rest);\n        }\n      }\n    },\n    () => {\n      const [_, relates] = chunks.split(RELATED_SPLIT);\n      try {\n        onRelates(JSON.parse(relates));\n      } catch (e) {\n        onRelates([]);\n      }\n    },\n  );\n};\n"
  },
  {
    "path": "web/tailwind.config.ts",
    "content": "import type { Config } from \"tailwindcss\";\n\nconst config: Config = {\n  content: [\n    \"./src/pages/**/*.{js,ts,jsx,tsx,mdx}\",\n    \"./src/components/**/*.{js,ts,jsx,tsx,mdx}\",\n    \"./src/app/**/*.{js,ts,jsx,tsx,mdx}\",\n  ],\n  theme: {\n    extend: {\n      backgroundImage: {\n        \"gradient-radial\": \"radial-gradient(var(--tw-gradient-stops))\",\n        \"gradient-conic\":\n          \"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))\",\n      },\n      colors: {\n        blue: {\n          500: \"#2F80ED\",\n        },\n      },\n    },\n  },\n  plugins: [require(\"@tailwindcss/typography\")],\n};\nexport default config;\n"
  },
  {
    "path": "web/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2015\",\n    \"lib\": [\n      \"dom\",\n      \"dom.iterable\",\n      \"esnext\"\n    ],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"noEmit\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"preserve\",\n    \"incremental\": true,\n    \"plugins\": [\n      {\n        \"name\": \"next\"\n      }\n    ],\n    \"paths\": {\n      \"@/*\": [\n        \"./src/*\"\n      ]\n    }\n  },\n  \"include\": [\n    \"next-env.d.ts\",\n    \"**/*.ts\",\n    \"**/*.tsx\",\n    \".next/types/**/*.ts\",\n    \"../ui/types/**/*.ts\"\n  ],\n  \"exclude\": [\n    \"node_modules\"\n  ]\n}\n"
  }
]