[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS]\n - Browser [e.g. chrome, safari]\n - Version [e.g. 22]\n\n**Smartphone (please complete the following information):**\n - Device: [e.g. iPhone6]\n - OS: [e.g. iOS8.1]\n - Browser [e.g. stock browser, safari]\n - Version [e.g. 22]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE/pull_request_template.md",
    "content": "# Pull Request Template\n\n## Description\n\nPlease include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.\n\nFixes # (issue)\n\n## Type of change\n\nPlease delete options that are not relevant.\n\n- [ ] Bug fix (non-breaking change which fixes an issue)\n- [ ] New feature (non-breaking change which adds functionality)\n- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)\n- [ ] This change requires a documentation update\n\n## How Has This Been Tested?\n\nPlease describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration\n\n- [ ] Test A\n- [ ] Test B\n\n## Checklist:\n\n- [ ] My code follows the style guidelines of this project\n- [ ] I have performed a self-review of my own code\n- [ ] I have commented my code, particularly in hard-to-understand areas\n- [ ] I have made corresponding changes to the documentation\n- [ ] My changes generate no new warnings\n- [ ] I have added tests that prove my fix is effective or that my feature works\n- [ ] New and existing unit tests pass locally with my changes\n- [ ] Any dependent changes have been merged and published in downstream modules\n\n## Additional context\n\nAdd any other context or screenshots about the pull request here.\n"
  },
  {
    "path": ".gitignore",
    "content": "/rag-venv\n/ragsaas-venvs\nbackend/poetry.lock\nbackend/rag_config.json\nbackend/data/**\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\n.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to RAG-SaaS\n\nFirst off, thank you for considering contributing to RAG-SaaS! It's people like you that make RAG-SaaS such a great tool. We welcome contributions from everyone, whether it's a bug report, feature request, documentation improvement, or a code contribution.\n\n## Table of Contents\n\n1. [Code of Conduct](#code-of-conduct)\n2. [Getting Started](#getting-started)\n3. [How Can I Contribute?](#how-can-i-contribute)\n   - [Reporting Bugs](#reporting-bugs)\n   - [Suggesting Enhancements](#suggesting-enhancements)\n   - [Your First Code Contribution](#your-first-code-contribution)\n   - [Pull Requests](#pull-requests)\n4. [Style Guidelines](#style-guidelines)\n   - [Git Commit Messages](#git-commit-messages)\n   - [Python Style Guide](#python-style-guide)\n   - [JavaScript Style Guide](#javascript-style-guide)\n5. [Additional Notes](#additional-notes)\n\n## Code of Conduct\n\nThis project and everyone participating in it is governed by the [RAG-SaaS Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [adithyaskolavi@gmail.com](mailto:adithyaskolavi@gmail.com).\n\n## Getting Started\n\n1. Fork the repository on GitHub\n2. Clone your fork locally\n3. Set up your environment (see README.md for details)\n4. Create a branch for your changes\n5. Make your changes\n6. Run tests and ensure they pass\n7. Commit your changes\n8. Push your changes to your fork\n9. Open a pull request\n\n## How Can I Contribute?\n\n### Reporting Bugs\n\n- Before submitting a bug report, please check the existing issues to see if someone has already reported the problem.\n- When you are creating a bug report, please include as many details as possible. Fill out the required template, the information it asks for helps us resolve issues faster.\n\n### Suggesting Enhancements\n\n- Before creating enhancement suggestions, please check the existing issues to see if the enhancement has already been suggested.\n- When you are creating an enhancement suggestion, please include as many details as possible. Fill in the template, including the steps that you imagine you would take if the feature you're requesting existed.\n\n### Your First Code Contribution\n\nUnsure where to begin contributing to RAG-SaaS? You can start by looking through these `beginner` and `help-wanted` issues:\n\n- [Beginner issues](https://github.com/adithya-s-k/RAG-SaaS/labels/beginner) - issues which should only require a few lines of code, and a test or two.\n- [Help wanted issues](https://github.com/adithya-s-k/RAG-SaaS/labels/help%20wanted) - issues which should be a bit more involved than `beginner` issues.\n\n### Pull Requests\n\n- Fill in the required template\n- Do not include issue numbers in the PR title\n- Include screenshots and animated GIFs in your pull request whenever possible\n- Follow the [Python](#python-style-guide) and [JavaScript](#javascript-style-guide) style guides\n- Document new code based on the Documentation Style Guide\n- End all files with a newline\n\n## Style Guidelines\n\n### Git Commit Messages\n\n- Use the present tense (\"Add feature\" not \"Added feature\")\n- Use the imperative mood (\"Move cursor to...\" not \"Moves cursor to...\")\n- Limit the first line to 72 characters or less\n- Reference issues and pull requests liberally after the first line\n\n### Python Style Guide\n\n- Follow [PEP 8](https://www.python.org/dev/peps/pep-0008/)\n- Use 4 spaces for indentation (not tabs)\n- Use docstrings for functions and classes\n- Use type hints where possible\n\n### JavaScript Style Guide\n\n- Use 2 spaces for indentation (not tabs)\n- Use semicolons at the end of each statement\n- Use single quotes for strings\n- Use camelCase for variable and function names\n- Use PascalCase for class names\n\n## Additional Notes\n\n### Issue and Pull Request Labels\n\nThis section lists the labels we use to help us track and manage issues and pull requests.\n\n- `bug` - Issues for bugs in the code\n- `enhancement` - Issues for new features or improvements\n- `documentation` - Issues related to documentation\n- `good first issue` - Good for newcomers\n- `help wanted` - Extra attention is needed\n- `question` - Further information is requested\n\nThank you for contributing to RAG-SaaS!\n"
  },
  {
    "path": "LICENSE",
    "content": "RAG-SaaS Dual License\n\nThis project is licensed under two licenses:\n\n1. Apache License, Version 2.0 (for students, developers, and individuals)\n2. GNU General Public License v3.0 (for companies and commercial use)\n\nThe full text of both licenses is included below. Please see LICENSING.md for details on which license applies to your use case.\n\n---\n\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1.  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\n2.  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\n3.  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\n4.  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\n5.  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\n6.  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\n7.  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\n8.  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\n9.  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\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: 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\nCopyright [2024] [Adithya S Kolavi]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n---\n\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n                            Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work\nfor making modifications to it. \"Object code\" means any non-source\nform of a work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) 2024  Adithya S Kolavi\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) 2024  Adithya S Kolavi\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License. Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "LICENSING.md",
    "content": "# Licensing for RAG-SaaS\n\nRAG-SaaS is released under a dual licensing model designed to accommodate both open-source and commercial use.\n\n## For Students, Developers, Individuals, and Educational Institutions\n\nIf you are a student, individual developer, educational institution, or using this software for non-profit educational purposes (including commercial projects for educational purposes), you may use, modify, and distribute this software under the terms of the **Apache License 2.0**.\n\nThe Apache License 2.0 allows you to:\n\n- Use the software for any purpose, including commercial purposes\n- Modify the software and distribute your modifications\n- Distribute the software, in source or binary forms\n- Sublicense the software\n\nFor the full terms of the Apache License 2.0, please see the [LICENSE](LICENSE) file in this repository.\n\n## For Companies and Commercial Use (Non-Educational)\n\nIf you are a company or using this software for commercial purposes outside of educational contexts, you must use this software under the terms of the **GNU General Public License v3.0 (GPL-3.0)**.\n\nThe GPL-3.0 requires that:\n\n- Any modifications to the software must also be released under the GPL-3.0\n- If you distribute the software, you must make the source code available\n- Any software that incorporates GPL-3.0 licensed code must also be released under the GPL-3.0\n\nFor the full terms of the GNU General Public License v3.0, please see the [LICENSE](LICENSE) file in this repository.\n\n## Choosing the Appropriate License\n\n1. If you are a student, individual developer, or educational institution (including for commercial educational projects), you may choose to use the software under the Apache License 2.0.\n\n2. If you are a company or using the software for non-educational commercial purposes, you must use the software under the GNU General Public License v3.0.\n\n## Additional Notes\n\n- This dual licensing model is designed to promote open-source use and development while also ensuring that commercial entities contribute back to the open-source community.\n- If you are unsure which license applies to your use case, please contact us for clarification.\n- Contributions to this project will be accepted under the terms of both licenses.\n\n## Contact\n\nIf you have any questions about licensing, please open an issue in the GitHub repository or contact the project maintainers at [your contact email].\n\nBy using this software, you agree to abide by the terms of the applicable license.\n"
  },
  {
    "path": "README.md",
    "content": "<h2 align=\"center\">RAG SaaS</h2>\n<p align=\"center\">\n  Ship RAG solutions quickly⚡\n</p>\n\n<p align=\"center\">\n  <img alt=\"RAG-SaaS Logo\" src=\"./assets/banner.png\" width=\"80%\">\n</p>\n\n<p align=\"center\">\n  <strong>A end to end SaaS Solution for Retrieval-Augmented Generation (RAG) <br> and Agentic based applications.</strong><br>\n\n</p>\n\n<p align=\"center\">\n  <a href=\"#-features\">Features</a> ·\n  <a href=\"#%EF%B8%8F-tech-stack\">Tech Stack</a> ·\n  <a href=\"#-getting-started\">Getting Started</a> ·\n  <a href=\"#-docker-compose-deployment\">Deployment</a> ·\n  <a href=\"#roadmap\">Roadmap</a>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://github.com/adithya-s-k/RAG-SaaS/stargazers\">\n    <img src=\"https://img.shields.io/github/stars/adithya-s-k/RAG-SaaS?style=social\" alt=\"GitHub Stars\">\n  </a>\n  <a href=\"https://github.com/adithya-s-k/RAG-SaaS/network/members\">\n    <img src=\"https://img.shields.io/github/forks/adithya-s-k/RAG-SaaS?style=social\" alt=\"GitHub Forks\">\n  </a>\n  <a href=\"https://github.com/adithya-s-k/RAG-SaaS/issues\">\n    <img src=\"https://img.shields.io/github/issues/adithya-s-k/RAG-SaaS\" alt=\"GitHub Issues\">\n  </a>\n  <a href=\"https://github.com/adithya-s-k/RAG-SaaS/pulls\">\n    <img src=\"https://img.shields.io/github/issues-pr/adithya-s-k/RAG-SaaS\" alt=\"GitHub Pull Requests\">\n  </a>\n</p>\n\n\n\n<table>\n    <tr>\n        <th>Features</th>\n        <th>Demo Video</th>\n    </tr>\n    <tr>\n        <td>\n            <ul>\n                <li>🔐 Basic Authentication</li>\n                <li>💬 Chat History Tracking</li>\n                <li>🧠 Multiple RAG Variations\n                    <ul>\n                        <li>Basic RAG</li>\n                        <li>Two additional configurations</li>\n                    </ul>\n                </li>\n                <li>👨‍💼 Admin Dashboard\n                    <ul>\n                        <li>📥 Data Ingestion</li>\n                        <li>📊 Monitoring</li>\n                        <li>👁️ Observability</li>\n                        <li>🔄 RAG Configuration Switching</li>\n                    </ul>\n                </li>\n                <li>🗄️ S3 Integration for PDF uploads</li>\n                <li>🐳 Easy Deployment with Docker / Docker Compose</li>\n            </ul>\n        </td>\n        <td>\n          <div align=\"center\">\n  \n![f937cd54-217f-4106-81b6-56636a17306f (1)](https://github.com/user-attachments/assets/2f2c75fa-a3f0-4311-9a43-554d8cb3e04e)\n</div>\n        </td>\n    </tr>\n</table>\n\n<div align=\"center\">\n<video width=\"100%\" src=\"https://github.com/user-attachments/assets/f6de3ae5-bcc9-480c-bc46-dee69ec22795\" alt=\"Demo Video RAG SAAS\">\n</div>\n\n\n## Tech Stack\n\n- 🦙 LlamaIndex: For building and orchestrating RAG pipelines\n- 📦 MongoDB: Used as both a normal database and a vector database\n- ⚡ FastAPI: Backend API framework\n- ⚛️ Next.js: Frontend framework\n- 🔍 Qdrant: Vector database for efficient similarity search\n- 👁️ Arize Phoenix: Observability Platform to monitor/evaluate your RAG system\n\n## 🌟 Why RAG-SaaS?\n\nSetting up reliable RAG systems can be time-consuming and complex. RAG-SaaS allows developers to focus on fine-tuning and developing their RAG pipeline rather than worrying about packaging it into a usable application. Built on top of [create-llama](https://www.llamaindex.ai/blog/create-llama-a-command-line-tool-to-generate-llamaindex-apps-8f7683021191) by LlamaIndex, RAG-SaaS provides a solid foundation for your RAG-based projects.\n\n## 🚀 Getting Started\n\n1. Clone the repository:\n   ```bash\n   git clone https://github.com/adithya-s-k/RAG-SaaS.git\n   cd RAG-SaaS\n   ```\n\n## 🐳 Docker Compose Deployment\n\n### Environment Variables\n\n<details>\n<summary>🔑 How to Set up .env</summary>\n\n### Environment Variables\n\nTo properly configure and run RAG-SaaS, you need to set up several environment variables. These are divided into three main sections: Frontend, Backend, and Docker Compose. Here's a detailed explanation of each:\n\n#### Frontend Environment (./frontend/.env.local)\n\n- `NEXT_PUBLIC_SERVER_URL`: (Compulsory) The endpoint URL of your FastAPI server.\n- `NEXT_PUBLIC_CHAT_API`: (Compulsory) Derived from NEXT_SERVER_URL, typically set to `${NEXT_PUBLIC_SERVER_URL}/api/chat`.\n\n#### Backend Environment (./backend/.env)\n\n1. Model Configuration:\n\n   - `MODEL_PROVIDER`: (Compulsory) The AI model provider (e.g., 'openai').\n   - `MODEL`: (Compulsory) The name of the LLM model to use.\n   - `EMBEDDING_MODEL`: (Compulsory) The name of the embedding model.\n   - `EMBEDDING_DIM`: (Compulsory) The dimensionality of the embedding model.\n\n2. OpenAI Configuration:\n\n   - `OPENAI_API_KEY`: (Compulsory) Your OpenAI API key.\n\n3. Application Settings:\n\n   - `CONVERSATION_STARTERS`: (Compulsory) A list of starter questions for users.\n   - `SYSTEM_PROMPT`: (Compulsory) The system prompt for the AI model.\n   - `SYSTEM_CITATION_PROMPT`: (Optional) Additional prompt for citation.\n   - `APP_HOST`: (Compulsory) The host address for the backend (default: '0.0.0.0').\n   - `APP_PORT`: (Compulsory) The port for the backend (default: 8000).\n\n4. Database Configuration:\n\n   - `MONGODB_URI`: (Compulsory) The MongoDB connection URI.\n   - `MONGODB_NAME`: (Compulsory) The MongoDB database name (default: 'RAGSAAS').\n   - `QDRANT_URL`: (Compulsory) The URL for the Qdrant server.\n   - `QDRANT_COLLECTION`: (Compulsory) The Qdrant collection name.\n   - `QDRANT_API_KEY`: (Optional) API key for Qdrant authentication.\n\n5. Authentication:\n\n   - `JWT_SECRET_KEY`: (Compulsory) Secret key for signing JWT tokens.\n   - `JWT_REFRESH_SECRET_KEY`: (Compulsory) Secret key for signing JWT refresh tokens.\n   - `ADMIN_EMAIL`: (Compulsory) Administrator email for application login.\n   - `ADMIN_PASSWORD`: (Compulsory) Administrator password for application login.\n\n6. AWS S3 Configuration (Optional):\n\n   - `AWS_ACCESS_KEY_ID`: AWS Access Key ID.\n   - `AWS_SECRET_ACCESS_KEY`: AWS Secret Access Key.\n   - `AWS_REGION`: AWS Region for your services.\n   - `BUCKET_NAME`: The name of the S3 bucket to use.\n\n7. Observability:\n   - `ARIZE_PHOENIX_ENDPOINT`: (Optional) Endpoint for Arize Phoenix observability.\n\n#### S3 Integration\n\nTo enable S3 integration for PDF uploads/Ingestion:\n\n1. Set the following environment variables in your `.env` file:\n\n```\n\nAWS_ACCESS_KEY_ID=your_access_key\nAWS_SECRET_ACCESS_KEY=your_secret_key\nAWS_REGION=bucket_region\nBUCKET_NAME=your_bucket_name\n\n```\n\n### Docker Compose Env (./env)\n\n```\n  backend:\n    build:\n      context: ./backend\n      dockerfile: Dockerfile\n    image: ragsaas/backend:latest\n    container_name: backend\n    ports:\n      - '8000:8000'\n    environment:\n      # MongoDB Configuration\n      MONGODB_NAME: RAGSAAS\n      MONGODB_URI: mongodb://admin:password@mongodb:27017/\n      # Qdrant Configuration\n      QDRANT_COLLECTION: default\n      QDRANT_URL: http://qdrant:6333\n      # QDRANT_API_KEY:\n      # OPENAI_API_KEY is compulsory\n      OPENAI_API_KEY:\n      # Backend Application Configuration\n      MODEL_PROVIDER: openai\n      MODEL: gpt-4o-mini\n      EMBEDDING_MODEL: text-embedding-3-small\n      EMBEDDING_DIM: 1536\n      FILESERVER_URL_PREFIX: http://backend:8000/api/files\n      SYSTEM_PROMPT: 'You are a helpful assistant who helps users with their questions.'\n      APP_HOST: 0.0.0.0\n      APP_PORT: 8000\n      JWT_SECRET_KEY:\n      JWT_REFRESH_SECRET_KEY:\n      ARIZE_PHOENIX_ENDPOINT: http://arizephoenix:4317\n```\n\n</details>\n\nFor Docker Compose deployment, use:\n\n```bash\ndocker compose up -d\n```\n\nPull down the containers\n\n```bash\ndocker compose down\n```\n\n### Development Mode\n\nTo run the project in development mode, follow these steps:\n\n1. **Start the Next.js Frontend:**\n\n   Navigate to the `frontend` directory and install the required dependencies. Then, run the development server:\n\n   ```bash\n   cd frontend\n   npm install\n   npm run dev\n   ```\n\n2. **Set Up the Vector Database (Qdrant), Database (MongoDB), and Observability Platform (Arize Phoenix):**\n\n   You can either self-host these services using Docker or use hosted solutions.\n\n   **Self-Hosted Options:**\n\n   - Qdrant:\n\n     ```bash\n     docker pull qdrant/qdrant\n     ```\n\n   - MongoDB:\n\n     ```bash\n     docker pull mongo\n     ```\n\n   - Arize Phoenix:\n     ```bash\n     docker pull arizephoenix/phoenix\n     ```\n\n   **Hosted Options:**\n\n   - Qdrant Cloud: [Qdrant Cloud](https://cloud.qdrant.io/)\n   - MongoDB Atlas: [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)\n   - Arize Phoenix: [Arize Phoenix](https://app.phoenix.arize.com/)\n\n3. **Start the FastAPI Server:**\n\n   Navigate to the `backend` directory and set up the Python environment. You can use either Conda or Python's built-in `venv`:\n\n   ```bash\n   cd backend\n   ```\n\n   **Using Conda:**\n\n   ```bash\n   conda create -n ragsaas-venv python=3.11\n   conda activate ragsaas-venv\n   ```\n\n   **Using Python's `venv`:**\n\n   ```bash\n   python -m venv ragsaas-venv\n   \\ragsaas-venv\\Scripts\\activate  # On Windows\n   source ragsaas-venv/bin/activate  # On macOS/Linux\n   ```\n\n   Install the required dependencies and run the server:\n\n   ```bash\n   pip install -e .\n   python main.py\n   ```\n\n---\n\n## Roadmap\n\n- [x] add support to store ingested data in AWS S3\n- [x] Add Docker compose for each set up\n- [x] Implement Observability\n- [ ] Improve authentication system\n- [ ] Integrate OmniParse API for efficient Data ingestion\n- [ ] Provide more control to Admin over RAG configuration\n- [ ] Implement Advanced and Agentic RAG\n\n## 👥 Contributing\n\nWe welcome contributions to RAG-SaaS! Please see our [CONTRIBUTING.md](CONTRIBUTING.md) for more details on how to get started.\n\n## 📄 Licensing\n\nThis project is available under a dual license:\n\n- Apache License 2.0 for students, developers, and individuals\n- GNU General Public License v3.0 for companies and commercial use\n\nSee the [LICENSING.md](LICENSING.md) file for more details.\n\n## 🙏 Acknowledgements\n\nThis project is built on the following frameworks, technologies and tools:\n\n- [LlamaIndex](https://www.llamaindex.ai/) for the create-llama tool and RAG orchestration\n- [FastAPI](https://fastapi.tiangolo.com/)\n- [Next.js](https://nextjs.org/)\n- [MongoDB](https://www.mongodb.com/)\n- [Qdrant](https://qdrant.tech/)\n- [Arize Phoenix](https://docs.arize.com/phoenix)\n\n## Contact & Support\n\n### Bug Reports\n\nIf you encounter any issues or bugs, please report them in the [Issues](https://github.com/adithya-s-k/RAG-SaaS/issues) tab of our GitHub repository.\n\n### Commercial Use & Custom Solutions\n\nFor inquiries regarding:\n\n- Commercial licensing\n- Custom modifications\n- Managed deployment\n- Specialized integrations\n\nPlease contact: adithyaskolavi@gmail.com\n\nWe're here to help tailor RAG-SaaS to your specific needs and ensure you get the most out of our solution.\n\n## Star History\n\n<p align=\"center\">\n  <a href=\"https://cognitivelab.in\">\n    <img src=\"https://api.star-history.com/svg?repos=adithya-s-k/RAG-SaaS&type=Date\" alt=\"Star History Chart\">\n  </a>\n</p>\n"
  },
  {
    "path": "backend/.gitignore",
    "content": "__pycache__\nstorage\n.env\noutput\n"
  },
  {
    "path": "backend/Dockerfile",
    "content": "FROM python:3.11 as build\n\nWORKDIR /app\n\nENV PYTHONPATH=/app\n\n# Install Poetry\nRUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \\\n    cd /usr/local/bin && \\\n    ln -s /opt/poetry/bin/poetry && \\\n    poetry config virtualenvs.create false\n\n# Install Chromium for web loader\n# Can disable this if you don't use the web loader to reduce the image size\nRUN apt update && apt install -y chromium chromium-driver\n\n# Install dependencies\nCOPY ./pyproject.toml ./poetry.lock* /app/\nRUN poetry install --no-root --no-cache --only main\n\n# ====================================\nFROM build as release\n\nCOPY . .\n\nCMD [\"python\", \"main.py\"]"
  },
  {
    "path": "backend/README.md",
    "content": "This is a [LlamaIndex](https://www.llamaindex.ai/) project using [FastAPI](https://fastapi.tiangolo.com/) bootstrapped with [`create-llama`](https://github.com/run-llama/LlamaIndexTS/tree/main/packages/create-llama).\n\n## Getting Started\n\nFirst, setup the environment with poetry:\n\n> **_Note:_** This step is not needed if you are using the dev-container.\n\n```\npoetry install\npoetry shell\n```\n\nThen check the parameters that have been pre-configured in the `.env` file in this directory. (E.g. you might need to configure an `OPENAI_API_KEY` if you're using OpenAI as model provider).\n\nIf you are using any tools or data sources, you can update their config files in the `config` folder.\n\nSecond, generate the embeddings of the documents in the `./data` directory (if this folder exists - otherwise, skip this step):\n\n```\npoetry run generate\n```\n\nThird, run the development server:\n\n```\npython main.py\n```\n\nThe example provides two different API endpoints:\n\n1. `/api/chat` - a streaming chat endpoint\n2. `/api/chat/request` - a non-streaming chat endpoint\n\nYou can test the streaming endpoint with the following curl request:\n\n```\ncurl --location 'localhost:8000/api/chat' \\\n--header 'Content-Type: application/json' \\\n--data '{ \"messages\": [{ \"role\": \"user\", \"content\": \"Hello\" }] }'\n```\n\nAnd for the non-streaming endpoint run:\n\n```\ncurl --location 'localhost:8000/api/chat/request' \\\n--header 'Content-Type: application/json' \\\n--data '{ \"messages\": [{ \"role\": \"user\", \"content\": \"Hello\" }] }'\n```\n\nYou can start editing the API endpoints by modifying `app/api/chat/chat.py`. The endpoints auto-update as you save the file. You can delete the endpoint you're not using.\n\nOpen [http://localhost:8000/docs](http://localhost:8000/docs) with your browser to see the Swagger UI of the API.\n\nThe API allows CORS for all origins to simplify development. You can change this behavior by setting the `ENVIRONMENT` environment variable to `prod`:\n\n```\nENVIRONMENT=prod python main.py\n```\n\n## Using Docker\n\n1. Build an image for the FastAPI app:\n\n```\ndocker build -t <your_backend_image_name> .\n```\n\n2. Generate embeddings:\n\nParse the data and generate the vector embeddings if the `./data` folder exists - otherwise, skip this step:\n\n```\ndocker run \\\n  --rm \\\n  -v $(pwd)/.env:/app/.env \\ # Use ENV variables and configuration from your file-system\n  -v $(pwd)/config:/app/config \\\n  -v $(pwd)/data:/app/data \\ # Use your local folder to read the data\n  -v $(pwd)/storage:/app/storage \\ # Use your file system to store the vector database\n  <your_backend_image_name> \\\n  poetry run generate\n```\n\n3. Start the API:\n\n```\ndocker run \\\n  -v $(pwd)/.env:/app/.env \\ # Use ENV variables and configuration from your file-system\n  -v $(pwd)/config:/app/config \\\n  -v $(pwd)/storage:/app/storage \\ # Use your file system to store gea vector database\n  -p 8000:8000 \\\n  <your_backend_image_name>\n```\n\n## Learn More\n\nTo learn more about LlamaIndex, take a look at the following resources:\n\n- [LlamaIndex Documentation](https://docs.llamaindex.ai) - learn about LlamaIndex.\n\nYou can check out [the LlamaIndex GitHub repository](https://github.com/run-llama/llama_index) - your feedback and contributions are welcome!\n"
  },
  {
    "path": "backend/app/__init__.py",
    "content": ""
  },
  {
    "path": "backend/app/api/__init__.py",
    "content": ""
  },
  {
    "path": "backend/app/api/admin/__init__.py",
    "content": "from .route import admin_router\n\n__all__ = [\"admin_router\"]"
  },
  {
    "path": "backend/app/api/admin/route.py",
    "content": "import os\n\nfrom grpc import Status\nimport boto3\nimport tempfile\nimport shutil\nfrom dotenv import load_dotenv\nfrom fastapi import APIRouter, File, UploadFile, Depends, HTTPException, status\nfrom fastapi.responses import JSONResponse\nfrom typing import List, Dict, Any, Optional\nfrom pydantic import BaseModel, EmailStr, Field\nfrom app.core.user import get_current_user\nfrom app.models.user_model import User\nfrom app.services.admin_service import admin_service\nfrom app.schemas.admin_schema import UserOut, UsersOut, MessageOut, ErrorOut\nfrom app.services.config_service import config_service\nfrom llama_index.core.ingestion import IngestionPipeline\nfrom llama_index.core.node_parser import SentenceSplitter\nfrom llama_index.core.settings import Settings\nfrom app.api.chat.engine.vectordb import get_vector_store\nfrom llama_index.core import SimpleDirectoryReader\nfrom llama_index.core.schema import Document\nfrom phoenix.trace import using_project\n\nadmin_router = APIRouter()\n\nload_dotenv()\n# AWS configuration\n\nAWS_ACCESS_KEY_ID = os.getenv(\"AWS_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = os.getenv(\"AWS_SECRET_ACCESS_KEY\")\nAWS_REGION = os.getenv(\"AWS_REGION\")\nAWS_S3_BUCKET_NAME = os.getenv(\"AWS_S3_BUCKET_NAME\")\n\n# Local storage configuration\nDATA_DIR = os.getenv(\"DATA_DIR\", \"data\")\nPRIVATE_STORE_PATH = os.path.join(DATA_DIR)\n\n\ndef get_documents(\n    directory: str, recursive: bool = True, filename_as_id: bool = True\n) -> List[Document]:\n    \"\"\"\n    Load documents from a specified directory using SimpleDirectoryReader.\n\n    Args:\n        directory (str): The path to the directory containing the documents.\n        recursive (bool, optional): Whether to recursively search for documents in subdirectories. Defaults to True.\n        filename_as_id (bool, optional): Whether to use the filename as the document ID. Defaults to True.\n\n    Returns:\n        List[Document]: A list of loaded documents.\n    \"\"\"\n    reader = SimpleDirectoryReader(\n        directory, recursive=recursive, filename_as_id=filename_as_id\n    )\n    documents = reader.load_data(show_progress=True)\n    return documents\n\n\nclass UserUpdate(BaseModel):\n    first_name: Optional[str] = None\n    last_name: Optional[str] = None\n    email: Optional[EmailStr] = None\n    role: Optional[str] = None\n    disabled: Optional[bool] = None\n\n\ndef verify_admin(current_user: User = Depends(get_current_user)):\n    if current_user.role != \"admin\":\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"You don't have permission to access this resource\",\n        )\n    return current_user\n\n\n@admin_router.get(\n    \"/users\", response_model=UsersOut, responses={403: {\"model\": ErrorOut}}\n)\nasync def get_all_users(admin: User = Depends(verify_admin)) -> UsersOut:\n    users = await admin_service.get_all_users()\n    return UsersOut(users=[UserOut(**user) for user in users])\n\n\n@admin_router.get(\n    \"/users/{user_id}\",\n    response_model=UserOut,\n    responses={403: {\"model\": ErrorOut}, 404: {\"model\": ErrorOut}},\n)\nasync def get_user(user_id: str, admin: User = Depends(verify_admin)) -> UserOut:\n    user = await admin_service.get_user_by_id(user_id)\n    if not user:\n        raise HTTPException(status_code=404, detail=\"User not found\")\n    return UserOut(**user)\n\n\n@admin_router.put(\n    \"/users/{user_id}\",\n    response_model=MessageOut,\n    responses={403: {\"model\": ErrorOut}, 404: {\"model\": ErrorOut}},\n)\nasync def edit_user(\n    user_id: str, user_update: UserUpdate, admin: User = Depends(verify_admin)\n) -> MessageOut:\n    success = await admin_service.edit_user(\n        user_id, user_update.model_dump(exclude_unset=True)\n    )\n    if not success:\n        raise HTTPException(status_code=404, detail=\"User not found\")\n    return MessageOut(message=\"User updated successfully\")\n\n\n@admin_router.delete(\n    \"/users/{user_id}\",\n    response_model=MessageOut,\n    responses={\n        403: {\"model\": ErrorOut},\n        404: {\"model\": ErrorOut},\n        400: {\"model\": ErrorOut},\n    },\n)\nasync def delete_user(user_id: str, admin: User = Depends(verify_admin)) -> MessageOut:\n    user = await admin_service.get_user_by_id(user_id)\n    if not user:\n        raise HTTPException(status_code=404, detail=\"User not found\")\n\n    if user[\"role\"] == \"admin\":\n        raise HTTPException(status_code=400, detail=\"Cannot delete an admin user\")\n\n    success = await admin_service.delete_user(user_id)\n    if not success:\n        raise HTTPException(status_code=500, detail=\"Failed to delete user\")\n    return MessageOut(message=\"User deleted successfully\")\n\n\n@admin_router.get(\"/system-prompt\")\nasync def get_system_prompt(admin: User = Depends(verify_admin)):\n    system_prompt = await config_service.get_system_prompt()\n    return {\"system_prompt\": system_prompt}\n\n\nclass SystemPromptUpdate(BaseModel):\n    new_prompt: str\n\n\n@admin_router.put(\"/system-prompt\")\nasync def update_system_prompt(\n    prompt_update: SystemPromptUpdate, admin: User = Depends(verify_admin)\n):\n    success = await config_service.update_system_prompt(prompt_update.new_prompt)\n    if not success:\n        raise HTTPException(status_code=500, detail=\"Failed to update system prompt\")\n    return {\"message\": \"System prompt updated successfully\"}\n\n\nclass ConversationStartersUpdate(BaseModel):\n    new_starters: List[str] = Field(\n        ...,\n        description=\"A list of new conversation starter questions\",\n        min_items=1,\n        example=[\n            \"What is RAG?\",\n            \"How does chunking work?\",\n            \"Explain vector embeddings\",\n        ],\n    )\n\n\n@admin_router.put(\n    \"/conversation-starters\",\n    response_model=MessageOut,\n    responses={\n        200: {\n            \"model\": MessageOut,\n            \"description\": \"Conversation starters updated successfully\",\n        },\n        500: {\n            \"model\": ErrorOut,\n            \"description\": \"Failed to update conversation starters\",\n        },\n    },\n    summary=\"Update conversation starters\",\n    description=\"Update the list of conversation starter questions for the chat interface\",\n)\nasync def update_conversation_starters(\n    starters_update: ConversationStartersUpdate, admin: User = Depends(verify_admin)\n):\n    success = await config_service.update_conversation_starters(\n        starters_update.new_starters\n    )\n    if not success:\n        raise HTTPException(\n            status_code=500, detail=\"Failed to update conversation starters\"\n        )\n    return MessageOut(message=\"Conversation starters updated successfully\")\n\n\n@admin_router.post(\"/upload_data\")\nasync def upload_and_ingest_data(\n    file: UploadFile = File(...), admin: User = Depends(verify_admin)\n):\n    with using_project(\"RAGSAAS-Data-Ingest\"):\n        try:\n            # Check if AWS credentials are available\n            use_aws = all(\n                [\n                    AWS_ACCESS_KEY_ID,\n                    AWS_SECRET_ACCESS_KEY,\n                    AWS_REGION,\n                    AWS_S3_BUCKET_NAME,\n                ]\n            )\n\n            with tempfile.NamedTemporaryFile(delete=False) as tmp_file:\n                shutil.copyfileobj(file.file, tmp_file)\n                tmp_file_path = tmp_file.name\n\n            if use_aws:\n                # Initialize S3 client\n                s3_client = boto3.client(\n                    \"s3\",\n                    aws_access_key_id=AWS_ACCESS_KEY_ID,\n                    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\n                    region_name=AWS_REGION,\n                )\n\n                # Upload file to S3\n                folder_name = \"admin_uploads/\"\n                file_key = f\"{folder_name}{file.filename}\"\n                s3_client.upload_file(tmp_file_path, AWS_S3_BUCKET_NAME, file_key)\n\n                # Generate the file URL\n                file_url = f\"https://{AWS_S3_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/{file_key}\"\n            else:\n                # Store file locally\n                os.makedirs(PRIVATE_STORE_PATH, exist_ok=True)\n                local_file_path = os.path.join(PRIVATE_STORE_PATH, file.filename)\n                shutil.move(tmp_file_path, local_file_path)\n                file_url = f\"/api/files/data/{file.filename}\"\n\n            # Ingest file into vector database\n            with tempfile.TemporaryDirectory() as temp_dir:\n                file_path = os.path.join(temp_dir, file.filename)\n                shutil.copy(\n                    local_file_path if not use_aws else tmp_file_path, file_path\n                )\n\n                documents = get_documents(temp_dir)\n\n                # Set metadata for all documents\n                for doc in documents:\n                    doc.metadata[\"private\"] = \"false\"\n                    doc.metadata[\"file_id\"] = file_key if use_aws else file.filename\n                    doc.metadata[\"user_id\"] = \"admin\"\n                    doc.metadata[\"url\"] = file_url\n                    doc.metadata[\"file_path\"] = file_url\n                    doc.metadata[\"document_id\"] = file_url\n                    doc.metadata[\"document_id\"] = file_url\n\n                vector_store = get_vector_store()\n\n                pipeline = IngestionPipeline(\n                    transformations=[\n                        SentenceSplitter(\n                            chunk_size=Settings.chunk_size,\n                            chunk_overlap=Settings.chunk_overlap,\n                        ),\n                        Settings.embed_model,\n                    ],\n                    vector_store=vector_store,\n                )\n\n                nodes = pipeline.run(documents=documents, show_progress=True)\n\n            return JSONResponse(\n                status_code=200,\n                content={\n                    \"file_url\": file_url,\n                    \"message\": f\"Ingestion complete. {len(nodes)} nodes inserted.\",\n                    \"storage\": \"S3\" if use_aws else \"Local\",\n                },\n            )\n\n        except Exception as e:\n            return JSONResponse(status_code=500, content={\"error\": str(e)})\n"
  },
  {
    "path": "backend/app/api/auth/__init__.py",
    "content": "from .route import auth_router\n\n__all__ = [\"auth_router\"]"
  },
  {
    "path": "backend/app/api/auth/route.py",
    "content": "from fastapi import APIRouter, Depends, HTTPException, Response, status, Body\nfrom fastapi.security import OAuth2PasswordRequestForm\nfrom typing import Any\nfrom app.services import user_service\nfrom app.core.security import create_access_token, create_refresh_token\nfrom app.schemas.auth_schema import TokenSchema\nfrom app.schemas.user_schema import UserOut\nfrom app.models.user_model import User\nfrom app.core.user import get_current_user\nfrom app.core.config import settings\nfrom app.schemas.auth_schema import TokenPayload, AuthErrorOut, RefreshTokenRequest\nfrom app.schemas.user_schema import UserAuth, UserUpdate\nfrom pydantic import ValidationError\nfrom jose import JWTError, jwt\nimport pymongo\n\nauth_router = APIRouter()\n\n\n@auth_router.post(\"/signup\", summary=\"Create new user\", response_model=dict)\nasync def create_user(data: UserAuth):\n    try:\n        user = await user_service.create_user(data)\n        return {\n            \"status\": \"success\",\n            \"user\": UserOut(\n                # user_id=user.user_id,\n                email=user.email,\n                first_name=user.first_name,\n                last_name=user.last_name,\n                role=user.role,\n            ),\n        }\n    except ValueError as e:\n        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))\n    except pymongo.errors.DuplicateKeyError:\n        raise HTTPException(\n            status_code=status.HTTP_400_BAD_REQUEST,\n            detail=\"User with this email already exists\",\n        )\n\n\n@auth_router.post(\n    \"/login\",\n    summary=\"Create access and refresh tokens for user\",\n    response_model=TokenSchema,\n)\n@auth_router.post(\n    \"/login\",\n    summary=\"Create access and refresh tokens for user\",\n    response_model=TokenSchema,\n)\nasync def login(form_data: OAuth2PasswordRequestForm = Depends()) -> Any:\n    user = await user_service.authenticate(\n        email=form_data.username, password=form_data.password\n    )\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_400_BAD_REQUEST,\n            detail=\"Incorrect email or password\",\n        )\n\n    if user.disabled:\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"User account is disabled\",\n        )\n\n    return {\n        \"access_token\": create_access_token(user.user_id),\n        \"refresh_token\": create_refresh_token(user.user_id),\n    }\n\n\n# @auth_router.post(\"/refresh\", summary=\"Refresh token\", response_model=TokenSchema)\n# async def refresh_token(refresh_token: str = Body(...)):\n#     try:\n#         payload = jwt.decode(\n#             refresh_token,\n#             settings.JWT_REFRESH_SECRET_KEY,\n#             algorithms=[settings.ALGORITHM],\n#         )\n#         token_data = TokenPayload(**payload)\n#     except (jwt.JWTError, ValidationError):\n#         raise HTTPException(\n#             status_code=status.HTTP_403_FORBIDDEN,\n#             detail=\"Invalid token\",\n#             headers={\"WWW-Authenticate\": \"Bearer\"},\n#         )\n#     user = await user_service.get_user_by_id(token_data.sub)\n#     if not user:\n#         raise HTTPException(\n#             status_code=status.HTTP_404_NOT_FOUND,\n#             detail=\"Invalid token for user\",\n#         )\n#     return {\n#         \"access_token\": create_access_token(user.user_id),\n#         \"refresh_token\": create_refresh_token(user.user_id),\n#     }\n\n\n@auth_router.post(\n    \"/refresh\",\n    response_model=TokenSchema,\n    summary=\"Refresh token\",\n    responses={403: {\"model\": AuthErrorOut}, 404: {\"model\": AuthErrorOut}},\n)\nasync def refresh_token(response: Response, refresh_request: RefreshTokenRequest):\n    try:\n        payload = jwt.decode(\n            refresh_request.refresh_token,\n            settings.JWT_REFRESH_SECRET_KEY,\n            algorithms=[settings.ALGORITHM],\n        )\n        token_data = TokenPayload(**payload)\n    except (JWTError, ValidationError):\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"Invalid token\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n\n    user = await user_service.get_user_by_id(token_data.sub)\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_404_NOT_FOUND,\n            detail=\"Invalid token for user\",\n        )\n\n    if user.disabled:\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"User account is disabled\",\n        )\n\n    new_access_token = create_access_token(user.user_id)\n    new_refresh_token = create_refresh_token(user.user_id)\n\n    # Set cookies\n    response.set_cookie(\n        key=\"accessToken\",\n        value=new_access_token,\n        httponly=True,\n        max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,\n        expires=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,\n        samesite=\"lax\",\n        secure=settings.COOKIE_SECURE,  # True in production\n    )\n    response.set_cookie(\n        key=\"refreshToken\",\n        value=new_refresh_token,\n        httponly=True,\n        max_age=settings.REFRESH_TOKEN_EXPIRE_MINUTES * 60,\n        expires=settings.REFRESH_TOKEN_EXPIRE_MINUTES * 60,\n        samesite=\"lax\",\n        secure=settings.COOKIE_SECURE,  # True in production\n    )\n\n    return {\n        \"access_token\": new_access_token,\n        \"refresh_token\": new_refresh_token,\n    }\n\n\n@auth_router.get(\n    \"/me\", summary=\"Get details of currently logged in user\", response_model=UserOut\n)\nasync def get_me(user: User = Depends(get_current_user)):\n    return user\n\n\n@auth_router.get(\"/verify-admin\", response_model=dict)\nasync def verify_admin(current_user: User = Depends(get_current_user)):\n    if not current_user.role or current_user.role != \"admin\":\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"User is not an admin\",\n        )\n    return {\"isAdmin\": True}\n\n\n@auth_router.post(\"/update\", summary=\"Update User\", response_model=UserOut)\nasync def update_user(data: UserUpdate, user: User = Depends(get_current_user)):\n    try:\n        return await user_service.update_user(user.user_id, data)\n    except pymongo.errors.OperationFailure:\n        raise HTTPException(\n            status_code=status.HTTP_400_BAD_REQUEST, detail=\"User does not exist\"\n        )\n\n\n@auth_router.post(\n    \"/test-token\", summary=\"Test if the access token is valid\", response_model=UserOut\n)\nasync def test_token(user: User = Depends(get_current_user)):\n    return user\n"
  },
  {
    "path": "backend/app/api/chat/__init__.py",
    "content": "from .route import chat_router\nfrom .chat_config import config_router\nfrom .upload import file_upload_router\n\n__all__ = [\"chat_router\", \"config_router\", \"file_upload_router\"]"
  },
  {
    "path": "backend/app/api/chat/chat_config.py",
    "content": "import logging\nimport os\n\nfrom fastapi import APIRouter\n\nfrom app.api.chat.models import ChatConfig\nfrom app.services.config_service import config_service\n\nconfig_router = r = APIRouter()\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\n@r.get(\"\")\nasync def chat_config() -> ChatConfig:\n    return await config_service.get_chat_config()\n"
  },
  {
    "path": "backend/app/api/chat/engine/__init__.py",
    "content": "from .engine import get_chat_engine as get_chat_engine\n"
  },
  {
    "path": "backend/app/api/chat/engine/engine.py",
    "content": "import os\n\nfrom app.api.chat.engine.index import get_index\nfrom app.api.chat.engine.node_postprocessors import NodeCitationProcessor\nfrom fastapi import HTTPException\nfrom llama_index.core.chat_engine import CondensePlusContextChatEngine\n\nfrom app.db import sync_mongodb\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\n\ndef get_system_prompt_from_db():\n    config_collection = sync_mongodb.db.config\n    config = config_collection.find_one({\"_id\": \"app_config\"})\n    if config and \"SYSTEM_PROMPT\" in config:\n        return config[\"SYSTEM_PROMPT\"]\n    return None\n\n\ndef get_chat_engine(filters=None, params=None):\n    system_prompt = get_system_prompt_from_db()\n    if system_prompt is None:\n        system_prompt = os.getenv(\"SYSTEM_PROMPT\", \"\")\n\n    citation_prompt = os.getenv(\"SYSTEM_CITATION_PROMPT\", None)\n    top_k = int(os.getenv(\"TOP_K\", 0))\n\n    # node_postprocessors = []\n    # if citation_prompt:\n    #     node_postprocessors = [NodeCitationProcessor()]\n    #     system_prompt = f\"{system_prompt}\\n{citation_prompt}\"\n\n    index = get_index(params)\n    if index is None:\n        raise HTTPException(\n            status_code=500,\n            detail=str(\n                \"StorageContext is empty - call 'poetry run generate' to generate the storage first\"\n            ),\n        )\n\n    retriever = index.as_retriever(\n        filters=filters, **({\"similarity_top_k\": top_k} if top_k != 0 else {})\n    )\n\n    return CondensePlusContextChatEngine.from_defaults(\n        system_prompt=system_prompt,\n        retriever=retriever,\n        # node_postprocessors=node_postprocessors,\n    )\n"
  },
  {
    "path": "backend/app/api/chat/engine/generate.py",
    "content": "# flake8: noqa: E402\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nimport logging\nimport os\n\nfrom app.api.chat.engine.loaders import get_documents\nfrom app.api.chat.engine.vectordb import get_vector_store\nfrom app.settings import init_settings\nfrom llama_index.core.ingestion import IngestionPipeline\nfrom llama_index.core.node_parser import SentenceSplitter\nfrom llama_index.core.settings import Settings\nfrom llama_index.core.storage import StorageContext\nfrom llama_index.core.storage.docstore import SimpleDocumentStore\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\nSTORAGE_DIR = os.getenv(\"STORAGE_DIR\", \"storage\")\n\n\ndef get_doc_store():\n    # If the storage directory is there, load the document store from it.\n    # If not, set up an in-memory document store since we can't load from a directory that doesn't exist.\n    if os.path.exists(STORAGE_DIR):\n        return SimpleDocumentStore.from_persist_dir(STORAGE_DIR)\n    else:\n        return SimpleDocumentStore()\n\n\ndef run_pipeline(docstore, vector_store, documents):\n    pipeline = IngestionPipeline(\n        transformations=[\n            SentenceSplitter(\n                chunk_size=Settings.chunk_size,\n                chunk_overlap=Settings.chunk_overlap,\n            ),\n            Settings.embed_model,\n        ],\n        docstore=docstore,\n        docstore_strategy=\"upserts_and_delete\",\n        vector_store=vector_store,\n    )\n\n    # Run the ingestion pipeline and store the results\n    nodes = pipeline.run(show_progress=True, documents=documents)\n\n    return nodes\n\n\ndef persist_storage(docstore, vector_store):\n    storage_context = StorageContext.from_defaults(\n        docstore=docstore,\n        vector_store=vector_store,\n    )\n    storage_context.persist(STORAGE_DIR)\n\n\ndef generate_datasource():\n    init_settings()\n    logger.info(\"Generate index for the provided data\")\n\n    # Get the stores and documents or create new ones\n    documents = get_documents()\n    # Set private=false to mark the document as public (required for filtering)\n    for doc in documents:\n        doc.metadata[\"private\"] = \"false\"\n    docstore = get_doc_store()\n    vector_store = get_vector_store()\n\n    # Run the ingestion pipeline\n    _ = run_pipeline(docstore, vector_store, documents)\n\n    # Build the index and persist storage\n    persist_storage(docstore, vector_store)\n\n    logger.info(\"Finished generating the index\")\n\n\nif __name__ == \"__main__\":\n    generate_datasource()\n"
  },
  {
    "path": "backend/app/api/chat/engine/index.py",
    "content": "import logging\nfrom llama_index.core.indices import VectorStoreIndex\nfrom app.api.chat.engine.vectordb import get_vector_store\n\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\ndef get_index(params=None):\n    logger.info(\"Connecting vector store...\")\n    store = get_vector_store()\n    # Load the index from the vector store\n    # If you are using a vector store that doesn't store text,\n    # you must load the index from both the vector store and the document store\n    index = VectorStoreIndex.from_vector_store(store)\n    logger.info(\"Finished load index from vector store.\")\n    return index\n"
  },
  {
    "path": "backend/app/api/chat/engine/loaders/__init__.py",
    "content": "import logging\n\nimport yaml\nfrom app.api.chat.engine.loaders.db import DBLoaderConfig, get_db_documents\nfrom app.api.chat.engine.loaders.file import FileLoaderConfig, get_file_documents\nfrom app.api.chat.engine.loaders.web import WebLoaderConfig, get_web_documents\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_configs():\n    with open(\"config/loaders.yaml\") as f:\n        configs = yaml.safe_load(f)\n    return configs\n\n\ndef get_documents():\n    documents = []\n    config = load_configs()\n    for loader_type, loader_config in config.items():\n        logger.info(\n            f\"Loading documents from loader: {loader_type}, config: {loader_config}\"\n        )\n        match loader_type:\n            case \"file\":\n                document = get_file_documents(FileLoaderConfig(**loader_config))\n            case \"web\":\n                document = get_web_documents(WebLoaderConfig(**loader_config))\n            case \"db\":\n                document = get_db_documents(\n                    configs=[DBLoaderConfig(**cfg) for cfg in loader_config]\n                )\n            case _:\n                raise ValueError(f\"Invalid loader type: {loader_type}\")\n        documents.extend(document)\n\n    return documents\n"
  },
  {
    "path": "backend/app/api/chat/engine/loaders/db.py",
    "content": "import logging\nfrom typing import List\nfrom pydantic import BaseModel\n\nlogger = logging.getLogger(__name__)\n\n\nclass DBLoaderConfig(BaseModel):\n    uri: str\n    queries: List[str]\n\n\ndef get_db_documents(configs: list[DBLoaderConfig]):\n    from llama_index.readers.database import DatabaseReader\n\n    docs = []\n    for entry in configs:\n        loader = DatabaseReader(uri=entry.uri)\n        for query in entry.queries:\n            logger.info(f\"Loading data from database with query: {query}\")\n            documents = loader.load_data(query=query)\n            docs.extend(documents)\n\n    return documents\n"
  },
  {
    "path": "backend/app/api/chat/engine/loaders/file.py",
    "content": "import os\nimport logging\nfrom typing import Dict\nfrom llama_parse import LlamaParse\nfrom pydantic import BaseModel\n\nfrom app.config import DATA_DIR\n\nlogger = logging.getLogger(__name__)\n\n\nclass FileLoaderConfig(BaseModel):\n    use_llama_parse: bool = False\n\n\ndef llama_parse_parser():\n    if os.getenv(\"LLAMA_CLOUD_API_KEY\") is None:\n        raise ValueError(\n            \"LLAMA_CLOUD_API_KEY environment variable is not set. \"\n            \"Please set it in .env file or in your shell environment then run again!\"\n        )\n    parser = LlamaParse(\n        result_type=\"markdown\",\n        verbose=True,\n        language=\"en\",\n        ignore_errors=False,\n    )\n    return parser\n\n\ndef llama_parse_extractor() -> Dict[str, LlamaParse]:\n    from llama_parse.utils import SUPPORTED_FILE_TYPES\n\n    parser = llama_parse_parser()\n    return {file_type: parser for file_type in SUPPORTED_FILE_TYPES}\n\n\ndef get_file_documents(config: FileLoaderConfig):\n    from llama_index.core.readers import SimpleDirectoryReader\n\n    try:\n        file_extractor = None\n        if config.use_llama_parse:\n            # LlamaParse is async first,\n            # so we need to use nest_asyncio to run it in sync mode\n            import nest_asyncio\n\n            nest_asyncio.apply()\n\n            file_extractor = llama_parse_extractor()\n        reader = SimpleDirectoryReader(\n            DATA_DIR,\n            recursive=True,\n            filename_as_id=True,\n            raise_on_error=True,\n            file_extractor=file_extractor,\n        )\n        return reader.load_data()\n    except Exception as e:\n        import sys\n        import traceback\n\n        # Catch the error if the data dir is empty\n        # and return as empty document list\n        _, _, exc_traceback = sys.exc_info()\n        function_name = traceback.extract_tb(exc_traceback)[-1].name\n        if function_name == \"_add_files\":\n            logger.warning(\n                f\"Failed to load file documents, error message: {e} . Return as empty document list.\"\n            )\n            return []\n        else:\n            # Raise the error if it is not the case of empty data dir\n            raise e\n"
  },
  {
    "path": "backend/app/api/chat/engine/loaders/web.py",
    "content": "from pydantic import BaseModel, Field\n\n\nclass CrawlUrl(BaseModel):\n    base_url: str\n    prefix: str\n    max_depth: int = Field(default=1, ge=0)\n\n\nclass WebLoaderConfig(BaseModel):\n    driver_arguments: list[str] = Field(default=None)\n    urls: list[CrawlUrl]\n\n\ndef get_web_documents(config: WebLoaderConfig):\n    from llama_index.readers.web import WholeSiteReader\n    from selenium import webdriver\n    from selenium.webdriver.chrome.options import Options\n\n    options = Options()\n    driver_arguments = config.driver_arguments or []\n    for arg in driver_arguments:\n        options.add_argument(arg)\n\n    docs = []\n    for url in config.urls:\n        scraper = WholeSiteReader(\n            prefix=url.prefix,\n            max_depth=url.max_depth,\n            driver=webdriver.Chrome(options=options),\n        )\n        docs.extend(scraper.load_data(url.base_url))\n\n    return docs\n"
  },
  {
    "path": "backend/app/api/chat/engine/node_postprocessors.py",
    "content": "from typing import List, Optional\n\nfrom llama_index.core import QueryBundle\nfrom llama_index.core.postprocessor.types import BaseNodePostprocessor\nfrom llama_index.core.schema import NodeWithScore\n\n\nclass NodeCitationProcessor(BaseNodePostprocessor):\n    \"\"\"\n    Append node_id into metadata for citation purpose.\n    Config SYSTEM_CITATION_PROMPT in your runtime environment variable to enable this feature.\n    \"\"\"\n\n    def _postprocess_nodes(\n        self,\n        nodes: List[NodeWithScore],\n        query_bundle: Optional[QueryBundle] = None,\n    ) -> List[NodeWithScore]:\n        for node_score in nodes:\n            node_score.node.metadata[\"node_id\"] = node_score.node.node_id\n        return nodes\n"
  },
  {
    "path": "backend/app/api/chat/engine/query_filter.py",
    "content": "from llama_index.core.vector_stores.types import MetadataFilter, MetadataFilters\n\n\ndef generate_filters(doc_ids):\n    \"\"\"\n    Generate public/private document filters based on the doc_ids and the vector store.\n    \"\"\"\n    public_doc_filter = MetadataFilter(\n        key=\"private\",\n        value=\"true\",\n        operator=\"!=\",  # type: ignore\n    )\n    selected_doc_filter = MetadataFilter(\n        key=\"doc_id\",\n        value=doc_ids,\n        operator=\"in\",  # type: ignore\n    )\n    if len(doc_ids) > 0:\n        # If doc_ids are provided, we will select both public and selected documents\n        filters = MetadataFilters(\n            filters=[\n                public_doc_filter,\n                selected_doc_filter,\n            ],\n            condition=\"or\",  # type: ignore\n        )\n    else:\n        filters = MetadataFilters(\n            filters=[\n                public_doc_filter,\n            ]\n        )\n\n    return filters\n"
  },
  {
    "path": "backend/app/api/chat/engine/vectordb.py",
    "content": "import os\nimport qdrant_client\nfrom llama_index.vector_stores.qdrant import QdrantVectorStore\n\n\ndef get_vector_store():\n    collection_name = os.getenv(\"QDRANT_COLLECTION\", \"ragsaas\")\n    QDRANT_URL = os.getenv(\"QDRANT_URL\")\n    QDRANT_API_KEY = os.getenv(\"QDRANT_API_KEY\")\n    if not collection_name or not QDRANT_URL:\n        raise ValueError(\n            \"Please set QDRANT_COLLECTION, QDRANT_URL\"\n            \" to your environment variables or config them in the .env file\"\n        )\n    if QDRANT_API_KEY:\n        # creating a qdrant client instance\n        client = qdrant_client.QdrantClient(\n            url=QDRANT_URL,\n            api_key=QDRANT_API_KEY,\n        )\n\n        aclient = qdrant_client.AsyncQdrantClient(\n            url=QDRANT_URL,\n            api_key=QDRANT_API_KEY,\n        )\n\n        store = QdrantVectorStore(\n            client=client, aclient=aclient, collection_name=collection_name\n        )\n    else:\n        client = qdrant_client.QdrantClient(\n            url=QDRANT_URL,\n        )\n\n        aclient = qdrant_client.AsyncQdrantClient(\n            url=QDRANT_URL,\n        )\n\n        store = QdrantVectorStore(\n            client=client, aclient=aclient, collection_name=collection_name\n        )\n    return store\n"
  },
  {
    "path": "backend/app/api/chat/events.py",
    "content": "import json\nimport asyncio\nimport logging\nfrom typing import AsyncGenerator, Dict, Any, List, Optional\nfrom llama_index.core.callbacks.base import BaseCallbackHandler\nfrom llama_index.core.callbacks.schema import CBEventType\nfrom llama_index.core.tools.types import ToolOutput\nfrom pydantic import BaseModel\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CallbackEvent(BaseModel):\n    event_type: CBEventType\n    payload: Optional[Dict[str, Any]] = None\n    event_id: str = \"\"\n\n    def get_retrieval_message(self) -> dict | None:\n        if self.payload:\n            nodes = self.payload.get(\"nodes\")\n            if nodes:\n                msg = f\"Retrieved {len(nodes)} sources to use as context for the query\"\n            else:\n                msg = f\"Retrieving context for query: '{self.payload.get('query_str')}'\"\n            return {\n                \"type\": \"events\",\n                \"data\": {\"title\": msg},\n            }\n        else:\n            return None\n\n    def get_tool_message(self) -> dict | None:\n        func_call_args = self.payload.get(\"function_call\")\n        if func_call_args is not None and \"tool\" in self.payload:\n            tool = self.payload.get(\"tool\")\n            return {\n                \"type\": \"events\",\n                \"data\": {\n                    \"title\": f\"Calling tool: {tool.name} with inputs: {func_call_args}\",\n                },\n            }\n\n    def _is_output_serializable(self, output: Any) -> bool:\n        try:\n            json.dumps(output)\n            return True\n        except TypeError:\n            return False\n\n    def get_agent_tool_response(self) -> dict | None:\n        response = self.payload.get(\"response\")\n        if response is not None:\n            sources = response.sources\n            for source in sources:\n                # Return the tool response here to include the toolCall information\n                if isinstance(source, ToolOutput):\n                    if self._is_output_serializable(source.raw_output):\n                        output = source.raw_output\n                    else:\n                        output = source.content\n\n                    return {\n                        \"type\": \"tools\",\n                        \"data\": {\n                            \"toolOutput\": {\n                                \"output\": output,\n                                \"isError\": source.is_error,\n                            },\n                            \"toolCall\": {\n                                \"id\": None,  # There is no tool id in the ToolOutput\n                                \"name\": source.tool_name,\n                                \"input\": source.raw_input,\n                            },\n                        },\n                    }\n\n    def to_response(self):\n        try:\n            match self.event_type:\n                case \"retrieve\":\n                    return self.get_retrieval_message()\n                case \"function_call\":\n                    return self.get_tool_message()\n                case \"agent_step\":\n                    return self.get_agent_tool_response()\n                case _:\n                    return None\n        except Exception as e:\n            logger.error(f\"Error in converting event to response: {e}\")\n            return None\n\n\nclass EventCallbackHandler(BaseCallbackHandler):\n    _aqueue: asyncio.Queue\n    is_done: bool = False\n\n    def __init__(\n        self,\n    ):\n        \"\"\"Initialize the base callback handler.\"\"\"\n        ignored_events = [\n            CBEventType.CHUNKING,\n            CBEventType.NODE_PARSING,\n            CBEventType.EMBEDDING,\n            CBEventType.LLM,\n            CBEventType.TEMPLATING,\n        ]\n        super().__init__(ignored_events, ignored_events)\n        self._aqueue = asyncio.Queue()\n\n    def on_event_start(\n        self,\n        event_type: CBEventType,\n        payload: Optional[Dict[str, Any]] = None,\n        event_id: str = \"\",\n        **kwargs: Any,\n    ) -> str:\n        event = CallbackEvent(event_id=event_id, event_type=event_type, payload=payload)\n        if event.to_response() is not None:\n            self._aqueue.put_nowait(event)\n\n    def on_event_end(\n        self,\n        event_type: CBEventType,\n        payload: Optional[Dict[str, Any]] = None,\n        event_id: str = \"\",\n        **kwargs: Any,\n    ) -> None:\n        event = CallbackEvent(event_id=event_id, event_type=event_type, payload=payload)\n        if event.to_response() is not None:\n            self._aqueue.put_nowait(event)\n\n    def start_trace(self, trace_id: Optional[str] = None) -> None:\n        \"\"\"No-op.\"\"\"\n\n    def end_trace(\n        self,\n        trace_id: Optional[str] = None,\n        trace_map: Optional[Dict[str, List[str]]] = None,\n    ) -> None:\n        \"\"\"No-op.\"\"\"\n\n    async def async_event_gen(self) -> AsyncGenerator[CallbackEvent, None]:\n        while not self._aqueue.empty() or not self.is_done:\n            try:\n                yield await asyncio.wait_for(self._aqueue.get(), timeout=0.1)\n            except asyncio.TimeoutError:\n                pass\n"
  },
  {
    "path": "backend/app/api/chat/models.py",
    "content": "import logging\nimport os\nfrom typing import Any, Dict, List, Literal, Optional\n\nfrom llama_index.core.llms import ChatMessage, MessageRole\nfrom llama_index.core.schema import NodeWithScore\nfrom pydantic import BaseModel, Field, validator\nfrom pydantic.alias_generators import to_camel\n\nfrom app.config import DATA_DIR\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\nclass FileContent(BaseModel):\n    type: Literal[\"text\", \"ref\"]\n    # If the file is pure text then the value is be a string\n    # otherwise, it's a list of document IDs\n    value: str | List[str]\n\n\nclass File(BaseModel):\n    id: str\n    content: FileContent\n    filename: str\n    filesize: int\n    filetype: str\n\n\nclass AnnotationFileData(BaseModel):\n    files: List[File] = Field(\n        default=[],\n        description=\"List of files\",\n    )\n\n    class Config:\n        json_schema_extra = {\n            \"example\": {\n                \"csvFiles\": [\n                    {\n                        \"content\": \"Name, Age\\nAlice, 25\\nBob, 30\",\n                        \"filename\": \"example.csv\",\n                        \"filesize\": 123,\n                        \"id\": \"123\",\n                        \"type\": \"text/csv\",\n                    }\n                ]\n            }\n        }\n        alias_generator = to_camel\n\n\nclass Annotation(BaseModel):\n    type: str\n    data: AnnotationFileData | List[str]\n\n    def to_content(self) -> str | None:\n        if self.type == \"document_file\":\n            # We only support generating context content for CSV files for now\n            csv_files = [file for file in self.data.files if file.filetype == \"csv\"]\n            if len(csv_files) > 0:\n                return \"Use data from following CSV raw content\\n\" + \"\\n\".join(\n                    [f\"```csv\\n{csv_file.content.value}\\n```\" for csv_file in csv_files]\n                )\n        else:\n            logger.warning(\n                f\"The annotation {self.type} is not supported for generating context content\"\n            )\n        return None\n\n\nclass Message(BaseModel):\n    role: MessageRole\n    content: str\n    annotations: List[Annotation] | None = None\n\n\nclass ChatData(BaseModel):\n    messages: List[Message]\n    data: Any = None\n\n    class Config:\n        json_schema_extra = {\n            \"example\": {\n                \"messages\": [\n                    {\n                        \"role\": \"user\",\n                        \"content\": \"What standards for letters exist?\",\n                    }\n                ]\n            }\n        }\n\n    @validator(\"messages\")\n    def messages_must_not_be_empty(cls, v):\n        if len(v) == 0:\n            raise ValueError(\"Messages must not be empty\")\n        return v\n\n    def get_last_message_content(self) -> str:\n        \"\"\"\n        Get the content of the last message along with the data content if available.\n        Fallback to use data content from previous messages\n        \"\"\"\n        if len(self.messages) == 0:\n            raise ValueError(\"There is not any message in the chat\")\n        last_message = self.messages[-1]\n        message_content = last_message.content\n        for message in reversed(self.messages):\n            if message.role == MessageRole.USER and message.annotations is not None:\n                annotation_contents = filter(\n                    None,\n                    [annotation.to_content() for annotation in message.annotations],\n                )\n                if not annotation_contents:\n                    continue\n                annotation_text = \"\\n\".join(annotation_contents)\n                message_content = f\"{message_content}\\n{annotation_text}\"\n                break\n        return message_content\n\n    def get_history_messages(self) -> List[ChatMessage]:\n        \"\"\"\n        Get the history messages\n        \"\"\"\n        return [\n            ChatMessage(role=message.role, content=message.content)\n            for message in self.messages[:-1]\n        ]\n\n    def is_last_message_from_user(self) -> bool:\n        return self.messages[-1].role == MessageRole.USER\n\n    def get_chat_document_ids(self) -> List[str]:\n        \"\"\"\n        Get the document IDs from the chat messages\n        \"\"\"\n        document_ids: List[str] = []\n        for message in self.messages:\n            if message.role == MessageRole.USER and message.annotations is not None:\n                for annotation in message.annotations:\n                    if (\n                        annotation.type == \"document_file\"\n                        and annotation.data.files is not None\n                    ):\n                        for fi in annotation.data.files:\n                            if fi.content.type == \"ref\":\n                                document_ids += fi.content.value\n        return list(set(document_ids))\n\n\nclass SourceNodes(BaseModel):\n    id: str\n    metadata: Dict[str, Any]\n    score: Optional[float]\n    text: str\n    url: Optional[str]\n\n    @classmethod\n    def from_source_node(cls, source_node: NodeWithScore):\n        metadata = source_node.node.metadata\n        url = cls.get_url_from_metadata(metadata)\n\n        return cls(\n            id=source_node.node.node_id,\n            metadata=metadata,\n            score=source_node.score,\n            text=source_node.node.text,  # type: ignore\n            url=url,\n        )\n\n    @classmethod\n    def get_url_from_metadata(cls, metadata: Dict[str, Any]) -> str:\n        url_prefix = os.getenv(\"FILESERVER_URL_PREFIX\")\n        if not url_prefix:\n            logger.warning(\n                \"Warning: FILESERVER_URL_PREFIX not set in environment variables. Can't use file server\"\n            )\n        file_name = metadata.get(\"file_name\")\n\n        if file_name and url_prefix:\n            # file_name exists and file server is configured\n            pipeline_id = metadata.get(\"pipeline_id\")\n            if pipeline_id:\n                # file is from LlamaCloud\n                file_name = f\"{pipeline_id}${file_name}\"\n                return f\"{url_prefix}/output/llamacloud/{file_name}\"\n            is_private = metadata.get(\"private\", \"false\") == \"true\"\n            if is_private:\n                # file is a private upload\n                return f\"{url_prefix}/output/uploaded/{file_name}\"\n            # file is from calling the 'generate' script\n            # Get the relative path of file_path to data_dir\n            file_path = metadata.get(\"file_path\")\n            data_dir = os.path.abspath(DATA_DIR)\n            if file_path and data_dir:\n                relative_path = os.path.relpath(file_path, data_dir)\n                return f\"{url_prefix}/data/{relative_path}\"\n        # fallback to URL in metadata (e.g. for websites)\n        return metadata.get(\"URL\")\n\n    @classmethod\n    def from_source_nodes(cls, source_nodes: List[NodeWithScore]):\n        return [cls.from_source_node(node) for node in source_nodes]\n\n\nclass Result(BaseModel):\n    result: Message\n    nodes: List[SourceNodes]\n\n\nclass ChatConfig(BaseModel):\n    starter_questions: Optional[List[str]] = Field(\n        default=None,\n        description=\"List of starter questions\",\n        serialization_alias=\"starterQuestions\",\n    )\n\n    class Config:\n        json_schema_extra = {\n            \"example\": {\n                \"starterQuestions\": [\n                    \"What standards for letters exist?\",\n                    \"What are the requirements for a letter to be considered a letter?\",\n                ],\n            }\n        }\n"
  },
  {
    "path": "backend/app/api/chat/route.py",
    "content": "import json\nimport logging\nfrom typing import List, Dict, Any, Optional\nfrom fastapi import (\n    APIRouter,\n    Depends,\n    HTTPException,\n    Request,\n    status,\n    Query,\n)\nfrom llama_index.core.chat_engine.types import BaseChatEngine, NodeWithScore\nfrom llama_index.core.llms import MessageRole\n\nfrom app.api.chat.events import EventCallbackHandler\nfrom app.api.chat.models import (\n    ChatData,\n    Message,\n    Result,\n    SourceNodes,\n)\nfrom app.api.chat.vercel_response import VercelStreamResponse\nfrom app.api.chat.engine import get_chat_engine\nfrom app.api.chat.engine.query_filter import generate_filters\nfrom app.models.user_model import User\nfrom app.core.user import get_current_user\nfrom app.api.chat.summary import summary_generator\nfrom app.services import conversation_service\nfrom phoenix.trace import using_project\n\nchat_router = r = APIRouter()\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\n# streaming endpoint - delete if not needed\n@r.post(\"\")\nasync def chat(\n    request: Request,\n    data: ChatData,\n    conversation_id: Optional[str] = Query(None),\n    current_user: User = Depends(get_current_user),\n):\n    with using_project(\"RAGSAAS-Chat\"):\n        if not conversation_id:\n            raise HTTPException(\n                status_code=status.HTTP_400_BAD_REQUEST,\n                detail=\"Conversation ID is required for authenticated requests.\",\n            )\n        try:\n            USER_ID = current_user.email\n            conversation = await conversation_service.get_or_create_conversation(\n                conversation_id\n            )\n            if conversation:\n                stored_messages = conversation.get(\"messages\", [])\n                incoming_messages = data.messages\n                if len(incoming_messages) < len(stored_messages):\n                    await conversation_service.truncate_conversation(\n                        conversation_id, len(incoming_messages), USER_ID\n                    )\n\n            if conversation.get(\"summary\") == \"New Chat\":\n                if len(data.messages) <= 2:\n                    summary = await summary_generator(data.messages)\n            else:\n                try:\n                    summary = conversation.get(\"summary\")\n                except Exception as e:\n                    summary = \"New Chat\"\n            last_message_content = data.get_last_message_content()\n            messages = data.get_history_messages()\n\n            await conversation_service.update_conversation(\n                conversation_id,\n                {\"role\": MessageRole.USER, \"content\": last_message_content},\n            )\n\n            doc_ids = data.get_chat_document_ids()\n            filters = generate_filters(doc_ids)\n            params = data.data or {}\n            logger.info(\n                f\"Creating chat engine with filters: {str(filters)}\",\n            )\n            chat_engine = get_chat_engine(filters=filters, params=params)\n\n            event_handler = EventCallbackHandler()\n            chat_engine.callback_manager.handlers.append(event_handler)  # type: ignore\n\n            response = await chat_engine.astream_chat(last_message_content, messages)\n            # process_response_nodes(response.source_nodes, background_tasks)\n\n            final_response = \"\"\n            suggested_questions = []\n            source_nodes = []\n            event = []\n            tools = []\n\n            async def enhanced_content_generator():\n                nonlocal final_response, suggested_questions, source_nodes, event, tools\n                async for chunk in VercelStreamResponse.content_generator(\n                    request, event_handler, response, data\n                ):\n                    # print(chunk, end=\"\", flush=True)  # Print each chunk in the backend\n                    yield chunk\n\n                    if chunk.startswith(VercelStreamResponse.TEXT_PREFIX):\n                        final_response += json.loads(chunk[2:].strip())\n                    elif chunk.startswith(VercelStreamResponse.DATA_PREFIX):\n                        data_chunk = json.loads(chunk[2:].strip())[0]\n                        if data_chunk[\"type\"] == \"suggested_questions\":\n                            suggested_questions = data_chunk[\"data\"]\n                        elif data_chunk[\"type\"] == \"sources\":\n                            try:\n                                source_nodes = data_chunk[\n                                    \"data\"\n                                ]  # might have chidlen key value pair\n                            except Exception:\n                                source_nodes = []\n                        elif data_chunk[\"type\"] == \"events\":\n                            try:\n                                event = data_chunk[\n                                    \"data\"\n                                ]  # might have chidlen key value pair\n                            except Exception:\n                                event = []  # might have chidlen key value pair\n                        elif data_chunk[\"type\"] == \"tools\":\n                            try:\n                                tools = data_chunk[\"data\"]\n                            except Exception:\n                                tools = []\n\n                await conversation_service.update_conversation(\n                    conversation_id,\n                    {\n                        \"role\": MessageRole.ASSISTANT,\n                        \"content\": final_response,\n                        \"annotations\": [\n                            {\"type\": \"sources\", \"data\": source_nodes},\n                            {\n                                \"type\": \"suggested_questions\",\n                                \"data\": suggested_questions,\n                            },\n                            {\"type\": \"events\", \"data\": event},\n                            {\"type\": \"tools\", \"data\": tools},\n                        ],\n                    },\n                    summary=summary,\n                    user_id=USER_ID,\n                )\n\n            return VercelStreamResponse(\n                request,\n                event_handler,\n                response,\n                data,\n                content=enhanced_content_generator(),\n            )\n        except Exception as e:\n            logger.exception(\"Error in chat engine\", exc_info=True)\n            raise HTTPException(\n                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n                detail=f\"Error in chat engine: {e}\",\n            ) from e\n\n\n# non-streaming endpoint - delete if not needed\n# @r.post(\"/request\")\n# async def chat_request(\n#     data: ChatData,\n#     chat_engine: BaseChatEngine = Depends(get_chat_engine),\n# ) -> Result:\n#     last_message_content = data.get_last_message_content()\n#     messages = data.get_history_messages()\n\n#     response = await chat_engine.achat(last_message_content, messages)\n#     return Result(\n#         result=Message(role=MessageRole.ASSISTANT, content=response.response),\n#         nodes=SourceNodes.from_source_nodes(response.source_nodes),\n#     )\n\n\n# def process_response_nodes(\n#     nodes: List[NodeWithScore],\n#     background_tasks: BackgroundTasks,\n# ):\n#     try:\n#         # Start background tasks to download documents from LlamaCloud if needed\n#         from app.api.chat.engine.service import LLamaCloudFileService\n\n#         LLamaCloudFileService.download_files_from_nodes(nodes, background_tasks)\n#     except ImportError:\n#         logger.debug(\"LlamaCloud is not configured. Skipping post processing of nodes\")\n#         pass\n"
  },
  {
    "path": "backend/app/api/chat/services/file.py",
    "content": "import base64\nimport mimetypes\nimport os\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import Any, List, Tuple\n\n\nfrom app.api.chat.engine.index import get_index\nfrom llama_index.core import VectorStoreIndex\nfrom llama_index.core.ingestion import IngestionPipeline\nfrom llama_index.core.readers.file.base import (\n    _try_loading_included_file_formats as get_file_loaders_map,\n)\nfrom llama_index.core.schema import Document\nfrom llama_index.indices.managed.llama_cloud.base import LlamaCloudIndex\nfrom llama_index.readers.file import FlatReader\n\n\ndef get_llamaparse_parser():\n    from app.api.chat.engine.loaders import load_configs\n    from app.api.chat.engine.loaders.file import FileLoaderConfig, llama_parse_parser\n\n    config = load_configs()\n    file_loader_config = FileLoaderConfig(**config[\"file\"])\n    if file_loader_config.use_llama_parse:\n        return llama_parse_parser()\n    else:\n        return None\n\n\ndef default_file_loaders_map():\n    default_loaders = get_file_loaders_map()\n    default_loaders[\".txt\"] = FlatReader\n    return default_loaders\n\n\nclass PrivateFileService:\n    PRIVATE_STORE_PATH = \"output/uploaded\"\n\n    @staticmethod\n    def preprocess_base64_file(base64_content: str) -> Tuple[bytes, str | None]:\n        header, data = base64_content.split(\",\", 1)\n        mime_type = header.split(\";\")[0].split(\":\", 1)[1]\n        extension = mimetypes.guess_extension(mime_type)\n        # File data as bytes\n        return base64.b64decode(data), extension\n\n    @staticmethod\n    def store_and_parse_file(file_name, file_data, extension) -> List[Document]:\n        # Store file to the private directory\n        os.makedirs(PrivateFileService.PRIVATE_STORE_PATH, exist_ok=True)\n        file_path = Path(os.path.join(PrivateFileService.PRIVATE_STORE_PATH, file_name))\n\n        # write file\n        with open(file_path, \"wb\") as f:\n            f.write(file_data)\n\n        # Load file to documents\n        # If LlamaParse is enabled, use it to parse the file\n        # Otherwise, use the default file loaders\n        reader = get_llamaparse_parser()\n        if reader is None:\n            reader_cls = default_file_loaders_map().get(extension)\n            if reader_cls is None:\n                raise ValueError(f\"File extension {extension} is not supported\")\n            reader = reader_cls()\n        documents = reader.load_data(file_path)\n        # Add custom metadata\n        for doc in documents:\n            doc.metadata[\"file_name\"] = file_name\n            doc.metadata[\"private\"] = \"true\"\n        return documents\n\n    @staticmethod\n    def process_file(file_name: str, base64_content: str, params: Any) -> List[str]:\n        file_data, extension = PrivateFileService.preprocess_base64_file(base64_content)\n\n        # Add the nodes to the index and persist it\n        current_index = get_index(params)\n\n        # Insert the documents into the index\n        if isinstance(current_index, LlamaCloudIndex):\n            from app.api.chat.engine.service import LLamaCloudFileService\n\n            project_id = current_index._get_project_id()\n            pipeline_id = current_index._get_pipeline_id()\n            # LlamaCloudIndex is a managed index so we can directly use the files\n            upload_file = (file_name, BytesIO(file_data))\n            return [\n                LLamaCloudFileService.add_file_to_pipeline(\n                    project_id,\n                    pipeline_id,\n                    upload_file,\n                    custom_metadata={\n                        # Set private=true to mark the document as private user docs (required for filtering)\n                        \"private\": \"true\",\n                    },\n                )\n            ]\n        else:\n            # First process documents into nodes\n            documents = PrivateFileService.store_and_parse_file(\n                file_name, file_data, extension\n            )\n            pipeline = IngestionPipeline()\n            nodes = pipeline.run(documents=documents)\n\n            # Add the nodes to the index and persist it\n            if current_index is None:\n                current_index = VectorStoreIndex(nodes=nodes)\n            else:\n                current_index.insert_nodes(nodes=nodes)\n            current_index.storage_context.persist(\n                persist_dir=os.environ.get(\"STORAGE_DIR\", \"storage\")\n            )\n\n            # Return the document ids\n            return [doc.doc_id for doc in documents]\n"
  },
  {
    "path": "backend/app/api/chat/services/suggestion.py",
    "content": "import logging\nfrom typing import List\n\nfrom app.api.chat.models import Message\nfrom llama_index.core.prompts import PromptTemplate\nfrom llama_index.core.settings import Settings\nfrom pydantic import BaseModel\n\nNEXT_QUESTIONS_SUGGESTION_PROMPT = PromptTemplate(\n    \"You're a helpful assistant! Your task is to suggest the next question that user might ask. \"\n    \"\\nHere is the conversation history\"\n    \"\\n---------------------\\n{conversation}\\n---------------------\"\n    \"Given the conversation history, please give me {number_of_questions} questions that you might ask next!\"\n)\nN_QUESTION_TO_GENERATE = 3\n\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\nclass NextQuestions(BaseModel):\n    \"\"\"A list of questions that user might ask next\"\"\"\n\n    questions: List[str]\n\n\nclass NextQuestionSuggestion:\n    @staticmethod\n    async def suggest_next_questions(\n        messages: List[Message],\n        number_of_questions: int = N_QUESTION_TO_GENERATE,\n    ) -> List[str]:\n        \"\"\"\n        Suggest the next questions that user might ask based on the conversation history\n        Return as empty list if there is an error\n        \"\"\"\n        try:\n            # Reduce the cost by only using the last two messages\n            last_user_message = None\n            last_assistant_message = None\n            for message in reversed(messages):\n                if message.role == \"user\":\n                    last_user_message = f\"User: {message.content}\"\n                elif message.role == \"assistant\":\n                    last_assistant_message = f\"Assistant: {message.content}\"\n                if last_user_message and last_assistant_message:\n                    break\n            conversation: str = f\"{last_user_message}\\n{last_assistant_message}\"\n\n            output: NextQuestions = await Settings.llm.astructured_predict(\n                NextQuestions,\n                prompt=NEXT_QUESTIONS_SUGGESTION_PROMPT,\n                conversation=conversation,\n                number_of_questions=number_of_questions,\n            )\n\n            return output.questions\n        except Exception as e:\n            logger.error(f\"Error when generating next question: {e}\")\n            return []\n"
  },
  {
    "path": "backend/app/api/chat/summary.py",
    "content": "from typing import List\nfrom app.api.chat.models import Message\nfrom llama_index.core.settings import Settings\n\n\nasync def summary_generator(\n    messages: List[Message],\n) -> str:\n    # Reduce the cost by only using the last two messages\n    last_user_message = None\n    last_assistant_message = None\n    for message in reversed(messages):\n        if message.role == \"user\":\n            last_user_message = f\"User: {message.content}\"\n        elif message.role == \"assistant\":\n            last_assistant_message = f\"Assistant: {message.content}\"\n        if last_user_message and last_assistant_message:\n            break\n    conversation: str = f\"{last_user_message}\\n{last_assistant_message}\"\n\n    response = await Settings.llm.acomplete(\n        prompt=f\"\"\"\n        Here is the conversation history\n        \\n---------------------\\n{messages}\\n---------------------\\n\n        Given the a conversation between a user and an Medical AI assistant \n        give me one line summary of the conversation so that is instantly recognizable \n        make sure its really short don't mention user or assistant in the summary \n        dont start with conversation , discussion , inquiry it should always start with a keyboard of the conversation\n        the summary should be short less then 5 to 10 words, straight to the point and distinct \n        \"\"\",\n        formatted=False,\n    )\n    # print(response)\n    return str(response)\n"
  },
  {
    "path": "backend/app/api/chat/upload.py",
    "content": "import logging\nfrom typing import List, Any\n\nfrom fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel\n\nfrom app.api.chat.services.file import PrivateFileService\n\nfile_upload_router = r = APIRouter()\n\nlogger = logging.getLogger(\"uvicorn\")\n\n\nclass FileUploadRequest(BaseModel):\n    base64: str\n    filename: str\n    params: Any = None\n\n\n# @r.post(\"\")\n# def upload_file(request: FileUploadRequest) -> List[str]:\n#     try:\n#         logger.info(\"Processing file\")\n#         return PrivateFileService.process_file(\n#             request.filename, request.base64, request.params\n#         )\n#     except Exception as e:\n#         logger.error(f\"Error processing file: {e}\", exc_info=True)\n#         raise HTTPException(status_code=500, detail=\"Error processing file\")\n"
  },
  {
    "path": "backend/app/api/chat/vercel_response.py",
    "content": "import json\n\nfrom aiostream import stream\nfrom fastapi import Request\nfrom fastapi.responses import StreamingResponse\nfrom llama_index.core.chat_engine.types import StreamingAgentChatResponse\n\nfrom app.api.chat.events import EventCallbackHandler\nfrom app.api.chat.models import ChatData, Message, SourceNodes\nfrom app.api.chat.services.suggestion import NextQuestionSuggestion\n\n\nclass VercelStreamResponse(StreamingResponse):\n    \"\"\"\n    Class to convert the response from the chat engine to the streaming format expected by Vercel\n    \"\"\"\n\n    TEXT_PREFIX = \"0:\"\n    DATA_PREFIX = \"8:\"\n\n    @classmethod\n    def convert_text(cls, token: str):\n        # Escape newlines and double quotes to avoid breaking the stream\n        token = json.dumps(token)\n        return f\"{cls.TEXT_PREFIX}{token}\\n\"\n\n    @classmethod\n    def convert_data(cls, data: dict):\n        data_str = json.dumps(data)\n        return f\"{cls.DATA_PREFIX}[{data_str}]\\n\"\n\n    def __init__(\n        self,\n        request: Request,\n        event_handler: EventCallbackHandler,\n        response: StreamingAgentChatResponse,\n        chat_data: ChatData,\n        content=None,\n    ):\n        if content is None:\n            content = VercelStreamResponse.content_generator(\n                request, event_handler, response, chat_data\n            )\n        super().__init__(content=content)\n\n    @classmethod\n    async def content_generator(\n        cls,\n        request: Request,\n        event_handler: EventCallbackHandler,\n        response: StreamingAgentChatResponse,\n        chat_data: ChatData,\n    ):\n        # Yield the text response\n        async def _chat_response_generator():\n            final_response = \"\"\n            async for token in response.async_response_gen():\n                final_response += token\n                yield VercelStreamResponse.convert_text(token)\n\n            # Generate questions that user might interested to\n            conversation = chat_data.messages + [\n                Message(role=\"assistant\", content=final_response)\n            ]\n            questions = await NextQuestionSuggestion.suggest_next_questions(\n                conversation\n            )\n            if len(questions) > 0:\n                yield VercelStreamResponse.convert_data(\n                    {\n                        \"type\": \"suggested_questions\",\n                        \"data\": questions,\n                    }\n                )\n\n            # the text_generator is the leading stream, once it's finished, also finish the event stream\n            event_handler.is_done = True\n\n            # Yield the source nodes\n            yield cls.convert_data(\n                {\n                    \"type\": \"sources\",\n                    \"data\": {\n                        \"nodes\": [\n                            SourceNodes.from_source_node(node).model_dump()\n                            for node in response.source_nodes\n                        ]\n                    },\n                }\n            )\n\n        # Yield the events from the event handler\n        async def _event_generator():\n            async for event in event_handler.async_event_gen():\n                event_response = event.to_response()\n                if event_response is not None:\n                    yield VercelStreamResponse.convert_data(event_response)\n\n        combine = stream.merge(_chat_response_generator(), _event_generator())\n        is_stream_started = False\n        async with combine.stream() as streamer:\n            async for output in streamer:\n                if not is_stream_started:\n                    is_stream_started = True\n                    # Stream a blank message to start the stream\n                    yield VercelStreamResponse.convert_text(\"\")\n\n                yield output\n\n                if await request.is_disconnected():\n                    break\n"
  },
  {
    "path": "backend/app/api/conversation/__init__.py",
    "content": "from .route import conversation_router\n\n__all__ = [\"conversation_router\"]"
  },
  {
    "path": "backend/app/api/conversation/route.py",
    "content": "import logging\nfrom pydantic import BaseModel\nfrom datetime import datetime, timedelta\nfrom typing import List, Dict, Any, Optional\nfrom bson import ObjectId\nfrom fastapi import APIRouter, HTTPException, status, Depends\nfrom fastapi.responses import JSONResponse\nfrom dotenv import load_dotenv\nfrom app.core.user import get_current_user\nfrom app.services import conversation_service\nfrom app.models.user_model import User\n\nconversation_router = APIRouter(tags=[\"Conversation\"])\n\nlogger = logging.getLogger(\"uvicorn\")\n\nload_dotenv()\n\n\n@conversation_router.get(\"/\")\nasync def get_new_conversation(\n    current_user: User = Depends(get_current_user),\n):\n    try:\n        new_conversation_id = ObjectId()\n        # user_email = current_user.get(\"email\") if current_user else None\n        user_email = current_user.email\n\n        await conversation_service.get_or_create_conversation(\n            str(new_conversation_id), user_email\n        )\n        return {\"conversation_id\": str(new_conversation_id)}\n    except Exception as e:\n        logger.exception(\"Error creating new conversation\", exc_info=True)\n        raise HTTPException(\n            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n            detail=f\"Error creating new conversation: {e}\",\n        ) from e\n\n\n@conversation_router.get(\"/list\")\nasync def get_conversation_history(\n    current_user: Dict[str, Any] = Depends(get_current_user),\n):\n    try:\n        conversations_by_date = (\n            await conversation_service.get_all_conversations_for_user(\n                current_user.email\n            )\n        )\n        return {\"conversations\": conversations_by_date}\n    except Exception as e:\n        raise HTTPException(status_code=500, detail=str(e))\n\n\n@conversation_router.get(\"/{conversation_id}\")\nasync def get_conversation(\n    conversation_id: str, current_user: Dict[str, Any] = Depends(get_current_user)\n):\n    conversation = await conversation_service.get_or_create_conversation(\n        conversation_id, current_user.email\n    )\n    conversation[\"_id\"] = str(conversation[\"_id\"])\n    return {\"messages\": conversation.get(\"messages\", [])}\n\n\n@conversation_router.get(\"/sharable/{conversation_id}\")\nasync def get_sharable_conversation(conversation_id: str):\n    conversation = await conversation_service.get_sharable_conversation(\n        conversation_id,\n    )\n    if conversation is None:\n        raise HTTPException(status_code=404, detail=\"Sharable conversation not found\")\n    return {\"messages\": conversation.get(\"messages\", [])}\n\n\n@conversation_router.delete(\"/{conversation_id}\")\nasync def delete_conversation(\n    conversation_id: str, current_user: Dict[str, Any] = Depends(get_current_user)\n):\n    try:\n        deleted_count = await conversation_service.delete_conversation(\n            conversation_id, current_user.email\n        )\n        if deleted_count == 1:\n            return JSONResponse(\n                status_code=status.HTTP_200_OK,\n                content={\n                    \"message\": f\"Conversation {conversation_id} deleted successfully.\"\n                },\n            )\n        else:\n            raise HTTPException(\n                status_code=status.HTTP_404_NOT_FOUND,\n                detail=f\"Conversation {conversation_id} not found for the current user.\",\n            )\n    except Exception as e:\n        logger.exception(\"Error deleting conversation\", exc_info=True)\n        raise HTTPException(\n            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n            detail=f\"Error deleting conversation: {e}\",\n        ) from e\n\n\nclass ConversationSummaryUpdate(BaseModel):\n    summary: str\n\n\n@conversation_router.patch(\"/{conversation_id}/share\")\nasync def edit_conversation_sharable(\n    conversation_id: str,\n    current_user: User = Depends(get_current_user),\n):\n    try:\n        success = await conversation_service.make_conversation_sharable(\n            conversation_id, current_user.email\n        )\n        if success:\n            return JSONResponse(\n                status_code=status.HTTP_200_OK,\n                content={\n                    \"message\": f\"Conversation {conversation_id} is now shareable.\"\n                },\n            )\n        else:\n            raise HTTPException(\n                status_code=status.HTTP_404_NOT_FOUND,\n                detail=f\"Conversation {conversation_id} not found for the current user.\",\n            )\n    except HTTPException as he:\n        raise he\n    except Exception as e:\n        logger.exception(\"Error updating conversation shareable status\", exc_info=True)\n        raise HTTPException(\n            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n            detail=f\"Error updating conversation shareable status: {str(e)}\",\n        ) from e\n\n\n@conversation_router.patch(\"/{conversation_id}/summary\")\nasync def edit_conversation_summary(\n    conversation_id: str,\n    summary_update: ConversationSummaryUpdate,\n    current_user: User = Depends(get_current_user),\n):\n    try:\n        matched_count = await conversation_service.edit_conversation_summary(\n            conversation_id, current_user.email, summary_update.summary\n        )\n        if matched_count == 1:\n            return JSONResponse(\n                status_code=status.HTTP_200_OK,\n                content={\n                    \"message\": f\"Summary for conversation {conversation_id} updated successfully.\"\n                },\n            )\n        else:\n            raise HTTPException(\n                status_code=status.HTTP_404_NOT_FOUND,\n                detail=f\"Conversation {conversation_id} not found for the current user.\",\n            )\n    except Exception as e:\n        logger.exception(\"Error updating conversation summary\", exc_info=True)\n        raise HTTPException(\n            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n            detail=f\"Error updating conversation summary: {e}\",\n        ) from e\n"
  },
  {
    "path": "backend/app/config.py",
    "content": "DATA_DIR = \"data\"\n"
  },
  {
    "path": "backend/app/core/config.py",
    "content": "from typing import List, ClassVar\n\nfrom decouple import config\nfrom pydantic import AnyHttpUrl\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    API_V1_STR: str = \"/api\"\n    JWT_SECRET_KEY: str = config(\"JWT_SECRET_KEY\", cast=str)\n    JWT_REFRESH_SECRET_KEY: str = config(\"JWT_REFRESH_SECRET_KEY\", cast=str)\n    ALGORITHM: ClassVar[str] = \"HS256\"\n    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24\n    REFRESH_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7  # 7 days\n    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [\"http://localhost:3000\"]\n    PROJECT_NAME: str = \"RAGSAAS\"\n    COOKIE_SECURE: bool = False\n\n    # Database\n    MONGO_CONNECTION_STRING: str = config(\"MONGODB_URI\", cast=str)\n\n    class Config:\n        case_sensitive = True\n\n\nsettings = Settings()\n"
  },
  {
    "path": "backend/app/core/security.py",
    "content": "from datetime import datetime, timedelta\nfrom passlib.context import CryptContext\nfrom typing import Union, Any\nfrom app.core.config import settings\nfrom jose import jwt\n\npassword_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n\n\ndef create_access_token(subject: Union[str, Any], expires_delta: int = None) -> str:\n    if expires_delta is not None:\n        expires_delta = datetime.utcnow() + expires_delta\n    else:\n        expires_delta = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)\n    \n    to_encode = {\"exp\": expires_delta, \"sub\": str(subject)}\n    encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET_KEY, settings.ALGORITHM)\n    return encoded_jwt\n\ndef create_refresh_token(subject: Union[str, Any], expires_delta: int = None) -> str:\n    if expires_delta is not None:\n        expires_delta = datetime.utcnow() + expires_delta\n    else:\n        expires_delta = datetime.utcnow() + timedelta(minutes=settings.REFRESH_TOKEN_EXPIRE_MINUTES)\n    \n    to_encode = {\"exp\": expires_delta, \"sub\": str(subject)}\n    encoded_jwt = jwt.encode(to_encode, settings.JWT_REFRESH_SECRET_KEY, settings.ALGORITHM)\n    return encoded_jwt\n\n\ndef get_password(password: str) -> str:\n    return password_context.hash(password)\n\n\ndef verify_password(password: str, hashed_pass: str) -> bool:\n    return password_context.verify(password, hashed_pass)"
  },
  {
    "path": "backend/app/core/user.py",
    "content": "from datetime import datetime\nfrom fastapi import Depends, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer\nfrom app.core.config import settings\nfrom app.models.user_model import User\nfrom jose import jwt\nfrom pydantic import ValidationError\nfrom app.services.user_service import user_service\nfrom app.schemas.auth_schema import TokenPayload\n\nreuseable_oauth = OAuth2PasswordBearer(\n    tokenUrl=f\"{settings.API_V1_STR}/auth/login\", scheme_name=\"JWT\"\n)\n\n\nasync def get_current_user(token: str = Depends(reuseable_oauth)) -> User:\n    try:\n        payload = jwt.decode(\n            token, settings.JWT_SECRET_KEY, algorithms=[settings.ALGORITHM]\n        )\n        token_data = TokenPayload(**payload)\n\n        if datetime.fromtimestamp(token_data.exp) < datetime.now():\n            raise HTTPException(\n                status_code=status.HTTP_401_UNAUTHORIZED,\n                detail=\"Token expired\",\n                headers={\"WWW-Authenticate\": \"Bearer\"},\n            )\n    except (jwt.JWTError, ValidationError):\n        raise HTTPException(\n            status_code=status.HTTP_403_FORBIDDEN,\n            detail=\"Could not validate credentials\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n\n    user = await user_service.get_user_by_id(token_data.sub)\n\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_404_NOT_FOUND,\n            detail=\"Could not find user\",\n        )\n\n    return user\n"
  },
  {
    "path": "backend/app/db.py",
    "content": "import asyncio\nimport re\nimport os\nimport json\nimport time\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom pymongo import MongoClient\nfrom dotenv import load_dotenv\nfrom pymongo.errors import ServerSelectionTimeoutError\nfrom app.models.user_model import User\nfrom app.core.security import get_password\n\nload_dotenv()\n\nMONGODB_URI = os.getenv(\"MONGODB_URI\")\nMONGODB_NAME = os.getenv(\"MONGODB_NAME\", \"RAGSAAS\")\nADMIN_EMAIL = os.getenv(\"ADMIN_EMAIL\")\nADMIN_PASSWORD = os.getenv(\"ADMIN_PASSWORD\")\nADMIN_USERNAME = os.getenv(\"ADMIN_USERNAME\", \"admin\")\n\nCONFIG_FILE = \"rag_config.json\"\n\n\nMAX_RETRIES = 5\nRETRY_DELAY = 5\n\n\nclass AsyncMongoDB:\n    client: AsyncIOMotorClient = None\n    db = None\n\n    async def connect_to_database(self):\n        for attempt in range(MAX_RETRIES):\n            try:\n                print(\n                    f\"Attempting to connect to MongoDB (Async) - Attempt {attempt + 1}\"\n                )\n                self.client = AsyncIOMotorClient(MONGODB_URI)\n                await (\n                    self.client.server_info()\n                )  # This will raise an exception if it can't connect\n                self.db = self.client[MONGODB_NAME]\n                print(\"Connected to MongoDB (Async)\")\n                return\n            except ServerSelectionTimeoutError as e:\n                print(f\"Connection attempt {attempt + 1} failed: {str(e)}\")\n                if attempt < MAX_RETRIES - 1:\n                    print(f\"Retrying in {RETRY_DELAY} seconds...\")\n                    await asyncio.sleep(RETRY_DELAY)\n                else:\n                    print(\"Max retries reached. Unable to connect to MongoDB.\")\n                    raise\n\n    async def close_database_connection(self):\n        if self.client:\n            self.client.close()\n            print(\"Closed MongoDB connection (Async)\")\n\n    async def database_init(self):\n        users_collection = self.db.users\n        config_collection = self.db.config\n\n        # Create admin user if not exists\n        existing_user = await users_collection.find_one({\"email\": ADMIN_EMAIL})\n        if not existing_user:\n            admin_user = User(\n                first_name=ADMIN_USERNAME,\n                last_name=ADMIN_USERNAME,\n                email=ADMIN_EMAIL,\n                hashed_password=get_password(ADMIN_PASSWORD),\n                role=\"admin\",\n            )\n            await users_collection.insert_one(admin_user.to_mongo())\n            print(f\"Admin user created with email: {ADMIN_EMAIL}\")\n\n        # Check if config already exists\n        existing_config = await config_collection.find_one({\"_id\": \"app_config\"})\n        if existing_config:\n            print(\"Configuration already exists. Skipping initialization.\")\n            return\n\n        # Initialize system prompt and conversation starters\n        system_prompt = os.getenv(\"SYSTEM_PROMPT\", \"\")\n        conversation_starters_raw = os.getenv(\"CONVERSATION_STARTERS\", \"\")\n\n        conversation_starters = re.split(r\"[,\\n]+\", conversation_starters_raw)\n        conversation_starters = [\n            starter.strip() for starter in conversation_starters if starter.strip()\n        ]\n\n        initial_config = {\n            \"SYSTEM_PROMPT\": system_prompt,\n            \"CONVERSATION_STARTERS\": conversation_starters,\n        }\n\n        await config_collection.insert_one({\"_id\": \"app_config\", **initial_config})\n\n        with open(CONFIG_FILE, \"w\") as f:\n            json.dump(initial_config, f, indent=2)\n\n        print(\"System prompt and conversation starters initialized\")\n        print(f\"Conversation starters: {conversation_starters}\")\n\n\nclass SyncMongoDB:\n    client: MongoClient = None\n    db = None\n\n    def connect_to_database(self):\n        for attempt in range(MAX_RETRIES):\n            try:\n                print(\n                    f\"Attempting to connect to MongoDB (Sync) - Attempt {attempt + 1}\"\n                )\n                self.client = MongoClient(MONGODB_URI)\n                self.client.server_info()  # This will raise an exception if it can't connect\n                self.db = self.client[MONGODB_NAME]\n                print(\"Connected to MongoDB (Sync)\")\n                return\n            except ServerSelectionTimeoutError as e:\n                print(f\"Connection attempt {attempt + 1} failed: {str(e)}\")\n                if attempt < MAX_RETRIES - 1:\n                    print(f\"Retrying in {RETRY_DELAY} seconds...\")\n                    time.sleep(RETRY_DELAY)\n                else:\n                    print(\"Max retries reached. Unable to connect to MongoDB.\")\n                    raise\n\n    def close_database_connection(self):\n        if self.client:\n            self.client.close()\n            print(\"Closed MongoDB connection (Sync)\")\n\n    def database_init(self):\n        users_collection = self.db.users\n        config_collection = self.db.config\n\n        # Create admin user if not exists\n        existing_user = users_collection.find_one({\"email\": ADMIN_EMAIL})\n        if not existing_user:\n            admin_user = User(\n                first_name=ADMIN_USERNAME,\n                last_name=ADMIN_USERNAME,\n                email=ADMIN_EMAIL,\n                hashed_password=get_password(ADMIN_PASSWORD),\n                role=\"admin\",\n            )\n            users_collection.insert_one(admin_user.to_mongo())\n            print(f\"Admin user created with email: {ADMIN_EMAIL}\")\n\n        # Check if config already exists\n        existing_config = config_collection.find_one({\"_id\": \"app_config\"})\n        if existing_config:\n            print(\"Configuration already exists. Skipping initialization.\")\n            return\n\n        # Initialize system prompt and conversation starters\n        system_prompt = os.getenv(\"SYSTEM_PROMPT\", \"\")\n        conversation_starters_raw = os.getenv(\"CONVERSATION_STARTERS\", \"\")\n\n        conversation_starters = re.split(r\"[,\\n]+\", conversation_starters_raw)\n        conversation_starters = [\n            starter.strip() for starter in conversation_starters if starter.strip()\n        ]\n\n        initial_config = {\n            \"SYSTEM_PROMPT\": system_prompt,\n            \"CONVERSATION_STARTERS\": conversation_starters,\n        }\n\n        config_collection.insert_one({\"_id\": \"app_config\", **initial_config})\n\n        with open(CONFIG_FILE, \"w\") as f:\n            json.dump(initial_config, f, indent=2)\n\n        print(\"System prompt and conversation starters initialized\")\n        print(f\"Conversation starters: {conversation_starters}\")\n\n\nasync_mongodb = AsyncMongoDB()\nsync_mongodb = SyncMongoDB()\n"
  },
  {
    "path": "backend/app/llmhub.py",
    "content": "from llama_index.embeddings.openai import OpenAIEmbedding\nfrom llama_index.core.settings import Settings\nfrom typing import Dict\nimport os\n\nDEFAULT_MODEL = \"gpt-3.5-turbo\"\nDEFAULT_EMBEDDING_MODEL = \"text-embedding-3-large\"\n\n\nclass TSIEmbedding(OpenAIEmbedding):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self._query_engine = self._text_engine = self.model_name\n\n\ndef llm_config_from_env() -> Dict:\n    from llama_index.core.constants import DEFAULT_TEMPERATURE\n\n    model = os.getenv(\"MODEL\", DEFAULT_MODEL)\n    temperature = os.getenv(\"LLM_TEMPERATURE\", DEFAULT_TEMPERATURE)\n    max_tokens = os.getenv(\"LLM_MAX_TOKENS\")\n    api_key = os.getenv(\"T_SYSTEMS_LLMHUB_API_KEY\")\n    api_base = os.getenv(\"T_SYSTEMS_LLMHUB_BASE_URL\")\n\n    config = {\n        \"model\": model,\n        \"api_key\": api_key,\n        \"api_base\": api_base,\n        \"temperature\": float(temperature),\n        \"max_tokens\": int(max_tokens) if max_tokens is not None else None,\n    }\n    return config\n\n\ndef embedding_config_from_env() -> Dict:\n    from llama_index.core.constants import DEFAULT_EMBEDDING_DIM\n\n    model = os.getenv(\"EMBEDDING_MODEL\", DEFAULT_EMBEDDING_MODEL)\n    dimension = os.getenv(\"EMBEDDING_DIM\", DEFAULT_EMBEDDING_DIM)\n    api_key = os.getenv(\"T_SYSTEMS_LLMHUB_API_KEY\")\n    api_base = os.getenv(\"T_SYSTEMS_LLMHUB_BASE_URL\")\n\n    config = {\n        \"model_name\": model,\n        \"dimension\": int(dimension) if dimension is not None else None,\n        \"api_key\": api_key,\n        \"api_base\": api_base,\n    }\n    return config\n\n\ndef init_llmhub():\n    from llama_index.llms.openai_like import OpenAILike\n\n    llm_configs = llm_config_from_env()\n    embedding_configs = embedding_config_from_env()\n\n    Settings.embed_model = TSIEmbedding(**embedding_configs)\n    Settings.llm = OpenAILike(\n        **llm_configs,\n        is_chat_model=True,\n        is_function_calling_model=False,\n        context_window=4096,\n    )\n"
  },
  {
    "path": "backend/app/models/user_model.py",
    "content": "from typing import Optional\nfrom datetime import datetime\nfrom uuid import UUID, uuid4\nfrom pydantic import BaseModel, Field, EmailStr\nfrom bson import Binary\n\n\nclass User(BaseModel):\n    user_id: UUID = Field(default_factory=uuid4)\n    email: EmailStr\n    hashed_password: str\n    first_name: Optional[str] = None\n    last_name: Optional[str] = None\n    disabled: Optional[bool] = None\n    role: str = \"user\"\n    created_at: datetime = Field(default_factory=datetime.utcnow)\n\n    def __repr__(self) -> str:\n        return f\"<User {self.email}>\"\n\n    def __str__(self) -> str:\n        return self.email\n\n    def __hash__(self) -> int:\n        return hash(self.email)\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, User):\n            return self.email == other.email\n        return False\n\n    @property\n    def create(self) -> datetime:\n        return self.created_at\n\n    class Config:\n        allow_population_by_field_name = True\n        arbitrary_types_allowed = True\n        json_encoders = {UUID: str}\n\n    def to_mongo(self):\n        # Convert the model to a dictionary\n        data = self.model_dump()\n        # Convert UUID to Binary for MongoDB storage\n        data[\"user_id\"] = Binary.from_uuid(data[\"user_id\"])\n        return data\n\n    @classmethod\n    def from_mongo(cls, data):\n        # Convert Binary back to UUID\n        if data.get(\"user_id\"):\n            data[\"user_id\"] = data[\"user_id\"].as_uuid()\n        return cls(**data)\n"
  },
  {
    "path": "backend/app/observability.py",
    "content": "import os\nfrom openinference.instrumentation.llama_index import LlamaIndexInstrumentor\nfrom opentelemetry import trace as trace_api\nfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter\nfrom opentelemetry.sdk import trace as trace_sdk\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace.export import SimpleSpanProcessor\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef init_observability():\n    ARIZE_PHOENIX_ENDPOINT = os.getenv(\"ARIZE_PHOENIX_ENDPOINT\")\n    if ARIZE_PHOENIX_ENDPOINT:\n        try:\n            if ARIZE_PHOENIX_ENDPOINT and \"/v1/traces\" in ARIZE_PHOENIX_ENDPOINT:\n                PHOENIX_ENDPOINT_TRACE_ENDPOINT = ARIZE_PHOENIX_ENDPOINT\n            else:\n                PHOENIX_ENDPOINT_TRACE_ENDPOINT = f\"{ARIZE_PHOENIX_ENDPOINT}/v1/traces\"\n            resource = Resource(attributes={})\n            tracer_provider = trace_sdk.TracerProvider(resource=resource)\n            span_exporter = OTLPSpanExporter(endpoint=PHOENIX_ENDPOINT_TRACE_ENDPOINT)\n            span_processor = SimpleSpanProcessor(span_exporter=span_exporter)\n            tracer_provider.add_span_processor(span_processor=span_processor)\n            trace_api.set_tracer_provider(tracer_provider=tracer_provider)\n            LlamaIndexInstrumentor().instrument()\n            print(\"🔭 ARIZE PHOENIX - Set up complete\")\n        except Exception as e:\n            print(\"Wasnt able to set up Arize Phoenix\", e)\n    else:\n        print(\"Arize Phoenix API Endpoint Not provided\")\n"
  },
  {
    "path": "backend/app/schemas/admin_schema.py",
    "content": "from pydantic import BaseModel, EmailStr\nfrom typing import List, Optional, Any\nfrom datetime import datetime\nfrom uuid import UUID\n\n\nclass UserOut(BaseModel):\n    user_id: UUID\n    email: EmailStr\n    first_name: Optional[str] = None\n    last_name: Optional[str] = None\n    role: str\n    disabled: Optional[bool] = None\n    created_at: datetime\n\n\nclass UsersOut(BaseModel):\n    users: List[UserOut]\n\n\nclass MessageOut(BaseModel):\n    message: str\n\n\nclass ErrorOut(BaseModel):\n    detail: str\n    status_code: int\n\n\nclass AuthErrorOut(ErrorOut):\n    error_description: Optional[str] = None\n    error_code: Optional[str] = None\n"
  },
  {
    "path": "backend/app/schemas/auth_schema.py",
    "content": "from uuid import UUID\nfrom pydantic import BaseModel\nfrom typing_extensions import Optional\n\n\nclass TokenSchema(BaseModel):\n    access_token: str\n    refresh_token: str\n\n\nclass TokenPayload(BaseModel):\n    sub: UUID = None\n    exp: int = None\n\n\nclass ErrorOut(BaseModel):\n    detail: str\n    status_code: int\n\n\nclass AuthErrorOut(ErrorOut):\n    error_description: Optional[str] = None\n    error_code: Optional[str] = None\n\n\nclass RefreshTokenRequest(BaseModel):\n    refresh_token: str\n"
  },
  {
    "path": "backend/app/schemas/user_schema.py",
    "content": "from typing import Optional\nfrom pydantic import BaseModel, EmailStr, Field\n\n\nclass UserAuth(BaseModel):\n    email: EmailStr = Field(..., description=\"user email\")\n    first_name: str = Field(..., description=\"first name\")\n    last_name: str = Field(..., description=\"last name\")\n    password: str = Field(..., min_length=5, max_length=24, description=\"user password\")\n\n\nclass UserOut(BaseModel):\n    # user_id: UUID\n    email: EmailStr\n    first_name: Optional[str]\n    last_name: Optional[str]\n    role: Optional[str]\n\n\nclass UserUpdate(BaseModel):\n    first_name: Optional[str] = None\n    last_name: Optional[str] = None\n"
  },
  {
    "path": "backend/app/services/__init__.py",
    "content": "from .user_service import user_service\nfrom .conversation_service import conversation_service\nfrom .admin_service import admin_service\nfrom .config_service import config_service\n\n__all__ = [\"user_service\", \"conversation_service\", \"admin_service\", \"config_service\"]\n"
  },
  {
    "path": "backend/app/services/admin_service.py",
    "content": "from typing import List, Dict, Any, Optional\nfrom bson import ObjectId, Binary\nfrom datetime import datetime\nfrom app.db import async_mongodb\nfrom app.models.user_model import User\nfrom uuid import UUID\n\n\nclass AdminService:\n    @property\n    def user_collection(self):\n        return async_mongodb.db.users\n\n    async def get_all_users(self) -> List[Dict[str, Any]]:\n        users = await self.user_collection.find().to_list(length=None)\n        return [self._serialize_user(User.from_mongo(user)) for user in users]\n\n    async def get_user_by_id(self, user_id: str) -> Optional[Dict[str, Any]]:\n        user = await self.user_collection.find_one(\n            {\"user_id\": Binary.from_uuid(UUID(user_id))}\n        )\n        return self._serialize_user(User.from_mongo(user)) if user else None\n\n    async def edit_user(self, user_id: str, updated_data: Dict[str, Any]) -> bool:\n        result = await self.user_collection.update_one(\n            {\"user_id\": Binary.from_uuid(UUID(user_id))}, {\"$set\": updated_data}\n        )\n        return result.modified_count > 0\n\n    async def delete_user(self, user_id: str) -> bool:\n        result = await self.user_collection.delete_one(\n            {\"user_id\": Binary.from_uuid(UUID(user_id))}\n        )\n        return result.deleted_count > 0\n\n    def _serialize_user(self, user: User) -> Dict[str, Any]:\n        return {\n            \"user_id\": str(user.user_id),\n            \"email\": user.email,\n            \"first_name\": user.first_name,\n            \"last_name\": user.last_name,\n            \"role\": user.role,\n            \"disabled\": user.disabled,\n            \"created_at\": user.created_at.isoformat() if user.created_at else None,\n        }\n\n\nadmin_service = AdminService()\n"
  },
  {
    "path": "backend/app/services/config_service.py",
    "content": "from typing import List, Dict, Any, Optional\nfrom app.db import async_mongodb\nfrom app.api.chat.models import ChatConfig\n\n\nclass ConfigService:\n    @property\n    def config_collection(self):\n        return async_mongodb.db.config\n\n    async def get_chat_config(self) -> ChatConfig:\n        config = await self.config_collection.find_one({\"_id\": \"app_config\"})\n        if config:\n            return ChatConfig(\n                system_prompt=config.get(\"SYSTEM_PROMPT\", \"\"),\n                starter_questions=config.get(\"CONVERSATION_STARTERS\", []),\n            )\n        return ChatConfig(system_prompt=\"\", starter_questions=[])\n\n    async def update_chat_config(self, updated_data: Dict[str, Any]) -> bool:\n        result = await self.config_collection.update_one(\n            {\"_id\": \"app_config\"}, {\"$set\": updated_data}, upsert=True\n        )\n        return result.modified_count > 0 or result.upserted_id is not None\n\n    async def get_system_prompt(self) -> str:\n        config = await self.config_collection.find_one({\"_id\": \"app_config\"})\n        return config.get(\"SYSTEM_PROMPT\", \"\") if config else \"\"\n\n    async def update_system_prompt(self, new_prompt: str) -> bool:\n        return await self.update_chat_config({\"SYSTEM_PROMPT\": new_prompt})\n\n    async def update_conversation_starters(self, new_starters: List[str]) -> bool:\n        return await self.update_chat_config({\"CONVERSATION_STARTERS\": new_starters})\n\n\nconfig_service = ConfigService()\n"
  },
  {
    "path": "backend/app/services/conversation_service.py",
    "content": "import logging\nfrom pydantic import BaseModel\nfrom datetime import datetime, timedelta\nfrom typing import List, Dict, Any, Optional\nfrom bson import ObjectId\nfrom dotenv import load_dotenv\nfrom app.db import async_mongodb\n\n\nlogger = logging.getLogger(\"uvicorn\")\n\nload_dotenv()\n\n\nclass ConversationService:\n    @property\n    def conversation_collection(self):\n        return async_mongodb.db.conversation\n\n    async def get_or_create_conversation(\n        self, conversation_id: str, user_id: Optional[str] = None\n    ) -> Dict[str, Any]:\n        conversation = await self.conversation_collection.find_one(\n            {\"_id\": ObjectId(conversation_id)}\n        )\n        if not conversation:\n            conversation = {\n                \"_id\": ObjectId(conversation_id),\n                \"messages\": [],\n                \"created_at\": datetime.utcnow(),\n                \"updated_at\": datetime.utcnow(),\n                \"summary\": \"New Chat\",\n            }\n            if user_id:\n                conversation[\"user_id\"] = user_id\n            await self.conversation_collection.insert_one(conversation)\n        return conversation\n\n    async def update_conversation(\n        self,\n        conversation_id: str,\n        new_message: Dict[str, Any],\n        summary: Optional[str] = None,\n        user_id: Optional[str] = None,\n    ) -> None:\n        update_fields = {\n            \"$push\": {\"messages\": new_message},\n            \"$set\": {\"updated_at\": datetime.utcnow()},\n        }\n\n        if summary:\n            update_fields[\"$set\"] = update_fields.get(\"$set\", {})\n            update_fields[\"$set\"][\"summary\"] = summary\n\n        if user_id:\n            update_fields[\"$set\"] = update_fields.get(\"$set\", {})\n            update_fields[\"$set\"][\"user_id\"] = user_id\n\n        await self.conversation_collection.update_one(\n            {\"_id\": ObjectId(conversation_id)}, update_fields\n        )\n\n    async def truncate_conversation(\n        self, conversation_id: str, index: int, user_id: str\n    ) -> None:\n        conversation = await self.get_or_create_conversation(conversation_id)\n        if conversation and conversation.get(\"user_id\") == user_id:\n            stored_messages = conversation.get(\"messages\", [])\n            truncated_messages = stored_messages[: index - 1]\n            await self.conversation_collection.update_one(\n                {\"_id\": ObjectId(conversation_id)},\n                {\n                    \"$set\": {\n                        \"messages\": truncated_messages,\n                        \"updated_at\": datetime.utcnow(),\n                    }\n                },\n            )\n        else:\n            raise PermissionError(\"User ID does not match or conversation not found.\")\n\n    async def get_all_conversations_for_user(self, user_id: str):\n        projection = {\"summary\": 1, \"created_at\": 1, \"updated_at\": 1}\n        conversations_cursor = self.conversation_collection.find(\n            {\"user_id\": user_id}, projection\n        ).sort(\"updated_at\", -1)\n        conversations = await conversations_cursor.to_list(length=None)\n\n        now = datetime.utcnow()\n        today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n        yesterday = today - timedelta(days=1)\n        last_week = today - timedelta(days=7)\n\n        categorized_conversations = {\n            \"today\": [],\n            \"yesterday\": [],\n            \"last_7_days\": [],\n            \"before_that\": [],\n        }\n\n        for conversation in conversations:\n            conversation[\"_id\"] = str(conversation[\"_id\"])\n            updated_at = conversation[\"updated_at\"]\n\n            if updated_at >= today:\n                categorized_conversations[\"today\"].append(conversation)\n            elif updated_at >= yesterday:\n                categorized_conversations[\"yesterday\"].append(conversation)\n            elif updated_at >= last_week:\n                categorized_conversations[\"last_7_days\"].append(conversation)\n            else:\n                categorized_conversations[\"before_that\"].append(conversation)\n\n        for category in categorized_conversations:\n            categorized_conversations[category].sort(\n                key=lambda x: x[\"updated_at\"], reverse=True\n            )\n\n        return categorized_conversations\n\n    async def delete_conversation(self, conversation_id: str, user_id: str) -> int:\n        result = await self.conversation_collection.delete_one(\n            {\"_id\": ObjectId(conversation_id), \"user_id\": user_id}\n        )\n        return result.deleted_count\n\n    async def edit_conversation_summary(\n        self, conversation_id: str, user_id: str, new_summary: str\n    ) -> int:\n        result = await self.conversation_collection.update_one(\n            {\"_id\": ObjectId(conversation_id), \"user_id\": user_id},\n            {\n                \"$set\": {\n                    \"summary\": new_summary,\n                    \"updated_at\": datetime.utcnow(),\n                }\n            },\n        )\n        return result.matched_count\n\n    async def get_sharable_conversation(\n        self,\n        conversation_id: str,\n    ) -> Dict[str, Any]:\n        conversation = await self.conversation_collection.find_one(\n            {\"_id\": ObjectId(conversation_id), \"sharable\": True}\n        )\n\n        if conversation is None:\n            return None\n\n        conversation[\"_id\"] = str(conversation[\"_id\"])\n        return conversation\n\n    async def make_conversation_sharable(\n        self, conversation_id: str, user_id: str\n    ) -> bool:\n        conversation = await self.conversation_collection.find_one(\n            {\"_id\": ObjectId(conversation_id), \"user_id\": user_id}\n        )\n\n        if not conversation:\n            return False\n\n        if conversation.get(\"sharable\", False):  # Changed True to False here\n            return True\n\n        result = await self.conversation_collection.update_one(\n            {\"_id\": ObjectId(conversation_id), \"user_id\": user_id},\n            {\n                \"$set\": {\n                    \"sharable\": True,\n                    \"updated_at\": datetime.utcnow(),\n                }\n            },\n        )\n        return result.modified_count == 1\n\n\nconversation_service = ConversationService()\n"
  },
  {
    "path": "backend/app/services/user_service.py",
    "content": "from typing import Optional\nfrom uuid import UUID\nfrom app.schemas.user_schema import UserAuth, UserUpdate\nfrom app.models.user_model import User\nfrom app.core.security import get_password, verify_password\nfrom pymongo.errors import DuplicateKeyError\nfrom bson import Binary\nfrom dotenv import load_dotenv\nfrom app.db import async_mongodb\n\n# Load environment variables\nload_dotenv()\n\n\nclass UserService:\n    @property\n    def users_collection(self):\n        return async_mongodb.db.users\n\n    async def create_user(self, user: UserAuth) -> User:\n        user_obj = User(\n            email=user.email,\n            first_name=user.first_name,\n            last_name=user.last_name,\n            hashed_password=get_password(user.password),\n            role=\"user\",  # Set default role to \"user\"\n        )\n        user_dict = user_obj.to_mongo()\n\n        try:\n            result = await self.users_collection.insert_one(user_dict)\n            user_dict[\"_id\"] = result.inserted_id\n            return User.from_mongo(user_dict)\n        except DuplicateKeyError:\n            raise ValueError(\"Username or email already exists\")\n\n    async def authenticate(self, email: str, password: str) -> Optional[User]:\n        user = await self.get_user_by_email(email=email)\n        if not user:\n            return None\n        if not verify_password(password=password, hashed_pass=user.hashed_password):\n            return None\n        return user\n\n    async def get_user_by_email(self, email: str) -> Optional[User]:\n        user_dict = await self.users_collection.find_one({\"email\": email})\n        return User.from_mongo(user_dict) if user_dict else None\n\n    async def get_user_by_id(self, id: UUID) -> Optional[User]:\n        user_dict = await self.users_collection.find_one(\n            {\"user_id\": Binary.from_uuid(id)}\n        )\n        return User.from_mongo(user_dict) if user_dict else None\n\n    async def update_user(self, id: UUID, data: UserUpdate) -> User:\n        update_data = data.model_dump(exclude_unset=True)\n        result = await self.users_collection.update_one(\n            {\"user_id\": Binary.from_uuid(id)}, {\"$set\": update_data}\n        )\n\n        if result.modified_count == 0:\n            raise ValueError(\"User not found\")\n\n        updated_user = await self.get_user_by_id(id)\n        return updated_user\n\n\nuser_service = UserService()\n"
  },
  {
    "path": "backend/app/settings.py",
    "content": "import os\nfrom typing import Dict\n\nfrom llama_index.core.settings import Settings\n\n\ndef init_settings():\n    model_provider = os.getenv(\"MODEL_PROVIDER\")\n    match model_provider:\n        case \"openai\":\n            init_openai()\n        case \"groq\":\n            init_groq()\n        case \"ollama\":\n            init_ollama()\n        case \"anthropic\":\n            init_anthropic()\n        case \"gemini\":\n            init_gemini()\n        case \"mistral\":\n            init_mistral()\n        case \"azure-openai\":\n            init_azure_openai()\n        case \"t-systems\":\n            from .llmhub import init_llmhub\n\n            init_llmhub()\n        case _:\n            raise ValueError(f\"Invalid model provider: {model_provider}\")\n\n    Settings.chunk_size = int(os.getenv(\"CHUNK_SIZE\", \"1024\"))\n    Settings.chunk_overlap = int(os.getenv(\"CHUNK_OVERLAP\", \"20\"))\n\n\ndef init_ollama():\n    from llama_index.embeddings.ollama import OllamaEmbedding\n    from llama_index.llms.ollama.base import DEFAULT_REQUEST_TIMEOUT, Ollama\n\n    base_url = os.getenv(\"OLLAMA_BASE_URL\") or \"http://127.0.0.1:11434\"\n    request_timeout = float(\n        os.getenv(\"OLLAMA_REQUEST_TIMEOUT\", DEFAULT_REQUEST_TIMEOUT)\n    )\n    Settings.embed_model = OllamaEmbedding(\n        base_url=base_url,\n        model_name=os.getenv(\"EMBEDDING_MODEL\"),\n    )\n    Settings.llm = Ollama(\n        base_url=base_url, model=os.getenv(\"MODEL\"), request_timeout=request_timeout\n    )\n\n\ndef init_openai():\n    from llama_index.core.constants import DEFAULT_TEMPERATURE\n    from llama_index.embeddings.openai import OpenAIEmbedding\n    from llama_index.llms.openai import OpenAI\n\n    max_tokens = os.getenv(\"LLM_MAX_TOKENS\")\n    config = {\n        \"model\": os.getenv(\"MODEL\"),\n        \"temperature\": float(os.getenv(\"LLM_TEMPERATURE\", DEFAULT_TEMPERATURE)),\n        \"max_tokens\": int(max_tokens) if max_tokens is not None else None,\n    }\n    Settings.llm = OpenAI(**config)\n\n    dimensions = os.getenv(\"EMBEDDING_DIM\")\n    config = {\n        \"model\": os.getenv(\"EMBEDDING_MODEL\"),\n        \"dimensions\": int(dimensions) if dimensions is not None else None,\n    }\n    Settings.embed_model = OpenAIEmbedding(**config)\n\n\ndef init_azure_openai():\n    from llama_index.core.constants import DEFAULT_TEMPERATURE\n    from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding\n    from llama_index.llms.azure_openai import AzureOpenAI\n\n    llm_deployment = os.environ[\"AZURE_OPENAI_LLM_DEPLOYMENT\"]\n    embedding_deployment = os.environ[\"AZURE_OPENAI_EMBEDDING_DEPLOYMENT\"]\n    max_tokens = os.getenv(\"LLM_MAX_TOKENS\")\n    temperature = os.getenv(\"LLM_TEMPERATURE\", DEFAULT_TEMPERATURE)\n    dimensions = os.getenv(\"EMBEDDING_DIM\")\n\n    azure_config = {\n        \"api_key\": os.environ[\"AZURE_OPENAI_API_KEY\"],\n        \"azure_endpoint\": os.environ[\"AZURE_OPENAI_ENDPOINT\"],\n        \"api_version\": os.getenv(\"AZURE_OPENAI_API_VERSION\")\n        or os.getenv(\"OPENAI_API_VERSION\"),\n    }\n\n    Settings.llm = AzureOpenAI(\n        model=os.getenv(\"MODEL\"),\n        max_tokens=int(max_tokens) if max_tokens is not None else None,\n        temperature=float(temperature),\n        deployment_name=llm_deployment,\n        **azure_config,\n    )\n\n    Settings.embed_model = AzureOpenAIEmbedding(\n        model=os.getenv(\"EMBEDDING_MODEL\"),\n        dimensions=int(dimensions) if dimensions is not None else None,\n        deployment_name=embedding_deployment,\n        **azure_config,\n    )\n\n\ndef init_fastembed():\n    \"\"\"\n    Use Qdrant Fastembed as the local embedding provider.\n    \"\"\"\n    from llama_index.embeddings.fastembed import FastEmbedEmbedding\n\n    embed_model_map: Dict[str, str] = {\n        # Small and multilingual\n        \"all-MiniLM-L6-v2\": \"sentence-transformers/all-MiniLM-L6-v2\",\n        # Large and multilingual\n        \"paraphrase-multilingual-mpnet-base-v2\": \"sentence-transformers/paraphrase-multilingual-mpnet-base-v2\",  # noqa: E501\n    }\n\n    # This will download the model automatically if it is not already downloaded\n    Settings.embed_model = FastEmbedEmbedding(\n        model_name=embed_model_map[os.getenv(\"EMBEDDING_MODEL\")]\n    )\n\n\ndef init_groq():\n    from llama_index.llms.groq import Groq\n\n    model_map: Dict[str, str] = {\n        \"llama3-8b\": \"llama3-8b-8192\",\n        \"llama3-70b\": \"llama3-70b-8192\",\n        \"mixtral-8x7b\": \"mixtral-8x7b-32768\",\n    }\n\n    Settings.llm = Groq(model=model_map[os.getenv(\"MODEL\")])\n    # Groq does not provide embeddings, so we use FastEmbed instead\n    init_fastembed()\n\n\ndef init_anthropic():\n    from llama_index.llms.anthropic import Anthropic\n\n    model_map: Dict[str, str] = {\n        \"claude-3-opus\": \"claude-3-opus-20240229\",\n        \"claude-3-sonnet\": \"claude-3-sonnet-20240229\",\n        \"claude-3-haiku\": \"claude-3-haiku-20240307\",\n        \"claude-2.1\": \"claude-2.1\",\n        \"claude-instant-1.2\": \"claude-instant-1.2\",\n    }\n\n    Settings.llm = Anthropic(model=model_map[os.getenv(\"MODEL\")])\n    # Anthropic does not provide embeddings, so we use FastEmbed instead\n    init_fastembed()\n\n\ndef init_gemini():\n    from llama_index.embeddings.gemini import GeminiEmbedding\n    from llama_index.llms.gemini import Gemini\n\n    model_name = f\"models/{os.getenv('MODEL')}\"\n    embed_model_name = f\"models/{os.getenv('EMBEDDING_MODEL')}\"\n\n    Settings.llm = Gemini(model=model_name)\n    Settings.embed_model = GeminiEmbedding(model_name=embed_model_name)\n\n\ndef init_mistral():\n    from llama_index.embeddings.mistralai import MistralAIEmbedding\n    from llama_index.llms.mistralai import MistralAI\n\n    Settings.llm = MistralAI(model=os.getenv(\"MODEL\"))\n    Settings.embed_model = MistralAIEmbedding(model_name=os.getenv(\"EMBEDDING_MODEL\"))\n"
  },
  {
    "path": "backend/config/loaders.yaml",
    "content": "file:\n  # use_llama_parse: Use LlamaParse if `true`. Needs a `LLAMA_CLOUD_API_KEY` from https://cloud.llamaindex.ai set as environment variable\n  use_llama_parse: false\n"
  },
  {
    "path": "backend/config/tools.yaml",
    "content": "local: {}\nllamahub: {}\n"
  },
  {
    "path": "backend/main.py",
    "content": "# flake8: noqa: E402\nfrom dotenv import load_dotenv\n\nfrom app.config import DATA_DIR\n\nload_dotenv()\n\nimport logging\nimport os\nimport json\n\nimport uvicorn\n\nfrom app.api.chat import chat_router\nfrom app.api.chat import config_router\nfrom app.api.chat import file_upload_router\nfrom app.api.auth import auth_router\nfrom app.api.conversation import conversation_router\nfrom app.api.admin import admin_router\nfrom app.observability import init_observability\nfrom app.settings import init_settings\nfrom app.db import async_mongodb, sync_mongodb\n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.responses import RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\n\nfrom contextlib import asynccontextmanager\n\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    await async_mongodb.connect_to_database()\n    sync_mongodb.connect_to_database()\n    await async_mongodb.database_init()\n    yield\n    # Shutdown: Close the database connection\n    sync_mongodb.close_database_connection()\n    await async_mongodb.close_database_connection()\n\n\napp = FastAPI(lifespan=lifespan)\n\ninit_settings()\ninit_observability()\n\nenvironment = os.getenv(\"ENVIRONMENT\", \"dev\")  # Default to 'development' if not set\nlogger = logging.getLogger(\"uvicorn\")\n\n# if environment == \"dev\":\n#     logger.warning(\"Running in development mode - allowing CORS for all origins\")\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"*\"],\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\n\n# Redirect to documentation page when accessing base URL\n@app.get(\"/\")\nasync def redirect_to_docs():\n    return RedirectResponse(url=\"/docs\")\n\n\ndef mount_static_files(directory, path):\n    if os.path.exists(directory):\n        logger.info(f\"Mounting static files '{directory}' at '{path}'\")\n        app.mount(\n            path,\n            StaticFiles(directory=directory, check_dir=False),\n            name=f\"{directory}-static\",\n        )\n\n\n# Mount the data files to serve the file viewer\nmount_static_files(DATA_DIR, \"/api/files/data\")\n# Mount the output files from tools\nmount_static_files(\"output\", \"/api/files/output\")\n\napp.include_router(auth_router, prefix=\"/api/auth\", tags=[\"Authentication\"])\napp.include_router(chat_router, prefix=\"/api/chat\", tags=[\"Chat\"])\napp.include_router(config_router, prefix=\"/api/chat/config\", tags=[\"Chat\"])\napp.include_router(file_upload_router, prefix=\"/api/chat/upload\", tags=[\"Chat\"])\napp.include_router(\n    conversation_router, prefix=\"/api/conversation\", tags=[\"Conversation\"]\n)\napp.include_router(admin_router, prefix=\"/api/admin\", tags=[\"Admin\"])\n\nif __name__ == \"__main__\":\n    app_host = os.getenv(\"APP_HOST\", \"0.0.0.0\")\n    app_port = int(os.getenv(\"APP_PORT\", \"8000\"))\n    reload = True if environment == \"dev\" else False\n\n    uvicorn.run(app=\"main:app\", host=app_host, port=app_port, reload=reload)\n"
  },
  {
    "path": "backend/pyproject.toml",
    "content": "[tool]\n[tool.poetry]\nname = \"app\"\nversion = \"0.1.0\"\ndescription = \"⚡ Ship RAG Solutions Quickly\"\nauthors = [ \"Adithya S K <Adithyaskolavi@gmail.com>\" ]\nreadme = \"README.md\"\n\n[tool.poetry.scripts]\ngenerate = \"app.api.chat.engine.generate:generate_datasource\"\n\n[tool.poetry.dependencies]\npython = \">=3.11,<3.12\"\nfastapi = {extras = [\"all\"], version = \"^0.112.2\"}\npython-dotenv = \"^1.0.0\"\naiostream = \"^0.5.2\"\nllama-index = \"0.10.58\"\ncachetools = \"^5.3.3\"\npymongo = \"^4.8.0\"\nmotor = \"^3.5.1\"\npython-jose = \"^3.3.0\"\npasslib = {extras = [\"bcrypt\"], version = \"^1.7.4\"}\npython-multipart = \"^0.0.9\"\npydantic = {extras = [\"email\"], version = \"^2.8.2\"}\npydantic-settings = \"^2.4.0\"\nfastapi-mail = \"^1.4.1\"\nbeanie = \"^1.26.0\"\npython-decouple = \"^3.8\"\nboto3 = \"^1.35.6\"\nopeninference-instrumentation = \"^0.1.12\"\nopeninference-instrumentation-llama-index = \"^2.2.1\"\nopeninference-instrumentation-openai = \"^0.1.12\"\nopeninference-semantic-conventions = \"^0.1.9\"\nopentelemetry-api = \"^1.26.0\"\nopentelemetry-exporter-otlp = \"^1.26.0\"\narize-phoenix = {extras = [\"evals\"], version = \"^4.19.0\"}\n\n[tool.poetry.dependencies.uvicorn]\nextras = [ \"standard\" ]\nversion = \"^0.23.2\"\n\n[tool.poetry.dependencies.llama-index-vector-stores-qdrant]\nversion = \"^0.2.8\"\n\n[tool.poetry.dependencies.docx2txt]\nversion = \"^0.8\"\n\n[tool.poetry.dependencies.llama-index-agent-openai]\nversion = \"0.2.6\"\n\n[build-system]\nrequires = [ \"poetry-core\" ]\nbuild-backend = \"poetry.core.masonry.api\""
  },
  {
    "path": "backend/tests/__init__.py",
    "content": ""
  },
  {
    "path": "docker-compose.yaml",
    "content": "version: '3.8'\n\nservices:\n  qdrant:\n    image: qdrant/qdrant:latest\n    container_name: qdrant\n    ports:\n      - 6333:6333\n      - 6334:6334\n    networks:\n      - ragsaas-network\n\n  mongodb:\n    image: mongo:latest\n    container_name: mongodb\n    ports:\n      - 27017:27017\n    environment:\n      MONGO_INITDB_ROOT_USERNAME: admin\n      MONGO_INITDB_ROOT_PASSWORD: password\n    networks:\n      - ragsaas-network\n    volumes:\n      - mongodb_data:/data/db\n\n  arizephoenix:\n    image: arizephoenix/phoenix:latest\n    container_name: arizephoenix\n    ports:\n      - '6006:6006'\n      - '4317:4317'\n    networks:\n      - ragsaas-network\n\n  backend:\n    build:\n      context: ./backend\n      dockerfile: Dockerfile\n    image: ragsaas/backend:latest\n    container_name: backend\n    ports:\n      - '8000:8000'\n    environment:\n      # MongoDB Configuration\n      MONGODB_NAME: RAGSAAS\n      MONGODB_URI: mongodb://admin:password@mongodb:27017/\n      # Qdrant Configuration\n      QDRANT_COLLECTION: default\n      QDRANT_URL: http://qdrant:6333\n      # QDRANT_API_KEY:\n      OPENAI_API_KEY:\n      # Backend Application Configuration\n      MODEL_PROVIDER: openai\n      MODEL: gpt-4o-mini\n      EMBEDDING_MODEL: text-embedding-3-small\n      EMBEDDING_DIM: 1536\n      FILESERVER_URL_PREFIX: http://backend:8000/api/files\n      SYSTEM_PROMPT: 'You are a helpful assistant who helps users with their questions.'\n      APP_HOST: 0.0.0.0\n      APP_PORT: 8000\n      ADMIN_EMAIL: admin@ragsaas.com\n      ADMIN_PASSWORD: ragsaas\n      JWT_SECRET_KEY:\n      JWT_REFRESH_SECRET_KEY:\n      ARIZE_PHOENIX_ENDPOINT: http://arizephoenix:6006\n    depends_on:\n      - qdrant\n      - mongodb\n      - arizephoenix\n    networks:\n      - ragsaas-network\n\n  frontend:\n    build:\n      context: ./frontend\n      dockerfile: Dockerfile\n    image: ragsaas/frontend:latest\n    container_name: frontend\n    ports:\n      - '3000:3000'\n    environment:\n      NEXT_PUBLIC_SERVER_URL: http://backend:8000\n      NEXT_PUBLIC_CHAT_API: http://backend:8000/api/chat\n    depends_on:\n      - backend\n    networks:\n      - ragsaas-network\n\nnetworks:\n  ragsaas-network:\n    name: ragsaas-network\n    driver: bridge\n\nvolumes:\n  mongodb_data:\n"
  },
  {
    "path": "frontend/.eslintrc.json",
    "content": "{\n  \"extends\": \"next/core-web-vitals\"\n}\n"
  },
  {
    "path": "frontend/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_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\n# misc\n.DS_Store\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": "frontend/Dockerfile",
    "content": "FROM node:18-alpine AS base\n\nFROM base AS deps\n\nRUN apk add --no-cache libc6-compat\nWORKDIR /app\n\nCOPY package.json ./\n\nRUN npm update && npm install\n\n# If you want yarn update and  install uncomment the bellow\n\n# RUN yarn install &&  yarn upgrade\n\n\n\nFROM base AS builder\nWORKDIR /app\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY . .\n\nRUN npm run build\n\nFROM base AS runner\nWORKDIR /app\n\nENV NODE_ENV production\nRUN addgroup --system --gid 1001 nodejs\nRUN adduser --system --uid 1001 nextjs\n\nCOPY --from=builder /app/public ./public\n\nRUN mkdir .next\nRUN chown nextjs:nodejs .next\n\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static\n\nUSER nextjs\n\nEXPOSE 3000\n\nENV PORT 3000\n\nCMD [\"node\", \"server.js\"]"
  },
  {
    "path": "frontend/README.md",
    "content": "This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).\n\n## Getting Started\n\nFirst, run the development server:\n\n```bash\nnpm run dev\n# or\nyarn dev\n# or\npnpm dev\n# or\nbun dev\n```\n\nOpen [http://localhost:3000](http://localhost:3000) with your browser to see the result.\n\nYou can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.\n\nThis project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.\n\n## Learn More\n\nTo learn more about Next.js, take a look at the following resources:\n\n- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.\n- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.\n\nYou can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!\n\n## Deploy on Vercel\n\nThe easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.\n\nCheck out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.\n"
  },
  {
    "path": "frontend/app/(auth)/signin/page.tsx",
    "content": "'use client';\n\nimport Image from 'next/image';\nimport Link from 'next/link';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport BannerCard from '@/components/banner-card';\nimport { ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react';\nimport { useState, FormEvent, Suspense } from 'react';\nimport { useRouter } from 'next/navigation';\nimport { useAuth } from '@/app/authProvider';\nimport axios, { AxiosError } from 'axios';\nimport { toast } from 'sonner';\nimport Loading from '@/components/loading';\n\ninterface LoginResponse {\n  access_token: string;\n  refresh_token: string;\n}\n\ninterface UserResponse {\n  id: string;\n  email: string;\n  first_name: string;\n  last_name: string;\n  role: string;\n}\nfunction SignInContent() {\n  const [email, setEmail] = useState<string>('');\n  const [password, setPassword] = useState<string>('');\n  const [showPassword, setShowPassword] = useState<boolean>(false);\n  const [error, setError] = useState<string>('');\n  const [isLoading, setIsLoading] = useState<boolean>(false);\n  const router = useRouter();\n  const { login } = useAuth();\n\n  const togglePasswordVisibility = () => {\n    setShowPassword(!showPassword);\n  };\n\n  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    setError('');\n    setIsLoading(true);\n\n    const formData = new FormData();\n    formData.append('username', email);\n    formData.append('password', password);\n\n    try {\n      const response = await axios.post<LoginResponse>(\n        `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/login`,\n        formData,\n        {\n          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n        }\n      );\n\n      const { access_token, refresh_token } = response.data;\n\n      // Get user details\n      const userResponse = await axios.get<UserResponse>(\n        `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/me`,\n        {\n          headers: { Authorization: `Bearer ${access_token}` },\n        }\n      );\n\n      const {\n        email: userEmail,\n        first_name,\n        last_name,\n        role,\n      } = userResponse.data;\n\n      login(access_token, refresh_token, userEmail, first_name, last_name);\n      toast.success('Sign In successful');\n      router.push('/chat');\n    } catch (error) {\n      if (axios.isAxiosError(error)) {\n        const axiosError = error as AxiosError<{ detail: string }>;\n        setError(\n          axiosError.response?.data?.detail ||\n            'An error occurred during sign in'\n        );\n      } else {\n        setError('An unexpected error occurred');\n      }\n      toast.error('Sign In failed. Please try again.');\n    } finally {\n      setIsLoading(false);\n    }\n  };\n\n  return (\n    <div className=\"flex h-full w-full flex-col lg:flex-row\">\n      <div className=\"flex flex-1 items-center justify-center p-6 lg:p-12\">\n        <div className=\"w-full max-w-[400px] space-y-6\">\n          <Button variant=\"ghost\" className=\"mb-4\" asChild>\n            <Link href=\"/\">\n              <ArrowLeft className=\"mr-2 h-4 w-4\" />\n              Back\n            </Link>\n          </Button>\n          <div className=\"space-y-2 text-center\">\n            <h1 className=\"text-3xl font-bold\">Login</h1>\n            <p className=\"text-balance text-muted-foreground\">\n              Enter your email below to login to your account\n            </p>\n          </div>\n          <form onSubmit={handleSubmit} className=\"space-y-4\">\n            <div className=\"space-y-2\">\n              <Label htmlFor=\"email\">Email</Label>\n              <Input\n                id=\"email\"\n                type=\"email\"\n                placeholder=\"m@example.com\"\n                required\n                value={email}\n                onChange={(e) => setEmail(e.target.value)}\n              />\n            </div>\n            <div className=\"space-y-2\">\n              <div className=\"flex items-center justify-between\">\n                <Label htmlFor=\"password\">Password</Label>\n              </div>\n              <div className=\"relative\">\n                <Input\n                  id=\"password\"\n                  type={showPassword ? 'text' : 'password'}\n                  required\n                  value={password}\n                  onChange={(e) => setPassword(e.target.value)}\n                />\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"icon\"\n                  className=\"absolute right-0 top-0 h-full px-3 py-2\"\n                  onClick={togglePasswordVisibility}\n                >\n                  {showPassword ? (\n                    <EyeOff className=\"h-4 w-4\" />\n                  ) : (\n                    <Eye className=\"h-4 w-4\" />\n                  )}\n                </Button>\n              </div>\n            </div>\n            {error && <p className=\"text-sm text-red-500\">{error}</p>}\n            <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n              {isLoading ? (\n                <>\n                  Signing In...\n                  <Loader2 className=\"h-4 w-4 animate-spin ml-4\" />\n                </>\n              ) : (\n                'Login'\n              )}\n            </Button>\n          </form>\n          <div className=\"text-center text-sm\">\n            Don&apos;t have an account?{' '}\n            <Link href=\"/signup\" className=\"underline\">\n              Sign up\n            </Link>\n          </div>\n        </div>\n      </div>\n      <div className=\"hidden flex-1 lg:flex justify-center items-center bg-muted\">\n        <BannerCard />\n      </div>\n    </div>\n  );\n}\n\nexport default function SignUp() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <SignInContent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/app/(auth)/signup/page.tsx",
    "content": "'use client';\n\nimport React, { Suspense, lazy, useState } from 'react';\nimport Image from 'next/image';\nimport Link from 'next/link';\nimport { useRouter } from 'next/navigation';\nimport { useAuth } from '@/app/authProvider';\nimport axios from 'axios';\nimport { ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react';\nimport { toast } from 'sonner';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\n// import BannerCard from '@/components/banner-card';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport Loading from '@/components/loading';\nconst BannerCard = lazy(() => import('@/components/banner-card'));\n\nfunction SignUpContent() {\n  const [formData, setFormData] = useState({\n    firstName: '',\n    lastName: '',\n    email: '',\n    password: '',\n    confirmPassword: '',\n  });\n  const [showPassword, setShowPassword] = useState<boolean>(false);\n  const [showConfirmPassword, setShowConfirmPassword] =\n    useState<boolean>(false);\n  const [error, setError] = useState('');\n  const [isLoading, setIsLoading] = useState(false);\n  const router = useRouter();\n  const { login } = useAuth();\n\n  const togglePasswordVisibility = (field: 'password' | 'confirmPassword') => {\n    if (field === 'password') {\n      setShowPassword(!showPassword);\n    } else {\n      setShowConfirmPassword(!showConfirmPassword);\n    }\n  };\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const { name, value } = e.target;\n    setFormData((prevData) => ({ ...prevData, [name]: value }));\n  };\n\n  const handleSubmit = async (e: React.FormEvent) => {\n    e.preventDefault();\n    setError('');\n    setIsLoading(true);\n\n    if (formData.password !== formData.confirmPassword) {\n      setError(\"Passwords don't match\");\n      setIsLoading(false);\n      return;\n    }\n\n    try {\n      const response = await axios.post(\n        `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/signup`,\n        {\n          first_name: formData.firstName,\n          last_name: formData.lastName,\n          email: formData.email,\n          password: formData.password,\n        }\n      );\n\n      if (response.data.status === 'success') {\n        toast('User Sign Up successful');\n        router.push('/signin');\n      }\n    } catch (error: any) {\n      toast(error.response?.data?.detail || 'An error occurred during sign up');\n      setError(\n        error.response?.data?.detail || 'An error occurred during sign up'\n      );\n    } finally {\n      setIsLoading(false);\n    }\n  };\n\n  return (\n    <div className=\"flex h-full w-full flex-col lg:flex-row\">\n      <div className=\"flex flex-1 items-center justify-center p-6 lg:p-12\">\n        <div className=\"w-full max-w-[400px] space-y-6\">\n          <Button variant=\"ghost\" className=\"mb-4\" asChild>\n            <Link href=\"/\">\n              <ArrowLeft className=\"mr-2 h-4 w-4\" />\n              Back\n            </Link>\n          </Button>\n          <div className=\"space-y-2 text-center\">\n            <h1 className=\"text-3xl font-bold\">Sign Up</h1>\n            <p className=\"text-balance text-muted-foreground\">\n              Create an account to get started\n            </p>\n          </div>\n          <form onSubmit={handleSubmit} className=\"space-y-4\">\n            <div className=\"grid grid-cols-2 gap-4\">\n              <div className=\"space-y-2\">\n                <Label htmlFor=\"firstName\">First name</Label>\n                <Input\n                  id=\"firstName\"\n                  name=\"firstName\"\n                  placeholder=\"John\"\n                  required\n                  value={formData.firstName}\n                  onChange={handleChange}\n                />\n              </div>\n              <div className=\"space-y-2\">\n                <Label htmlFor=\"lastName\">Last name</Label>\n                <Input\n                  id=\"lastName\"\n                  name=\"lastName\"\n                  placeholder=\"Doe\"\n                  required\n                  value={formData.lastName}\n                  onChange={handleChange}\n                />\n              </div>\n            </div>\n            <div className=\"space-y-2\">\n              <Label htmlFor=\"email\">Email</Label>\n              <Input\n                id=\"email\"\n                name=\"email\"\n                type=\"email\"\n                placeholder=\"m@example.com\"\n                required\n                value={formData.email}\n                onChange={handleChange}\n              />\n            </div>\n            <div className=\"space-y-2\">\n              <Label htmlFor=\"password\">Password</Label>\n              <div className=\"relative\">\n                <Input\n                  id=\"password\"\n                  name=\"password\"\n                  type={showPassword ? 'text' : 'password'}\n                  required\n                  value={formData.password}\n                  onChange={handleChange}\n                />\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"icon\"\n                  className=\"absolute right-0 top-0 h-full px-3 py-2\"\n                  onClick={() => togglePasswordVisibility('password')}\n                >\n                  {showPassword ? (\n                    <EyeOff className=\"h-4 w-4\" />\n                  ) : (\n                    <Eye className=\"h-4 w-4\" />\n                  )}\n                </Button>\n              </div>\n            </div>\n            <div className=\"space-y-2\">\n              <Label htmlFor=\"confirmPassword\">Confirm Password</Label>\n              <div className=\"relative\">\n                <Input\n                  id=\"confirmPassword\"\n                  name=\"confirmPassword\"\n                  type={showConfirmPassword ? 'text' : 'password'}\n                  required\n                  value={formData.confirmPassword}\n                  onChange={handleChange}\n                />\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"icon\"\n                  className=\"absolute right-0 top-0 h-full px-3 py-2\"\n                  onClick={() => togglePasswordVisibility('confirmPassword')}\n                >\n                  {showConfirmPassword ? (\n                    <EyeOff className=\"h-4 w-4\" />\n                  ) : (\n                    <Eye className=\"h-4 w-4\" />\n                  )}\n                </Button>\n              </div>\n            </div>\n            {error && (\n              <Alert variant=\"destructive\">\n                <AlertDescription>{error}</AlertDescription>\n              </Alert>\n            )}\n            <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n              {isLoading ? 'Creating Account...' : 'Create Account'}\n              {isLoading ? (\n                <Loader2 className=\"h-4 w-4 animate-spin ml-4\" />\n              ) : (\n                <></>\n              )}\n            </Button>\n          </form>\n          <div className=\"text-center text-sm\">\n            Already have an account?{' '}\n            <Link href=\"/signin\" className=\"underline\">\n              Log in\n            </Link>\n          </div>\n        </div>\n      </div>\n      <div className=\"hidden flex-1 lg:flex justify-center items-center bg-muted\">\n        <BannerCard />\n      </div>\n    </div>\n  );\n}\n\nexport default function SignUp() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <SignUpContent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/app/ConversationContext.tsx",
    "content": "'use client';\n\nimport React, { createContext, useContext, useState, useEffect } from 'react';\n\ninterface Conversation {\n  _id: string;\n  summary: string;\n  created_at?: string;\n  updated_at?: string;\n}\n\ninterface ConversationsByDate {\n  today: Conversation[];\n  yesterday: Conversation[];\n  last_7_days: Conversation[];\n  before_that: Conversation[];\n}\n\ninterface ConversationContextProps {\n  conversationList: ConversationsByDate;\n  setConversationList: React.Dispatch<\n    React.SetStateAction<ConversationsByDate>\n  >;\n  isSidebarOpen: boolean;\n  setIsSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;\n}\n\nconst ConversationContext = createContext<ConversationContextProps | undefined>(\n  undefined\n);\n\nexport const useConversationContext = () => {\n  const context = useContext(ConversationContext);\n  if (context === undefined) {\n    throw new Error(\n      'useConversationContext must be used within a ConversationProvider'\n    );\n  }\n  return context;\n};\n\ninterface ConversationProviderProps {\n  children: React.ReactNode;\n}\n\nexport const ConversationProvider: React.FC<ConversationProviderProps> = ({\n  children,\n}) => {\n  const [conversationList, setConversationList] = useState<ConversationsByDate>(\n    {\n      today: [],\n      yesterday: [],\n      last_7_days: [],\n      before_that: [],\n    }\n  );\n  const [isSidebarOpen, setIsSidebarOpen] = useState(false);\n\n  return (\n    <ConversationContext.Provider\n      value={{\n        conversationList,\n        setConversationList,\n        isSidebarOpen,\n        setIsSidebarOpen,\n      }}\n    >\n      {children}\n    </ConversationContext.Provider>\n  );\n};\n"
  },
  {
    "path": "frontend/app/admin/AdminAuthProvider.tsx",
    "content": "'use client';\n\nimport React, { createContext, useState, useContext, useEffect } from 'react';\nimport { useRouter } from 'next/navigation';\nimport axios from 'axios';\nimport Cookies from 'js-cookie';\n\ninterface AdminAuthContextType {\n  isAdminAuthenticated: boolean;\n  adminData: {\n    email: string;\n    firstName: string;\n    lastName: string;\n    role: string;\n  } | null;\n}\n\nconst AdminAuthContext = createContext<AdminAuthContextType | undefined>(\n  undefined\n);\n\nexport function AdminAuthProvider({ children }: { children: React.ReactNode }) {\n  const [isAdminAuthenticated, setIsAdminAuthenticated] =\n    useState<boolean>(false);\n  const [adminData, setAdminData] =\n    useState<AdminAuthContextType['adminData']>(null);\n  const router = useRouter();\n\n  const axiosInstance = axios.create({\n    baseURL: process.env.NEXT_PUBLIC_SERVER_URL,\n    headers: {\n      'Content-Type': 'application/json',\n      Authorization: `Bearer ${Cookies.get('accessToken')}`,\n    },\n  });\n\n  useEffect(() => {\n    const verifyAdminStatus = async () => {\n      const accessToken = Cookies.get('accessToken');\n      if (!accessToken) {\n        setIsAdminAuthenticated(false);\n        router.push('/');\n        return;\n      }\n\n      try {\n        const response = await axiosInstance.get('/api/auth/verify-admin');\n        if (response.data.isAdmin) {\n          setIsAdminAuthenticated(true);\n          fetchAdminData();\n        } else {\n          setIsAdminAuthenticated(false);\n          router.push('/');\n        }\n      } catch (error) {\n        console.error('Error verifying admin status:', error);\n        setIsAdminAuthenticated(false);\n        router.push('/');\n      }\n    };\n\n    verifyAdminStatus();\n  }, [router]);\n\n  const fetchAdminData = async () => {\n    try {\n      const response = await axiosInstance.get('/api/auth/me');\n      setAdminData(response.data);\n    } catch (error) {\n      console.error('Failed to fetch admin data:', error);\n    }\n  };\n\n  return (\n    <AdminAuthContext.Provider\n      value={{\n        isAdminAuthenticated,\n        adminData,\n      }}\n    >\n      {children}\n    </AdminAuthContext.Provider>\n  );\n}\n\nexport const useAdminAuth = () => {\n  const context = useContext(AdminAuthContext);\n  if (context === undefined) {\n    throw new Error('useAdminAuth must be used within an AdminAuthProvider');\n  }\n  return context;\n};\n"
  },
  {
    "path": "frontend/app/admin/DataIngestion.tsx",
    "content": "'use client';\nimport React, { useState } from 'react';\nimport { useAuth } from '@/app/authProvider';\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card';\nimport { Button } from '@/components/ui/button';\nimport { Label } from '@/components/ui/label';\nimport { Input } from '@/components/ui/input';\nimport { LoaderIcon, Upload } from 'lucide-react';\nimport { FileUpload } from '@/components/ui/file-upload';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/components/ui/select';\n\nexport default function DataIngestion() {\n  const { axiosInstance } = useAuth();\n  const [file, setFile] = useState<File | null>(null);\n  const [isUploading, setIsUploading] = useState(false);\n  const [uploadResult, setUploadResult] = useState<string | null>(null);\n\n  const handleFileUpload = (files: File[]) => {\n    if (files.length > 0) {\n      setFile(files[0]);\n    }\n  };\n\n  const uploadFile = async () => {\n    if (!file) return;\n\n    setIsUploading(true);\n    setUploadResult(null);\n\n    const formData = new FormData();\n    formData.append('file', file);\n\n    try {\n      const response = await axiosInstance.post(\n        '/api/admin/upload_data',\n        formData,\n        {\n          headers: {\n            'Content-Type': 'multipart/form-data',\n          },\n        }\n      );\n\n      setUploadResult(`File uploaded successfully. ${response.data.message}`);\n    } catch (error) {\n      console.error('Error uploading file:', error);\n      setUploadResult('Error uploading file. Please try again.');\n    } finally {\n      setIsUploading(false);\n      setFile(null);\n    }\n  };\n\n  return (\n    <Card>\n      <CardHeader>\n        <CardTitle>Data Ingestion</CardTitle>\n        <CardDescription>Manage data ingestion processes.</CardDescription>\n      </CardHeader>\n      <CardContent>\n        <div className=\"space-y-4\">\n          <div className=\"w-full mx-auto min-h-96 border border-dashed bg-white dark:bg-black border-neutral-200 dark:border-neutral-800 rounded-lg\">\n            <FileUpload onChange={handleFileUpload} />\n          </div>\n          {file && (\n            <div className=\"flex items-center space-x-2\">\n              <Button\n                onClick={uploadFile}\n                disabled={isUploading}\n                variant=\"default\"\n                className=\"flex items-center w-full\"\n              >\n                {isUploading ? (\n                  <LoaderIcon className=\"mr-2 h-4 w-4 animate-spin\" />\n                ) : (\n                  <Upload className=\"mr-2 h-4 w-4\" />\n                )}\n                {isUploading ? 'Uploading and Ingesting...' : 'Ingest File'}\n              </Button>\n            </div>\n          )}\n          {uploadResult && (\n            <div className=\"mt-2 text-sm text-gray-600 dark:text-gray-400\">\n              {uploadResult}\n            </div>\n          )}\n          <div>\n            <Label htmlFor=\"ingestionStrategy\">\n              Ingestion Strategy (Coming Soon)\n            </Label>\n            <Select disabled>\n              <SelectTrigger>\n                <SelectValue placeholder=\"Select a strategy\" />\n              </SelectTrigger>\n              <SelectContent>\n                <SelectItem value=\"fixed\">Fixed Size Chunking</SelectItem>\n                <SelectItem value=\"semantic\">Semantic Chunking</SelectItem>\n              </SelectContent>\n            </Select>\n          </div>\n          <div>\n            <Label htmlFor=\"parser\">Parser (Coming Soon)</Label>\n            <Select disabled>\n              <SelectTrigger>\n                <SelectValue placeholder=\"Select a parser\" />\n              </SelectTrigger>\n              <SelectContent>\n                <SelectItem value=\"llama\">Llama Parse</SelectItem>\n                <SelectItem value=\"omni\">Omniparse</SelectItem>\n              </SelectContent>\n            </Select>\n          </div>\n        </div>\n      </CardContent>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/app/admin/RAGConfiguration.tsx",
    "content": "'use client';\nimport React, { useEffect, useState } from 'react';\nimport { useAuth } from '@/app/authProvider';\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card';\nimport { Button } from '@/components/ui/button';\nimport { Label } from '@/components/ui/label';\nimport { Input } from '@/components/ui/input';\nimport { Textarea } from '@/components/ui/textarea';\nimport { Separator } from '@/components/ui/separator';\nimport { PlusCircle, Trash2 } from 'lucide-react';\n\nexport default function RAGConfiguration() {\n  const { axiosInstance } = useAuth();\n  const [systemPrompt, setSystemPrompt] = useState<string>('');\n  const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>([]);\n  const [configLoading, setConfigLoading] = useState<boolean>(true);\n  const [configError, setConfigError] = useState<string | null>(null);\n  const [systemPromptLoading, setSystemPromptLoading] = useState(false);\n  const [startersLoading, setStartersLoading] = useState(false);\n  const [initialSystemPrompt, setInitialSystemPrompt] = useState<string>('');\n  const [initialSuggestedQuestions, setInitialSuggestedQuestions] = useState<\n    string[]\n  >([]);\n\n  useEffect(() => {\n    fetchConfig();\n  }, [axiosInstance]);\n\n  const fetchConfig = async () => {\n    setConfigLoading(true);\n    setConfigError(null);\n    try {\n      const [configResponse, systemPromptResponse] = await Promise.all([\n        axiosInstance.get('/api/chat/config'),\n        axiosInstance.get('/api/admin/system-prompt'),\n      ]);\n\n      const config = configResponse.data;\n      const systemPromptData = systemPromptResponse.data;\n\n      setSystemPrompt(systemPromptData.system_prompt || '');\n      setInitialSystemPrompt(systemPromptData.system_prompt || '');\n      setSuggestedQuestions(config.starterQuestions || []);\n      setInitialSuggestedQuestions(config.starterQuestions || []);\n      setConfigLoading(false);\n    } catch (err: any) {\n      setConfigError(err.message || 'Failed to fetch configuration');\n      setConfigLoading(false);\n    }\n  };\n\n  const updateSystemPrompt = async () => {\n    setSystemPromptLoading(true);\n    try {\n      const response = await axiosInstance.put('/api/admin/system-prompt', {\n        new_prompt: systemPrompt,\n      });\n      if (response.status === 200) {\n        console.log('System prompt updated successfully');\n        setInitialSystemPrompt(systemPrompt);\n      }\n    } catch (error) {\n      console.error('Failed to update system prompt:', error);\n    } finally {\n      setSystemPromptLoading(false);\n    }\n  };\n\n  const updateConversationStarters = async () => {\n    setStartersLoading(true);\n    try {\n      const newStarters = suggestedQuestions.filter((q) => q.trim() !== '');\n      const response = await axiosInstance.put(\n        '/api/admin/conversation-starters',\n        { new_starters: newStarters }\n      );\n      if (response.status === 200) {\n        console.log('Conversation starters updated successfully');\n        setInitialSuggestedQuestions(newStarters);\n      }\n    } catch (error) {\n      console.error('Failed to update conversation starters:', error);\n    } finally {\n      setStartersLoading(false);\n    }\n  };\n\n  const addSuggestedQuestion = () => {\n    setSuggestedQuestions([...suggestedQuestions, '']);\n  };\n\n  const updateSuggestedQuestion = (index: number, value: string) => {\n    const updatedQuestions = [...suggestedQuestions];\n    updatedQuestions[index] = value;\n    setSuggestedQuestions(updatedQuestions);\n  };\n\n  const deleteSuggestedQuestion = (index: number) => {\n    const updatedQuestions = suggestedQuestions.filter((_, i) => i !== index);\n    setSuggestedQuestions(updatedQuestions);\n  };\n\n  const isSystemPromptChanged = systemPrompt !== initialSystemPrompt;\n  const areSuggestedQuestionsChanged =\n    JSON.stringify(suggestedQuestions) !==\n    JSON.stringify(initialSuggestedQuestions);\n\n  if (configLoading) return <div>Loading configuration...</div>;\n  if (configError) return <div>Error: {configError}</div>;\n\n  return (\n    <Card>\n      <CardHeader>\n        <CardTitle>RAG Configuration</CardTitle>\n        <CardDescription>\n          Configure Retrieval-Augmented Generation settings.\n        </CardDescription>\n      </CardHeader>\n      <CardContent className=\"space-y-4\">\n        <div>\n          <Label htmlFor=\"systemPrompt\">System Prompt</Label>\n          <Textarea\n            id=\"systemPrompt\"\n            value={systemPrompt}\n            onChange={(e) => setSystemPrompt(e.target.value)}\n            placeholder=\"Enter system prompt here...\"\n          />\n          <Button\n            onClick={updateSystemPrompt}\n            className=\"mt-2 w-full\"\n            variant={isSystemPromptChanged ? 'default' : 'secondary'}\n            disabled={systemPromptLoading || !isSystemPromptChanged}\n          >\n            {systemPromptLoading ? 'Updating...' : 'Update System Prompt'}\n          </Button>\n        </div>\n        <Separator />\n        <div>\n          <Label>Suggested Questions</Label>\n          {suggestedQuestions.map((question, index) => (\n            <div key={index} className=\"flex items-center space-x-2 mt-2\">\n              <Input\n                value={question}\n                onChange={(e) => updateSuggestedQuestion(index, e.target.value)}\n                placeholder=\"Enter a suggested question...\"\n              />\n              <Button\n                variant=\"outline\"\n                size=\"icon\"\n                onClick={() => deleteSuggestedQuestion(index)}\n              >\n                <Trash2 className=\"h-4 w-4\" />\n              </Button>\n            </div>\n          ))}\n          <div className=\"w-full flex justify-between items-center mt-2\">\n            <Button\n              variant=\"outline\"\n              className=\"mt-2\"\n              onClick={addSuggestedQuestion}\n            >\n              <PlusCircle className=\"h-4 w-4 mr-2\" />\n              Add Question\n            </Button>\n            <Button\n              variant={areSuggestedQuestionsChanged ? 'default' : 'secondary'}\n              onClick={updateConversationStarters}\n              className=\"mt-2 ml-2\"\n              disabled={startersLoading || !areSuggestedQuestionsChanged}\n            >\n              {startersLoading ? 'Updating...' : 'Update Conversation Starters'}\n            </Button>\n          </div>\n        </div>\n      </CardContent>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/app/admin/UsersManagement.tsx",
    "content": "'use client';\nimport React, { useEffect, useState } from 'react';\nimport { useAuth } from '@/app/authProvider';\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card';\nimport { Button } from '@/components/ui/button';\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from '@/components/ui/table';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/components/ui/select';\nimport { Switch } from '@/components/ui/switch';\nimport { Trash2 } from 'lucide-react';\nimport { AxiosError } from 'axios';\n\ninterface User {\n  user_id: string;\n  email: string;\n  first_name: string | null;\n  last_name: string | null;\n  role: string;\n  disabled?: boolean;\n}\n\ninterface UsersManagementProps {\n  adminEmail: string | undefined;\n}\n\nexport default function UsersManagement({ adminEmail }: UsersManagementProps) {\n  const { axiosInstance } = useAuth();\n  const [users, setUsers] = useState<User[]>([]);\n  const [loading, setLoading] = useState<boolean>(true);\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    fetchUsers();\n  }, [axiosInstance]);\n\n  const fetchUsers = async () => {\n    try {\n      const response = await axiosInstance.get<{ users: User[] }>(\n        '/api/admin/users'\n      );\n      setUsers(response.data.users);\n      setLoading(false);\n    } catch (err) {\n      const axiosError = err as AxiosError;\n      setError(axiosError.message || 'Failed to fetch users');\n      setLoading(false);\n    }\n  };\n\n  const deleteUser = async (userId: string) => {\n    try {\n      await axiosInstance.delete(`/api/admin/users/${userId}`);\n      setUsers(users.filter((user) => user.user_id !== userId));\n    } catch (err) {\n      const axiosError = err as AxiosError;\n      setError(axiosError.message || 'Failed to delete user');\n    }\n  };\n\n  const updateUser = async (userId: string, updatedData: Partial<User>) => {\n    try {\n      await axiosInstance.put(`/api/admin/users/${userId}`, updatedData);\n      setUsers(\n        users.map((user) =>\n          user.user_id === userId ? { ...user, ...updatedData } : user\n        )\n      );\n    } catch (err) {\n      const axiosError = err as AxiosError;\n      setError(axiosError.message || 'Failed to update user');\n    }\n  };\n\n  if (loading) return <div>Loading...</div>;\n  if (error) return <div>Error: {error}</div>;\n\n  return (\n    <Card>\n      <CardHeader>\n        <CardTitle>Users Management</CardTitle>\n        <CardDescription>Manage user accounts</CardDescription>\n      </CardHeader>\n      <CardContent>\n        <Table>\n          <TableHeader>\n            <TableRow>\n              <TableHead>Name</TableHead>\n              <TableHead>Email</TableHead>\n              <TableHead>Role</TableHead>\n              <TableHead>Status</TableHead>\n              <TableHead>Actions</TableHead>\n            </TableRow>\n          </TableHeader>\n          <TableBody>\n            {users\n              .filter((user) => user.email !== adminEmail)\n              .map((user) => (\n                <TableRow key={user.user_id}>\n                  <TableCell>\n                    {`${user.first_name || ''} ${user.last_name || ''}`.trim()}\n                  </TableCell>\n                  <TableCell>{user.email}</TableCell>\n                  <TableCell>\n                    <Select\n                      onValueChange={(value) =>\n                        updateUser(user.user_id, { role: value })\n                      }\n                      defaultValue={user.role}\n                      disabled={\n                        user.role === 'admin' &&\n                        users.filter((u) => u.role === 'admin').length === 1\n                      }\n                    >\n                      <SelectTrigger>\n                        <SelectValue placeholder=\"Select role\" />\n                      </SelectTrigger>\n                      <SelectContent>\n                        <SelectItem value=\"user\">User</SelectItem>\n                        <SelectItem value=\"admin\">Admin</SelectItem>\n                      </SelectContent>\n                    </Select>\n                  </TableCell>\n                  <TableCell>\n                    <Switch\n                      checked={!user.disabled}\n                      onCheckedChange={(checked) =>\n                        updateUser(user.user_id, { disabled: !checked })\n                      }\n                      disabled={user.role === 'admin'}\n                    />\n                  </TableCell>\n                  <TableCell>\n                    <Button\n                      variant=\"destructive\"\n                      onClick={() => deleteUser(user.user_id)}\n                      disabled={user.role === 'admin'}\n                    >\n                      <Trash2 className=\"h-4 w-4\" />\n                    </Button>\n                  </TableCell>\n                </TableRow>\n              ))}\n          </TableBody>\n        </Table>\n      </CardContent>\n    </Card>\n  );\n}\n"
  },
  {
    "path": "frontend/app/admin/layout.tsx",
    "content": "'use client';\n\nimport React from 'react';\nimport { AdminAuthProvider } from './AdminAuthProvider';\nimport { ScrollArea } from '@/components/ui/scroll-area';\n\nexport default function AdminLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return (\n    <AdminAuthProvider>\n      <ScrollArea className=\"w-full h-full\">\n        <main>{children}</main>\n      </ScrollArea>\n    </AdminAuthProvider>\n  );\n}\n"
  },
  {
    "path": "frontend/app/admin/page.tsx",
    "content": "'use client';\n\nimport React, { useEffect, useState } from 'react';\nimport { useAdminAuth } from './AdminAuthProvider';\nimport { useAuth } from '@/app/authProvider';\nimport Loading from '@/components/loading';\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card';\nimport { Avatar, AvatarFallback } from '@/components/ui/avatar';\nimport UsersManagement from '@/app/admin/UsersManagement';\nimport DataIngestion from '@/app/admin/DataIngestion';\nimport RAGConfiguration from '@/app/admin/RAGConfiguration';\n\nexport default function AdminPage() {\n  const { isAdminAuthenticated, adminData } = useAdminAuth();\n  const { isAuthenticated } = useAuth();\n\n  if (!isAdminAuthenticated) {\n    return <Loading />;\n  }\n\n  if (!isAuthenticated) return <div>Unauthorized</div>;\n\n  return (\n    <div className=\"container mx-auto px-4 py-8\">\n      <div className=\"flex-col md:flex md:flex-row justify-between items-center mb-6 \">\n        <h1 className=\"text-2xl font-bold py-2\">Dashboard</h1>\n\n        {adminData && Object.keys(adminData).length > 0 && (\n          <Card className=\"flex items-center space-x-4 p-4\">\n            <Avatar className=\"h-10 w-10\">\n              <AvatarFallback>\n                {adminData.firstName?.[0]}\n                {adminData.lastName?.[0]}\n              </AvatarFallback>\n            </Avatar>\n            <div>\n              {(adminData.firstName || adminData.lastName) && (\n                <p className=\"font-medium\">\n                  {`${adminData.firstName || ''} ${\n                    adminData.lastName || ''\n                  }`.trim()}\n                </p>\n              )}\n              {adminData.email && (\n                <CardDescription>{adminData.email}</CardDescription>\n              )}\n              {adminData.role && (\n                <p className=\"text-sm text-muted-foreground\">\n                  Role: {adminData.role}\n                </p>\n              )}\n            </div>\n          </Card>\n        )}\n      </div>\n\n      <Tabs defaultValue=\"users\" className=\"w-full\">\n        <TabsList className=\"grid w-full grid-cols-3\">\n          <TabsTrigger value=\"users\">Users Tracking</TabsTrigger>\n          <TabsTrigger value=\"ingestion\">Data Ingestion</TabsTrigger>\n          <TabsTrigger value=\"rag\">RAG Configuration</TabsTrigger>\n        </TabsList>\n        <TabsContent value=\"users\">\n          <UsersManagement adminEmail={adminData?.email} />\n        </TabsContent>\n        <TabsContent value=\"ingestion\">\n          <DataIngestion />\n        </TabsContent>\n        <TabsContent value=\"rag\">\n          <RAGConfiguration />\n        </TabsContent>\n      </Tabs>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/app/authProvider.tsx",
    "content": "'use client';\n\nimport React, { createContext, useState, useContext, useEffect } from 'react';\nimport { useRouter, usePathname } from 'next/navigation';\nimport Cookies from 'js-cookie';\nimport axios, { AxiosInstance } from 'axios';\nimport { jwtDecode, JwtPayload } from 'jwt-decode';\n\ninterface AuthContextType {\n  isAuthenticated: boolean;\n  email: string | null;\n  firstName: string | null;\n  lastName: string | null;\n  accessToken: string | null;\n  refreshToken: string | null;\n  login: (\n    accessToken: string,\n    refreshToken: string,\n    email: string,\n    firstName: string,\n    lastName: string\n  ) => void;\n  logout: () => void;\n  axiosInstance: AxiosInstance;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nconst authRoutes = ['/signin', '/signup', '/resetPassword', '/verifiedEmail'];\nconst protectedRoutes = ['/chat', '/profile'];\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n  const [email, setEmail] = useState<string | null>(null);\n  const [firstName, setFirstName] = useState<string | null>(null);\n  const [lastName, setLastName] = useState<string | null>(null);\n  const [accessToken, setAccessToken] = useState<string | null>(null);\n  const [refreshToken, setRefreshToken] = useState<string | null>(null);\n  const router = useRouter();\n  const pathname = usePathname();\n\n  const refreshAccessToken = async () => {\n    try {\n      const response = await axios.post(\n        `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/refresh`,\n        { refresh_token: refreshToken }\n      );\n      const { access_token, refresh_token } = response.data.tokens;\n      setAccessToken(access_token);\n      setRefreshToken(refresh_token);\n      Cookies.set('accessToken', access_token, { expires: 7 });\n      Cookies.set('refreshToken', refresh_token, { expires: 7 });\n      return access_token;\n    } catch (error) {\n      console.error('Error refreshing token:', error);\n      logout();\n      return null;\n    }\n  };\n\n  const axiosInstance: AxiosInstance = axios.create({\n    baseURL: process.env.NEXT_PUBLIC_SERVER_URL,\n    headers: {\n      'Content-Type': 'application/json',\n    },\n  });\n\n  axiosInstance.interceptors.request.use(\n    async (config) => {\n      if (accessToken) {\n        try {\n          const decodedToken = jwtDecode<JwtPayload>(accessToken);\n          const currentTime = Date.now() / 1000;\n\n          if (decodedToken.exp && decodedToken.exp < currentTime) {\n            const newAccessToken = await refreshAccessToken();\n            if (newAccessToken) {\n              config.headers['Authorization'] = `Bearer ${newAccessToken}`;\n            } else {\n              // If we couldn't refresh the token, we should probably log out the user\n              logout();\n              throw new axios.Cancel('Session expired. Please log in again.');\n            }\n          } else {\n            config.headers['Authorization'] = `Bearer ${accessToken}`;\n          }\n        } catch (error) {\n          console.error('Error processing token:', error);\n          logout();\n          throw new axios.Cancel('Invalid token. Please log in again.');\n        }\n      }\n      return config;\n    },\n    (error) => {\n      return Promise.reject(error);\n    }\n  );\n  useEffect(() => {\n    const checkAuthStatus = async () => {\n      const currentAccessToken = Cookies.get('accessToken');\n      const currentRefreshToken = Cookies.get('refreshToken');\n      const emailFromCookie = Cookies.get('email');\n\n      if (currentAccessToken && currentRefreshToken && emailFromCookie) {\n        setIsAuthenticated(true);\n        setAccessToken(currentAccessToken);\n        setRefreshToken(currentRefreshToken);\n        setEmail(emailFromCookie);\n        setFirstName(Cookies.get('firstName') || null);\n        setLastName(Cookies.get('lastName') || null);\n\n        if (authRoutes.includes(pathname)) {\n          router.push('/chat');\n        }\n      } else {\n        setIsAuthenticated(false);\n        if (protectedRoutes.includes(pathname)) {\n          router.push('/signin');\n        }\n      }\n    };\n\n    checkAuthStatus();\n  }, [router, pathname]);\n\n  const login = (\n    accessToken: string,\n    refreshToken: string,\n    email: string,\n    firstName: string,\n    lastName: string\n  ) => {\n    Cookies.set('accessToken', accessToken, { expires: 7 });\n    Cookies.set('refreshToken', refreshToken, { expires: 7 });\n    Cookies.set('email', email, { expires: 7 });\n    Cookies.set('firstName', firstName, { expires: 7 });\n    Cookies.set('lastName', lastName, { expires: 7 });\n\n    setIsAuthenticated(true);\n    setAccessToken(accessToken);\n    setRefreshToken(refreshToken);\n    setEmail(email);\n    setFirstName(firstName);\n    setLastName(lastName);\n    router.push('/chat');\n  };\n\n  const logout = () => {\n    Cookies.remove('accessToken');\n    Cookies.remove('refreshToken');\n    Cookies.remove('email');\n    Cookies.remove('firstName');\n    Cookies.remove('lastName');\n\n    setIsAuthenticated(false);\n    setAccessToken(null);\n    setRefreshToken(null);\n    setEmail(null);\n    setFirstName(null);\n    setLastName(null);\n    router.push('/signin');\n  };\n\n  return (\n    <AuthContext.Provider\n      value={{\n        isAuthenticated,\n        email,\n        firstName,\n        lastName,\n        accessToken,\n        refreshToken,\n        login,\n        logout,\n        axiosInstance,\n      }}\n    >\n      {children}\n    </AuthContext.Provider>\n  );\n}\n\nexport const useAuth = () => {\n  const context = useContext(AuthContext);\n  if (context === undefined) {\n    throw new Error('useAuth must be used within an AuthProvider');\n  }\n  return context;\n};\n"
  },
  {
    "path": "frontend/app/chat/page.tsx",
    "content": "'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { useChat } from 'ai/react';\nimport { ChatInput, ChatMessages } from '@/components/ui/chat';\nimport { useClientConfig } from '@/components/ui/chat/hooks/use-config';\nimport { useRouter, useSearchParams } from 'next/navigation';\nimport { Suspense } from 'react';\nimport { useConversationContext } from '@/app/ConversationContext';\nimport { useAuth } from '@/app/authProvider';\nimport Loading from '@/components/loading';\nimport { toast } from 'sonner';\nimport axios from 'axios';\n\nfunction ChatContent() {\n  const { accessToken, axiosInstance } = useAuth();\n  const { backend } = useClientConfig();\n  const router = useRouter();\n  const searchParams = useSearchParams();\n  const [conversationId, setConversationId] = useState<string | null>(null);\n  const { conversationList, setConversationList } = useConversationContext();\n  const [isClient, setIsClient] = useState(false);\n\n  useEffect(() => {\n    setIsClient(true);\n  }, []);\n\n  const fetchMessages = async () => {\n    if (!conversationId) return;\n    try {\n      const response = await axiosInstance.get(\n        `/api/conversation/${conversationId}`\n      );\n      setMessages(response.data.messages || []);\n    } catch (error: any) {\n      if (error.response && error.response.status === 401) {\n        return;\n      }\n      toast(`Failed to fetch conversation: ${error.message}`);\n    }\n  };\n\n  const fetchConversations = async () => {\n    try {\n      const response = await axiosInstance.get('/api/conversation/list');\n      setConversationList(response.data.conversations);\n    } catch (error: any) {\n      console.error('Error fetching conversations:', error.message);\n    }\n  };\n\n  const updateMessageContent = (\n    id: string,\n    oldContent: string,\n    newContent: string\n  ) => {\n    const messageIndex = messages.findIndex(\n      (m) => m.role === 'user' && m.content === oldContent\n    );\n    if (messageIndex !== -1) {\n      const updatedMessages = [...messages.slice(0, messageIndex)];\n      setMessages(updatedMessages);\n\n      append!({\n        role: 'user',\n        content: newContent,\n      });\n    }\n  };\n\n  const handleNewChat = async () => {\n    try {\n      const response = await axiosInstance.get('/api/conversation');\n      const newConversationId = response.data.conversation_id;\n      router.push(`/chat?conversation_id=${newConversationId}`);\n    } catch (error: any) {\n      console.error('Error creating new conversation:', error.message);\n    }\n  };\n\n  const {\n    messages,\n    input,\n    isLoading,\n    handleSubmit,\n    handleInputChange,\n    reload,\n    stop,\n    append,\n    setInput,\n    setMessages,\n  } = useChat({\n    api: `${backend}/api/chat?conversation_id=${conversationId}`,\n    headers: {\n      'Content-Type': 'application/json',\n      Authorization: `Bearer ${accessToken}`,\n    },\n    body: { conversation_id: conversationId },\n    onError: (error: unknown) => {\n      if (!(error instanceof Error)) throw error;\n      let errorMessage = 'An unexpected error occurred.';\n\n      try {\n        const errorResponse = JSON.parse(error.message);\n\n        if (errorResponse.detail === 'Not authenticated') {\n          alert('Session has expired. Please login again.');\n          router.push('/signin');\n          return;\n        }\n\n        if (errorResponse.detail) {\n          errorMessage = `Error: ${errorResponse.detail}`;\n        } else if (errorResponse.errors) {\n          errorMessage = `Validation Errors: ${errorResponse.errors.join(\n            ', '\n          )}`;\n        } else if (errorResponse.message) {\n          errorMessage = `Message: ${errorResponse.message}`;\n        } else if (errorResponse.error) {\n          errorMessage = `Error: ${errorResponse.error}`;\n        } else {\n          errorMessage = `Unknown error format: ${error.message}`;\n        }\n      } catch (parseError) {\n        errorMessage = `Error parsing response: ${error.message}`;\n      }\n\n      toast(errorMessage);\n    },\n  });\n\n  useEffect(() => {\n    if (isClient) {\n      fetchConversations();\n    }\n  }, [isClient, isLoading]);\n\n  useEffect(() => {\n    if (isClient && conversationId) {\n      fetchMessages();\n    }\n  }, [isClient, conversationId]);\n\n  useEffect(() => {\n    if (isClient) {\n      const urlConversationId = searchParams.get('conversation_id');\n      const query = searchParams.get('query');\n\n      setConversationId(urlConversationId);\n      if (query) {\n        setInput(query);\n      }\n\n      if (!urlConversationId) {\n        const timer = setTimeout(() => {\n          handleNewChat();\n        }, 1000);\n\n        return () => clearTimeout(timer);\n      }\n    }\n  }, [isClient, searchParams, setInput]);\n\n  if (!isClient) {\n    <Loading />;\n  }\n\n  return (\n    <div className=\"w-full h-full flex justify-center items-center bg-primary-foreground\">\n      <div className=\"space-y-2 w-full  md:w-[90%] lg:w-[70%] h-full flex flex-col p-4\">\n        <Suspense fallback={<Loading />}>\n          <ChatMessages\n            messages={messages}\n            isLoading={isLoading}\n            reload={reload}\n            stop={stop}\n            append={append}\n            updateMessageContent={updateMessageContent}\n          />\n        </Suspense>\n        <Suspense fallback={<Loading />}>\n          <ChatInput\n            input={input}\n            handleSubmit={handleSubmit}\n            handleInputChange={handleInputChange}\n            isLoading={isLoading}\n            messages={messages}\n            append={append}\n            setInput={setInput}\n          />\n        </Suspense>\n      </div>\n    </div>\n  );\n}\n\nexport default function Chat() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <ChatContent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/app/features/page.tsx",
    "content": "'use client';\n\nimport Link from 'next/link';\nimport { siteConfig } from '@/config/site';\nimport { cn } from '@/lib/utils';\nimport { buttonVariants } from '@/components/ui/button';\nimport { HoverEffect } from '@/components/ui/card-hover-effect';\nimport { Features } from '@/config/features';\nimport NumberTicker from '@/components/magicui/number-ticker';\nimport { Github, StarIcon } from 'lucide-react';\nimport useGitHubStars from '@/hooks/useGitHubStars';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport Loading from '@/components/loading';\nimport { Suspense } from 'react';\n\n// eslint-disable-next-line @next/next/no-async-client-component\nconst IndexPageContent = () => {\n  const stars = useGitHubStars('adithya-s-k/RAG-SaaS');\n  return (\n    <>\n      <ScrollArea className=\"w-full h-full\">\n        <section className=\"space-y-6 pb-8 pt-6 md:pb-12 md:pt-10 lg:py-32 min-h-screen md:h-fit flex flex-col justify-center\">\n          <div className=\"container flex max-w-[64rem] flex-col items-center gap-4 text-center\">\n            <Link\n              href={siteConfig.links.twitter}\n              className=\"rounded-2xlpx-4 py-1.5 text-sm font-medium\"\n              target=\"_blank\"\n            >\n              <button className=\"bg-slate-800 no-underline group cursor-pointer relative shadow-2xl shadow-zinc-900 rounded-full p-px text-xs font-semibold leading-6  text-white inline-block\">\n                <span className=\"absolute inset-0 overflow-hidden rounded-full\">\n                  <span className=\"absolute inset-0 rounded-full bg-[image:radial-gradient(75%_100%_at_50%_0%,rgba(56,189,248,0.6)_0%,rgba(56,189,248,0)_75%)] opacity-0 transition-opacity duration-500 group-hover:opacity-100\" />\n                </span>\n                <div className=\"relative flex space-x-2 items-center z-10 rounded-full bg-zinc-950 py-0.5 px-4 ring-1 ring-white/10 \">\n                  <span> Follow on Twitter</span>\n                  <svg\n                    fill=\"none\"\n                    height=\"16\"\n                    viewBox=\"0 0 24 24\"\n                    width=\"16\"\n                    xmlns=\"http://www.w3.org/2000/svg\"\n                  >\n                    <path\n                      d=\"M10.75 8.75L14.25 12L10.75 15.25\"\n                      stroke=\"currentColor\"\n                      strokeLinecap=\"round\"\n                      strokeLinejoin=\"round\"\n                      strokeWidth=\"1.5\"\n                    />\n                  </svg>\n                </div>\n                <span className=\"absolute -bottom-0 left-[1.125rem] h-px w-[calc(100%-2.25rem)] bg-gradient-to-r from-emerald-400/0 via-emerald-400/90 to-emerald-400/0 transition-opacity duration-500 group-hover:opacity-40\" />\n              </button>\n            </Link>\n\n            <h1 className=\"font-heading text-3xl sm:text-5xl md:text-6xl lg:text-7xl\">\n              Ship RAG Solutions ⚡Quickly\n            </h1>\n            <p className=\"max-w-[42rem] leading-normal text-muted-foreground sm:text-lg sm:leading-7\">\n              RAG-SaaS is an end-to-end platform for building\n              Retrieval-Augmented Generation (RAG) applications. It simplifies\n              deployment, allowing developers to focus on optimizing their RAG\n              systems.\n            </p>\n            <div className=\"space-x-4 flex\">\n              <Link\n                href=\"/signin\"\n                className={cn(\n                  buttonVariants(),\n                  'w-fit gap-2 overflow-hidden whitespace-pre md:flex',\n                  'group relative w-fit justify-center gap-2 rounded-md transition-all duration-300 ease-out hover:ring-2 hover:ring-primary hover:ring-offset-2'\n                )}\n              >\n                Get Started\n              </Link>\n              <Link\n                className={cn(\n                  buttonVariants(),\n                  'max-w-52 gap-2 overflow-hidden whitespace-pre md:flex',\n                  'group relative w-full justify-center gap-2 rounded-md transition-all duration-300 ease-out hover:ring-2 hover:ring-primary hover:ring-offset-2'\n                )}\n                target=\"_blank\"\n                href={siteConfig.links.github}\n              >\n                <span className=\"absolute right-0 -mt-12 h-32 w-8 translate-x-12 rotate-12 bg-white opacity-10 transition-all duration-1000 ease-out group-hover:-translate-x-40\" />\n                <div className=\"flex items-center\">\n                  <Github></Github>\n                  <span className=\"ml-1\">Star on GitHub</span>{' '}\n                </div>\n                <div className=\"ml-2 flex items-center gap-1 text-sm md:flex\">\n                  <StarIcon className=\"size-4 text-gray-500 transition-all duration-300 group-hover:text-yellow-300\" />\n                  <NumberTicker\n                    value={stars}\n                    className=\"font-display font-medium text-white dark:text-black\"\n                  />\n                </div>\n              </Link>\n            </div>\n          </div>\n        </section>\n        <section\n          id=\"features\"\n          className=\"container space-y-6 bg-slate-50 py-8 dark:bg-transparent md:py-12 lg:py-24\"\n        >\n          <div className=\"mx-auto flex max-w-[58rem] flex-col items-center space-y-4 text-center\">\n            <h2 className=\"font-heading text-3xl leading-[1.1] sm:text-3xl md:text-6xl\">\n              Features\n            </h2>\n          </div>\n          <HoverEffect items={Features} />\n        </section>\n        <section id=\"open-source\" className=\"container py-8 md:py-12 lg:py-24 \">\n          <div className=\"container mx-auto px-4 py-8 flex flex-col justify-center items-center\">\n            <h2 className=\"text-3xl font-bold mb-4\">Proudly Open Source</h2>\n            <p className=\"max-w-[85%] leading-normal text-muted-foreground sm:text-lg sm:leading-7 mb-4\">\n              RAG-SaaS is open source and powered by open source software.\n            </p>\n            <ul className=\"list-none space-y-2 mb-4\">\n              <li>\n                <span className=\"mr-2\">🦙</span>\n                <strong>LlamaIndex:</strong> For building and deploying RAG\n                pipelines\n              </li>\n              <li>\n                <span className=\"mr-2\">📦</span>\n                <strong>MongoDB:</strong> Used as both a normal database and a\n                vector database\n              </li>\n              <li>\n                <span className=\"mr-2\">⚡</span>\n                <strong>FastAPI:</strong> Backend API framework\n              </li>\n              <li>\n                <span className=\"mr-2\">⚛️</span>\n                <strong>Next.js:</strong> Frontend framework\n              </li>\n            </ul>\n            <p className=\"text-muted-foreground sm:text-lg sm:leading-7\">\n              The code is available on{' '}\n              <Link\n                href={siteConfig.links.github}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                className=\"underline underline-offset-4\"\n              >\n                GitHub\n              </Link>\n              .\n            </p>\n          </div>\n        </section>\n      </ScrollArea>\n    </>\n  );\n};\n\nexport default function IndexPage() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <IndexPageContent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/app/globals.css",
    "content": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n  :root {\n    --background: 0 0% 100%;\n    --foreground: 0 0% 3.9%;\n    --card: 0 0% 100%;\n    --card-foreground: 0 0% 3.9%;\n    --popover: 0 0% 100%;\n    --popover-foreground: 0 0% 3.9%;\n    --primary: 0 0% 9%;\n    --primary-foreground: 0 0% 98%;\n    --secondary: 0 0% 96.1%;\n    --secondary-foreground: 0 0% 9%;\n    --muted: 0 0% 96.1%;\n    --muted-foreground: 0 0% 45.1%;\n    --accent: 0 0% 96.1%;\n    --accent-foreground: 0 0% 9%;\n    --destructive: 0 84.2% 60.2%;\n    --destructive-foreground: 0 0% 98%;\n    --border: 0 0% 89.8%;\n    --input: 0 0% 89.8%;\n    --ring: 0 0% 3.9%;\n    --radius: 0.5rem;\n    --chart-1: 12 76% 61%;\n    --chart-2: 173 58% 39%;\n    --chart-3: 197 37% 24%;\n    --chart-4: 43 74% 66%;\n    --chart-5: 27 87% 67%;\n  }\n\n  .dark {\n    --background: 0 0% 3.9%;\n    --foreground: 0 0% 98%;\n    --card: 0 0% 3.9%;\n    --card-foreground: 0 0% 98%;\n    --popover: 0 0% 3.9%;\n    --popover-foreground: 0 0% 98%;\n    --primary: 0 0% 98%;\n    --primary-foreground: 0 0% 9%;\n    --secondary: 0 0% 14.9%;\n    --secondary-foreground: 0 0% 98%;\n    --muted: 0 0% 14.9%;\n    --muted-foreground: 0 0% 63.9%;\n    --accent: 0 0% 14.9%;\n    --accent-foreground: 0 0% 98%;\n    --destructive: 0 62.8% 30.6%;\n    --destructive-foreground: 0 0% 98%;\n    --border: 0 0% 14.9%;\n    --input: 0 0% 14.9%;\n    --ring: 0 0% 83.1%;\n    --chart-1: 220 70% 50%;\n    --chart-2: 160 60% 45%;\n    --chart-3: 30 80% 55%;\n    --chart-4: 280 65% 60%;\n    --chart-5: 340 75% 55%;\n  }\n}\n\n@layer base {\n  * {\n    @apply border-border;\n  }\n  html {\n    @apply overflow-x-hidden;\n  }\n  body {\n    @apply bg-background text-foreground overflow-x-hidden;\n  }\n}\n.content-height {\n  height: calc(100vh - 3.5rem); /* 3.5rem is the height of the navbar (h-14) */\n}\n"
  },
  {
    "path": "frontend/app/layout.tsx",
    "content": "import type { Metadata } from 'next';\n// import { Inter } from 'next/font/google';\nimport { Roboto } from 'next/font/google';\nimport { AuthProvider } from '@/app/authProvider';\nimport { ConversationProvider } from '@/app/ConversationContext';\nimport { Analytics } from '@/components/analytics';\nimport { siteConfig } from '@/config/site';\nimport { ThemeProvider } from '@/components/theme-provider';\nimport { Toaster } from '@/components/ui/sonner';\nimport './globals.css';\nimport { Header } from '@/components/header';\nimport Sidebar from '@/components/sidebar';\n\nconst roboto = Roboto({\n  weight: ['400', '700'],\n  subsets: ['latin'],\n  display: 'swap',\n});\n\nexport const metadata: Metadata = {\n  metadataBase: new URL(`${siteConfig.url}`),\n  title: {\n    default: siteConfig.name,\n    template: `%s | ${siteConfig.name}`,\n  },\n  description: siteConfig.description,\n  keywords: ['RAG', 'SAAS', 'RAG SAAS', 'AI SAAS', 'llamaindex'],\n  authors: [\n    {\n      name: 'Adithya S Kolavi',\n      url: 'https://adithyask.com',\n    },\n  ],\n  creator: 'Adithya S K',\n};\n\nexport const viewport = {\n  themeColor: [\n    { media: '(prefers-color-scheme: light)', color: 'white' },\n    { media: '(prefers-color-scheme: dark)', color: 'black' },\n  ],\n};\n\nexport default function RootLayout({\n  children,\n}: Readonly<{\n  children: React.ReactNode;\n}>) {\n  return (\n    <html lang=\"en\" suppressHydrationWarning>\n      <ThemeProvider attribute=\"class\" defaultTheme=\"dark\" enableSystem>\n        <Analytics />\n        <AuthProvider>\n          <ConversationProvider>\n            <body className={`${roboto.className} flex flex-col h-screen`}>\n              <Toaster position=\"top-right\" />\n              <Header />\n              <div className=\"flex flex-1 overflow-y-hidden\">\n                <Sidebar />\n                <main className=\"w-full h-full overflow-y-hidden\">\n                  {children}\n                </main>\n              </div>\n            </body>\n          </ConversationProvider>\n        </AuthProvider>\n      </ThemeProvider>\n    </html>\n  );\n}\n"
  },
  {
    "path": "frontend/app/markdown.css",
    "content": "/* Custom CSS for chat message markdown */\n.custom-markdown ul {\n  list-style-type: disc;\n  margin-left: 20px;\n}\n\n.custom-markdown ol {\n  list-style-type: decimal;\n  margin-left: 20px;\n}\n\n.custom-markdown li {\n  margin-bottom: 5px;\n}\n\n.custom-markdown ol ol {\n  list-style: lower-alpha;\n}\n\n.custom-markdown ul ul,\n.custom-markdown ol ol {\n  margin-left: 20px;\n}\n"
  },
  {
    "path": "frontend/app/page.tsx",
    "content": "// // page.tsx\n// 'use client';\n\n// import { Button } from '@/components/ui/button';\n// import Image from 'next/image';\n// import { useTheme } from 'next-themes';\n// import { PlaceholdersAndVanishInput } from '@/components/ui/placeholders-and-vanish-input';\n// import { Suspense, useState } from 'react';\n// import { useRouter } from 'next/navigation';\n// import Loading from '@/components/loading';\n// import { useAuth } from '@/app/authProvider';\n// import Ripple from '@/components/magicui/ripple';\n// import AnimatedGradientText from '@/components/magicui/animated-gradient-text';\n// import { cn } from '@/lib/utils';\n// import { ChevronRight } from 'lucide-react';\n// import HyperText from '@/components/magicui/hyper-text';\n// import GradualSpacing from '@/components/magicui/gradual-spacing';\n\n// function HomeContent() {\n//   const { theme, setTheme } = useTheme();\n//   const [inputValue, setInputValue] = useState('');\n//   const { isAuthenticated } = useAuth();\n//   const router = useRouter();\n\n//   const placeholders = [\n//     'Hello there how are you doing',\n//     'Tell me more about ...',\n//   ];\n\n//   const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n//     setInputValue(e.target.value);\n//   };\n\n//   const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n//     e.preventDefault();\n\n//     setTimeout(() => {\n//       if (isAuthenticated) {\n//         router.push(`/chat?query=${encodeURIComponent(inputValue)}`);\n//       } else {\n//         router.push(`/signin`);\n//       }\n//     }, 1500);\n//   };\n\n//   return (\n//     <div className=\"h-full flex flex-col justify-center items-center relative\">\n//       <Ripple />\n//       <div className=\"z-10 flex  items-center justify-center p-2\">\n//         <AnimatedGradientText>\n//           ⚡ <hr className=\"mx-2 h-4 w-[1px] shrink-0 bg-gray-300\" />{' '}\n//           <span\n//             className={cn(\n//               `inline animate-gradient bg-gradient-to-r from-[#ffaa40] via-[#9c40ff] to-[#ffaa40] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent`\n//             )}\n//           >\n//             Introducing RAG SAAS\n//           </span>\n//           <ChevronRight className=\"ml-1 size-3 transition-transform duration-300 ease-in-out group-hover:translate-x-0.5\" />\n//         </AnimatedGradientText>\n//       </div>\n//       <GradualSpacing\n//         className=\"text-2xl md:text-4xl font-bold text-black dark:text-white w-full \"\n//         text=\"Ship RAG Solutions Quickly\"\n//       />\n//       <div className=\"w-full md:w-[60%] p-4\">\n//         <PlaceholdersAndVanishInput\n//           placeholders={placeholders}\n//           onChange={handleChange}\n//           onSubmit={onSubmit}\n//           value={inputValue}\n//           setValue={setInputValue}\n//         />\n//       </div>\n//     </div>\n//   );\n// }\n\n// export default function Home() {\n//   return (\n//     <Suspense fallback={<Loading />}>\n//       <HomeContent />\n//     </Suspense>\n//   );\n// }\n\n// 'use client';\n\n// import { Button } from '@/components/ui/button';\n// import Image from 'next/image';\n// import { useTheme } from 'next-themes';\n// import { PlaceholdersAndVanishInput } from '@/components/ui/placeholders-and-vanish-input';\n// import { Suspense, useState } from 'react';\n// import { useRouter } from 'next/navigation';\n// import Loading from '@/components/loading';\n// import { useAuth } from '@/app/authProvider';\n// import Ripple from '@/components/magicui/ripple';\n// import AnimatedGradientText from '@/components/magicui/animated-gradient-text';\n// import { cn } from '@/lib/utils';\n// import { ChevronRight } from 'lucide-react';\n// import HyperText from '@/components/magicui/hyper-text';\n// import GradualSpacing from '@/components/magicui/gradual-spacing';\n\n// function HomeContent() {\n//   const { theme, setTheme } = useTheme();\n//   const [inputValue, setInputValue] = useState('');\n//   const { isAuthenticated } = useAuth();\n//   const router = useRouter();\n\n//   const placeholders = [\n//     'Hello there how are you doing',\n//     'Tell me more about ...',\n//   ];\n\n//   const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n//     setInputValue(e.target.value);\n//   };\n\n//   const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n//     e.preventDefault();\n\n//     setTimeout(() => {\n//       if (isAuthenticated) {\n//         router.push(`/chat?query=${encodeURIComponent(inputValue)}`);\n//       } else {\n//         router.push(`/signin`);\n//       }\n//     }, 1500);\n//   };\n\n//   return (\n//     <div className=\"h-full flex flex-col justify-center items-center relative\">\n//       <Ripple />\n//       <div className=\"z-10 flex items-center justify-center p-2 \">\n//         <AnimatedGradientText>\n//           ⚡ <hr className=\"mx-2 h-4 w-[1px] shrink-0 bg-gray-300\" />{' '}\n//           <span\n//             className={cn(\n//               `inline animate-gradient bg-gradient-to-r from-[#ffaa40] via-[#9c40ff] to-[#ffaa40] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent`\n//             )}\n//           >\n//             Ship RAG Solutions Quickly\n//           </span>\n//           <ChevronRight className=\"ml-1 size-3 transition-transform duration-300 ease-in-out group-hover:translate-x-0.5\" />\n//         </AnimatedGradientText>\n//       </div>\n//       <div className=\"relative w-full aspect-square max-w-[250px] h-fit\">\n//         <Image\n//           src={\n//             theme === 'dark'\n//               ? '/images/banner_dark.png'\n//               : '/images/banner_light.png'\n//           }\n//           alt=\"RAG SAAS Logo\"\n//           layout=\"fill\"\n//           objectFit=\"contain\"\n//           priority\n//         />\n//       </div>\n\n//       <div className=\"w-full md:w-[70%] p-4\">\n//         <PlaceholdersAndVanishInput\n//           placeholders={placeholders}\n//           onChange={handleChange}\n//           onSubmit={onSubmit}\n//           value={inputValue}\n//           setValue={setInputValue}\n//         />\n//       </div>\n//     </div>\n//   );\n// }\n\n// export default function Home() {\n//   return (\n//     <Suspense fallback={<Loading />}>\n//       <HomeContent />\n//     </Suspense>\n//   );\n// }\n\n'use client';\n\nimport React, { useState, useEffect } from 'react';\nimport { useTheme } from 'next-themes';\nimport { PlaceholdersAndVanishInput } from '@/components/ui/placeholders-and-vanish-input';\nimport { useRouter } from 'next/navigation';\nimport { useAuth } from '@/app/authProvider';\nimport Ripple from '@/components/magicui/ripple';\nimport AnimatedGradientText from '@/components/magicui/animated-gradient-text';\nimport { cn } from '@/lib/utils';\nimport { ChevronRight } from 'lucide-react';\nimport Image from 'next/image';\nimport { siteConfig } from '@/config/site';\nimport Link from 'next/link';\n\nfunction HomeContent() {\n  const { theme } = useTheme();\n  const [inputValue, setInputValue] = useState('');\n  const { isAuthenticated } = useAuth();\n  const router = useRouter();\n  const [isAnimating, setIsAnimating] = useState(false);\n\n  const placeholders = [\n    'Hello there how are you doing',\n    'Tell me more about ...',\n  ];\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setInputValue(e.target.value);\n  };\n\n  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    setIsAnimating(true);\n\n    setTimeout(() => {\n      if (isAuthenticated) {\n        router.push(`/chat?query=${encodeURIComponent(inputValue)}`);\n      } else {\n        router.push(`/signin`);\n      }\n    }, 1500);\n  };\n\n  return (\n    <div className=\"h-full flex flex-col justify-center items-center relative\">\n      <Ripple />\n      <Link\n        href={siteConfig.links.github}\n        target=\"_blank\"\n        rel=\"noopener noreferrer\"\n        className=\"w-full flex items-center justify-center\"\n      >\n        <div\n          className={`z-10 flex items-center justify-center p-2 transition-all duration-500 ${\n            isAnimating ? 'opacity-0 -translate-y-10' : ''\n          }`}\n        >\n          <AnimatedGradientText>\n            ⚡ <hr className=\"mx-2 h-4 w-[1px] shrink-0 bg-gray-300\" />{' '}\n            <span\n              className={cn(\n                `inline animate-gradient bg-gradient-to-r from-[#ffaa40] via-[#9c40ff] to-[#ffaa40] bg-[length:var(--bg-size)_100%] bg-clip-text text-transparent`\n              )}\n            >\n              Ship RAG Solutions Quickly\n            </span>\n            <ChevronRight className=\"ml-1 size-3 transition-transform duration-1300 ease-in-out group-hover:translate-x-0.5\" />\n          </AnimatedGradientText>\n        </div>\n      </Link>\n      <div\n        className={`relative w-full aspect-square max-w-[250px] h-fit transition-all duration-1500 ${\n          isAnimating ? 'opacity-0 -translate-y-10' : ''\n        }`}\n      >\n        <Image\n          src={\n            theme === 'dark'\n              ? '/images/banner_dark.png'\n              : '/images/banner_light.png'\n          }\n          alt=\"RAG SAAS Logo\"\n          layout=\"fill\"\n          objectFit=\"contain\"\n          priority\n        />\n      </div>\n\n      <div\n        className={`w-full md:w-[70%] p-4 transition-all duration-1500 ${\n          isAnimating ? 'md:translate-y-24 lg:md:translate-y-36' : ''\n        }`}\n      >\n        <PlaceholdersAndVanishInput\n          placeholders={placeholders}\n          onChange={handleChange}\n          onSubmit={onSubmit}\n          value={inputValue}\n          setValue={setInputValue}\n        />\n      </div>\n    </div>\n  );\n}\n\nexport default HomeContent;\n"
  },
  {
    "path": "frontend/app/share/page.tsx",
    "content": "/* eslint-disable react-hooks/exhaustive-deps */\n'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { useChat } from 'ai/react';\nimport { ChatInput, ChatMessages } from '@/components/ui/chat';\nimport { useClientConfig } from '@/components/ui/chat/hooks/use-config';\nimport { useRouter, useSearchParams } from 'next/navigation';\nimport { Suspense } from 'react';\nimport { useConversationContext } from '@/app/ConversationContext';\nimport { useAuth } from '@/app/authProvider';\nimport Loading from '@/components/loading';\nimport { toast } from 'sonner';\nimport axios from 'axios';\n\nfunction ChatContent() {\n  const { backend } = useClientConfig();\n  const { isAuthenticated, accessToken } = useAuth();\n  const router = useRouter();\n  const searchParams = useSearchParams();\n  const [conversationId, setConversationId] = useState<string | null>(null);\n  const { conversationList, setConversationList } = useConversationContext();\n  const [isClient, setIsClient] = useState(false);\n\n  useEffect(() => {\n    setIsClient(true);\n  }, []);\n\n  const axiosInstance = axios.create({\n    baseURL: backend,\n    headers: {\n      'Content-Type': 'application/json',\n    },\n  });\n\n  const {\n    messages,\n    input,\n    isLoading,\n    handleSubmit,\n    handleInputChange,\n    reload,\n    stop,\n    append,\n    setInput,\n    setMessages,\n  } = useChat({});\n\n  const fetchSharableMessages = useCallback(async () => {\n    if (!conversationId) return;\n    try {\n      const response = await axiosInstance.get(\n        `/api/conversation/sharable/${conversationId}`\n      );\n      setMessages(response.data.messages || []);\n    } catch (error: any) {\n      if (error.response && error.response.status === 404) {\n        toast('This conversation is not available or not sharable.');\n        // Optionally, redirect to a 404 page or clear the conversation\n        // router.push('/404');\n      } else {\n        toast(`Failed to fetch conversation: ${error.message}`);\n      }\n    }\n  }, [conversationId, axiosInstance, setMessages]);\n\n  const fetchConversations = useCallback(async () => {\n    if (!isAuthenticated) return;\n    try {\n      const response = await axiosInstance.get('/api/conversation/list');\n      setConversationList(response.data.conversations);\n    } catch (error: any) {\n      console.error('Error fetching conversations:', error.message);\n    }\n  }, [isAuthenticated, axiosInstance, setConversationList]);\n\n  useEffect(() => {\n    if (isAuthenticated) {\n      fetchConversations();\n    }\n  }, [isAuthenticated, fetchConversations, isLoading]);\n\n  useEffect(() => {\n    if (conversationId) {\n      fetchSharableMessages();\n    }\n  }, [conversationId, fetchSharableMessages]);\n\n  useEffect(() => {\n    const urlConversationId = searchParams.get('conversation_id');\n    setConversationId(urlConversationId);\n  }, [searchParams]);\n\n  return (\n    <div className=\"w-full h-full flex justify-center items-center bg-primary-foreground\">\n      <div className=\"space-y-2 w-full  md:w-[90%] lg:w-[70%] h-full flex flex-col p-4\">\n        <Suspense fallback={<Loading />}>\n          <ChatMessages messages={messages} isLoading={false} />\n        </Suspense>\n      </div>\n    </div>\n  );\n}\n\nexport default function Chat() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <ChatContent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/components/analytics.tsx",
    "content": "'use client';\n\nimport { Analytics as VercelAnalytics } from '@vercel/analytics/react';\n\nexport function Analytics() {\n  return <VercelAnalytics />;\n}\n"
  },
  {
    "path": "frontend/components/banner-card.tsx",
    "content": "// import React from 'react';\n// import { Github, Loader2 } from 'lucide-react';\n// import Image from 'next/image';\n// import Link from 'next/link';\n// import { Button, buttonVariants } from './ui/button';\n// import { cn } from '@/lib/utils';\n// import { siteConfig } from '@/config/site';\n// import { useTheme } from 'next-themes';\n// import ShinyButton from './magicui/shiny-button';\n\n// const BannerCard: React.FC = () => {\n//   const { theme, setTheme } = useTheme();\n//   return (\n//     <div className=\"relative h-fit md:1/2 lg:w-2/5 overflow-hidden rounded-2xl border-2 border-slate-500/10\">\n//       <div className=\"relative z-10  p-14 bg-background backdrop-blur-sm flex flex-col justify-center items-center gap-6\">\n//         <Image\n//           src={\n//             theme === 'dark'\n//               ? '/images/banner_dark.png'\n//               : '/images/banner_light.png'\n//           }\n//           alt=\"Image\"\n//           width=\"1080\"\n//           height=\"1080\"\n//           className=\"object-contain px-16\"\n//         />\n//         <h3 className=\"text-lg font-semibold w-full text-center\">\n//           Ship RAG Solutions ⚡Quickly\n//         </h3>\n//         <Link\n//           href={siteConfig.links.github}\n//           target=\"_blank\"\n//           className=\"w-full flex items-center justify-center\"\n//         >\n//           <ShinyButton text=\"⭐ STAR US ON GITHUB \" className=\"\" />\n//         </Link>\n//       </div>\n//     </div>\n//   );\n// };\n\n// export default BannerCard;\n\nimport React from 'react';\nimport { Github, Zap } from 'lucide-react';\nimport Image from 'next/image';\nimport Link from 'next/link';\nimport { Button } from '@/components/ui/button';\nimport { useTheme } from 'next-themes';\nimport { motion } from 'framer-motion';\nimport ShinyButton from './magicui/shiny-button';\nimport { siteConfig } from '@/config/site';\nimport HyperText from './magicui/hyper-text';\n\nconst BannerCard: React.FC = () => {\n  const { theme, setTheme } = useTheme();\n\n  return (\n    <motion.div\n      className=\"relative overflow-hidden rounded-2xl border-2 border-primary/10 bg-card text-card-foreground shadow-sm\"\n      initial={{ opacity: 0, y: 20 }}\n      animate={{ opacity: 1, y: 0 }}\n      transition={{ duration: 0.5 }}\n    >\n      <div className=\"relative z-10 p-6 sm:p-6 flex flex-col justify-center items-center gap-4\">\n        <div className=\"relative w-full aspect-square max-w-[180px]\">\n          <Image\n            src={\n              theme === 'dark'\n                ? '/images/banner_dark.png'\n                : '/images/banner_light.png'\n            }\n            alt=\"RAG SAAS Logo\"\n            layout=\"fill\"\n            objectFit=\"contain\"\n            priority\n          />\n        </div>\n        <h3 className=\"text-2xl font-bold text-center\">\n          Ship RAG Solutions{' '}\n          <Zap className=\"inline-block w-6 h-6 text-yellow-400\" /> Quickly\n        </h3>\n\n        <Link\n          href={siteConfig.links.github}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n          className=\"w-full flex items-center justify-center\"\n        >\n          <ShinyButton text=\"⭐ STAR US ON GITHUB \" className=\"\" />\n        </Link>\n      </div>\n      <div\n        className=\"absolute inset-0 bg-gradient-to-br from-primary/5 to-secondary/5\"\n        style={{\n          maskImage:\n            'radial-gradient(circle at center, transparent 0%, black 80%)',\n          WebkitMaskImage:\n            'radial-gradient(circle at center, transparent 0%, black 80%)',\n        }}\n      />\n    </motion.div>\n  );\n};\n\nexport default BannerCard;\n"
  },
  {
    "path": "frontend/components/header.tsx",
    "content": "'use client';\n\nimport { useState } from 'react';\nimport Link from 'next/link';\nimport Image from 'next/image';\nimport { useTheme } from 'next-themes';\nimport { useAuth } from '@/app/authProvider';\nimport { useConversationContext } from '@/app/ConversationContext';\nimport { cn } from '@/lib/utils';\nimport { Button, buttonVariants } from '@/components/ui/button';\nimport ShinyButton from '@/components/magicui/shiny-button';\n\nimport { Github, Menu, X, PanelLeft } from 'lucide-react';\nimport { Separator } from './ui/separator';\nimport { siteConfig } from '@/config/site';\n\ninterface MobileNavigationProps {\n  isOpen: boolean;\n  onClose: () => void;\n}\n\ninterface AuthContextType {\n  isAuthenticated: boolean;\n  logout: () => void;\n}\n\nexport function MobileNavigation({\n  isOpen,\n  onClose,\n}: MobileNavigationProps): JSX.Element | null {\n  const { isAuthenticated, logout } = useAuth();\n\n  const handleLogout = () => {\n    logout();\n    onClose();\n  };\n\n  if (!isOpen) return null;\n\n  return (\n    <div className=\"fixed inset-0 z-50 mt-14\">\n      <div\n        className=\"absolute inset-0 bg-background/80 backdrop-blur-10\"\n        onClick={onClose}\n      />\n      <div className=\"absolute inset-x-0 top-0 bg-background border-t px-4 shadow-lg\">\n        <div className=\"mt-4 space-y-4\">\n          <Button variant=\"outline\" asChild className=\"w-full justify-start\">\n            <Link href=\"/features\">Features</Link>\n          </Button>\n          {isAuthenticated ? (\n            <Button\n              variant=\"outline\"\n              onClick={handleLogout}\n              className=\"w-full justify-start\"\n            >\n              Logout\n            </Button>\n          ) : (\n            <Button variant=\"ghost\" asChild className=\"w-full justify-start\">\n              <Link href=\"/signin\">Sign In</Link>\n            </Button>\n          )}\n          <Separator />\n          <Link\n            href={siteConfig.links.github}\n            target=\"_blank\"\n            className=\"w-full\"\n          >\n            <ShinyButton\n              text=\"⭐ STAR US ON GITHUB \"\n              className=\"w-full my-4 py-2\"\n            />\n          </Link>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport function Header() {\n  const { theme } = useTheme();\n  const [isMenuOpen, setIsMenuOpen] = useState(false);\n  const { isAuthenticated, logout, firstName } = useAuth();\n  const { isSidebarOpen, setIsSidebarOpen } = useConversationContext();\n\n  const toggleSidebar = () => {\n    setIsSidebarOpen(!isSidebarOpen);\n  };\n\n  const handleLogout = () => {\n    logout();\n    setIsMenuOpen(false);\n  };\n\n  return (\n    <>\n      <header className=\"sticky top-0 z-50 w-full border-b bg-background backdrop-blur\">\n        <div className=\"px-4 flex h-14 items-center justify-between\">\n          <div className=\"flex items-center\">\n            <Button\n              variant=\"ghost\"\n              size=\"icon\"\n              className=\"bg-muted\"\n              onClick={toggleSidebar}\n            >\n              <PanelLeft className=\"h-5 w-5\" />\n              <span className=\"sr-only\">Toggle sidebar</span>\n            </Button>\n            {/* {isAuthenticated && (\n            <Button\n              variant=\"ghost\"\n              size=\"icon\"\n              className=\"bg-muted\"\n              onClick={toggleSidebar}\n            >\n              <PanelLeft className=\"h-5 w-5\" />\n              <span className=\"sr-only\">Toggle sidebar</span>\n            </Button>\n          )} */}\n            <Link href=\"/\" className=\"flex items-center\">\n              <Image\n                src={\n                  theme == 'dark'\n                    ? '/images/logo_light.png'\n                    : '/images/logo_dark.png'\n                }\n                alt=\"RAG SAAS Logo\"\n                width={200}\n                height={70}\n              />\n            </Link>\n          </div>\n          <nav className=\"hidden md:flex items-center space-x-4\">\n            <Button variant=\"link\" asChild>\n              <Link href=\"/features\">Features</Link>\n            </Button>\n            <a\n              href=\"https://github.com/adithya-s-k/RAG-SaaS\"\n              target=\"_blank\"\n              rel=\"noopener noreferrer\"\n            >\n              <ShinyButton text=\"Github ⭐\" className=\"\" />\n            </a>\n            {isAuthenticated ? (\n              <Button variant=\"outline\" onClick={handleLogout}>\n                Logout\n              </Button>\n            ) : (\n              <Button variant=\"outline\" asChild>\n                <Link href=\"/signin\">Sign In</Link>\n              </Button>\n            )}\n          </nav>\n          <button\n            className=\"inline-flex items-center justify-center rounded-md p-2 text-foreground hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary md:hidden\"\n            onClick={() => setIsMenuOpen(!isMenuOpen)}\n          >\n            <span className=\"sr-only\">Toggle menu</span>\n            {isMenuOpen ? (\n              <X className=\"h-6 w-6\" aria-hidden=\"true\" />\n            ) : (\n              <Menu className=\"h-6 w-6\" aria-hidden=\"true\" />\n            )}\n          </button>\n        </div>\n      </header>\n      <MobileNavigation\n        isOpen={isMenuOpen}\n        onClose={() => setIsMenuOpen(false)}\n      />\n    </>\n  );\n}\n"
  },
  {
    "path": "frontend/components/history.tsx",
    "content": "'use client';\n\nimport React, { useState, useEffect, Suspense } from 'react';\nimport { useRouter, useSearchParams } from 'next/navigation';\nimport {\n  Github,\n  LinkIcon,\n  MessageCircle,\n  MessageSquare,\n  MoreHorizontal,\n  Plus,\n} from 'lucide-react';\nimport { useConversationContext } from '@/app/ConversationContext';\nimport { useAuth } from '@/app/authProvider';\nimport { Button } from '@/components/ui/button';\nimport { Card, CardContent } from '@/components/ui/card';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  DialogTrigger,\n} from '@/components/ui/dialog';\nimport { Input } from '@/components/ui/input';\nimport { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';\nimport { ThemeToggle } from './theme-toggle';\nimport { toast } from 'sonner';\nimport axios from 'axios';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport Loading from './loading';\nimport Link from 'next/link';\n\ninterface Conversation {\n  _id: string;\n  summary: string;\n  created_at?: string;\n  updated_at?: string;\n}\n\nconst MAX_SUMMARY_LENGTH = 27;\n\nfunction HistoryComponent() {\n  const { isAuthenticated, firstName, lastName, email, axiosInstance } =\n    useAuth();\n  const router = useRouter();\n  const searchParams = useSearchParams();\n  const { conversationList, setConversationList } = useConversationContext();\n  const [isEditing, setIsEditing] = useState<string | null>(null);\n\n  const [isShareModalOpen, setIsShareModalOpen] = useState<boolean>(false);\n  const [shareableLink, setShareableLink] = useState<string>('');\n  const [editedSummaries, setEditedSummaries] = useState<{\n    [key: string]: string;\n  }>({});\n\n  const fetchConversations = async () => {\n    if (!isAuthenticated) return;\n    try {\n      const response = await axiosInstance.get('/api/conversation/list');\n      setConversationList(response.data.conversations);\n    } catch (error: any) {\n      toast(`Failed to fetch conversations: ${error.message}`);\n    }\n  };\n\n  const handleEditClick = (conversationId: string, currentSummary: string) => {\n    if (!isAuthenticated) return;\n    setIsEditing(conversationId);\n    setEditedSummaries((prev) => ({\n      ...prev,\n      [conversationId]: currentSummary,\n    }));\n  };\n\n  const handleEditSubmit = async (conversationId: string) => {\n    if (!isAuthenticated) return;\n    try {\n      await axiosInstance.patch(`/api/conversation/${conversationId}/summary`, {\n        summary: editedSummaries[conversationId],\n      });\n      await fetchConversations();\n      setIsEditing(null);\n    } catch (error: any) {\n      toast(`Failed to update summary: ${error.message}`);\n    }\n  };\n\n  const handleShareClick = async (conversationId: string) => {\n    try {\n      const response = await axiosInstance.patch(\n        `/api/conversation/${conversationId}/share`\n      );\n\n      if (response.status === 200) {\n        const shareableLink = `${window.location.origin}/share?conversation_id=${conversationId}`;\n        setShareableLink(shareableLink);\n        setIsShareModalOpen(true);\n      }\n    } catch (error: any) {\n      toast(`Failed to share conversation: ${error.message}`);\n    }\n  };\n\n  const copyToClipboard = () => {\n    navigator.clipboard.writeText(shareableLink);\n    toast('Link copied to clipboard!');\n  };\n\n  const handleDeleteClick = async (conversationId: string): Promise<void> => {\n    if (!isAuthenticated) return;\n    const confirmed = window.confirm(\n      'Are you sure you want to delete this conversation?'\n    );\n    if (!confirmed) return;\n    try {\n      await axiosInstance.delete(`/api/conversation/${conversationId}`);\n\n      const currentConversationId = searchParams.get('conversation_id');\n\n      if (currentConversationId === conversationId) {\n        router.push('/chat');\n      } else {\n        router.push(`/chat?conversation_id=${currentConversationId}`);\n      }\n\n      await fetchConversations();\n    } catch (error) {\n      if (axios.isAxiosError(error)) {\n        toast(`Failed to delete conversation: ${error.message}`);\n      } else {\n        toast('An unexpected error occurred while deleting the conversation');\n      }\n    }\n  };\n\n  const handleNewChat = async () => {\n    if (!isAuthenticated) return;\n    try {\n      const response = await axiosInstance.get('/api/conversation');\n      const newConversationId = response.data.conversation_id;\n      fetchConversations();\n      router.push(`/chat?conversation_id=${newConversationId}`);\n    } catch (error: any) {\n      toast(`Failed to create new chat: ${error.message}`);\n    }\n  };\n\n  useEffect(() => {\n    if (isAuthenticated) {\n      fetchConversations();\n    }\n  }, [isAuthenticated]);\n\n  if (!isAuthenticated) {\n    return (\n      <div className=\"flex flex-col h-full bg-background text-foreground text-sm\">\n        <Button\n          variant=\"ghost\"\n          onClick={handleNewChat}\n          className=\"m-3 py-2 rounded-md font-semibold text-base border-2\"\n        >\n          <Plus className=\"mr-2 h-5 w-5\" /> New Chat\n        </Button>\n        <div className=\"flex-grow flex items-center justify-center\">\n          <p className=\"text-center text-muted-foreground\">\n            Sign in to see your chat history\n          </p>\n        </div>\n        <div className=\"p-3 border-t flex items-center justify-between\">\n          <div className=\"flex items-center space-x-3\">\n            <Button variant=\"secondary\" asChild>\n              <Link href=\"/signin\">Sign In</Link>\n            </Button>\n          </div>\n          <div className=\"flex items-center space-x-3\">\n            <ThemeToggle />\n          </div>\n        </div>\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"flex flex-col h-full bg-background text-foreground text-sm \">\n      <Dialog open={isShareModalOpen} onOpenChange={setIsShareModalOpen}>\n        <DialogContent>\n          <DialogHeader>\n            <DialogTitle>Share Conversation</DialogTitle>\n            <DialogDescription>\n              Copy the link below to share this conversation:\n            </DialogDescription>\n          </DialogHeader>\n          <div className=\"flex items-center space-x-2\">\n            <Input value={shareableLink} readOnly />\n            <Button onClick={copyToClipboard}>\n              <LinkIcon className=\"mr-2 h-4 w-4\" />\n              Copy\n            </Button>\n          </div>\n        </DialogContent>\n      </Dialog>\n      <Button\n        variant=\"ghost\"\n        onClick={handleNewChat}\n        className=\"m-3 py-2 rounded-md font-semibold text-base border-2\"\n      >\n        <Plus className=\"mr-2 h-5 w-5\" /> New Chat\n      </Button>\n      <div className=\"flex-1 overflow-hidden\">\n        <ScrollArea className=\"h-full px-2\">\n          {/* {Object.entries(conversationList).map(\n            ([dateCategory, conversations]) =>\n              conversations.length > 0 ? (\n                <div key={dateCategory} className=\"mb-3\">\n                  <h3 className=\"text-sm font-bold my-2 capitalize text-muted-foreground\">\n                    {dateCategory.replace(/_/g, ' ')}\n                  </h3>\n                  {conversations\n                    .sort(\n                      (a: { updated_at: any }, b: { updated_at: any }) =>\n                        new Date(b.updated_at || '').getTime() -\n                        new Date(a.updated_at || '').getTime()\n                    )\n                    .map((conversation: Conversation) => (\n                      <div\n                        key={conversation._id}\n                        className=\"flex items-center justify-between px-2 py-1 hover:bg-accent rounded-md cursor-pointer\"\n                      >\n                        <div\n                          className=\"flex items-center space-x-3 overflow-hidden\"\n                          onClick={() =>\n                            router.push(\n                              `/chat?conversation_id=${conversation._id}`\n                            )\n                          }\n                        >\n                          <MessageSquare className=\"h-5 w-5 text-muted-foreground flex-shrink-0\" />\n                          {isEditing === conversation._id ? (\n                            <Input\n                              value={editedSummaries[conversation._id]}\n                              onChange={(e) =>\n                                setEditedSummaries((prev) => ({\n                                  ...prev,\n                                  [conversation._id]: e.target.value,\n                                }))\n                              }\n                              onBlur={() => handleEditSubmit(conversation._id)}\n                              onKeyDown={(e) => {\n                                if (e.key === 'Enter') {\n                                  handleEditSubmit(conversation._id);\n                                }\n                              }}\n                              className=\"h-full text-md w-full focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0\"\n                              placeholder=\"Edited Summary\"\n                              onClick={(e) => e.stopPropagation()}\n                            />\n                          ) : (\n                            <span className=\"truncate text-base\">\n                              {conversation.summary.length > MAX_SUMMARY_LENGTH\n                                ? `${conversation.summary.substring(\n                                    0,\n                                    MAX_SUMMARY_LENGTH\n                                  )}...`\n                                : conversation.summary}\n                            </span>\n                          )}\n                        </div>\n                        <DropdownMenu>\n                          <DropdownMenuTrigger\n                            asChild\n                            onClick={(e) => e.stopPropagation()}\n                          >\n                            <Button variant=\"ghost\" className=\"h-8 w-8 p-0\">\n                              <MoreHorizontal className=\"h-4 w-4\" />\n                            </Button>\n                          </DropdownMenuTrigger>\n                          <DropdownMenuContent align=\"end\" className=\"w-36\">\n                            <DropdownMenuItem\n                              onClick={() => setIsEditing(conversation._id)}\n                            >\n                              Edit\n                            </DropdownMenuItem>\n                            <DropdownMenuItem\n                              onClick={() => handleShareClick(conversation._id)}\n                            >\n                              Share\n                            </DropdownMenuItem>\n                            <DropdownMenuItem\n                              onClick={() =>\n                                handleDeleteClick(conversation._id)\n                              }\n                            >\n                              Delete\n                            </DropdownMenuItem>\n                          </DropdownMenuContent>\n                        </DropdownMenu>\n                      </div>\n                    ))}\n                </div>\n              ) : null\n          )} */}\n          {Object.entries(conversationList).map(\n            ([dateCategory, conversations]) =>\n              conversations.length > 0 ? (\n                <div key={dateCategory} className=\"mb-3\">\n                  <h3 className=\"text-sm font-bold my-2 capitalize text-muted-foreground\">\n                    {dateCategory.replace(/_/g, ' ')}\n                  </h3>\n                  {conversations\n                    .sort(\n                      (a: { updated_at: any }, b: { updated_at: any }) =>\n                        new Date(b.updated_at || '').getTime() -\n                        new Date(a.updated_at || '').getTime()\n                    )\n                    .map((conversation: Conversation) => (\n                      <div\n                        key={conversation._id}\n                        className=\"flex items-center justify-between px-2 py-1 hover:bg-accent rounded-md\"\n                      >\n                        <div\n                          className=\"flex items-center space-x-3 overflow-hidden flex-grow cursor-pointer\"\n                          onClick={() =>\n                            router.push(\n                              `/chat?conversation_id=${conversation._id}`\n                            )\n                          }\n                        >\n                          <MessageSquare className=\"h-5 w-5 text-muted-foreground flex-shrink-0\" />\n                          {isEditing === conversation._id ? (\n                            <Input\n                              value={editedSummaries[conversation._id]}\n                              onChange={(e) =>\n                                setEditedSummaries((prev) => ({\n                                  ...prev,\n                                  [conversation._id]: e.target.value,\n                                }))\n                              }\n                              onBlur={() => handleEditSubmit(conversation._id)}\n                              onKeyDown={(e) => {\n                                if (e.key === 'Enter') {\n                                  handleEditSubmit(conversation._id);\n                                }\n                              }}\n                              className=\"h-full text-md w-full focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0\"\n                              placeholder=\"Edited Summary\"\n                              onClick={(e) => e.stopPropagation()}\n                            />\n                          ) : (\n                            <span className=\"truncate text-base\">\n                              {conversation.summary.length > MAX_SUMMARY_LENGTH\n                                ? `${conversation.summary.substring(\n                                    0,\n                                    MAX_SUMMARY_LENGTH\n                                  )}...`\n                                : conversation.summary}\n                            </span>\n                          )}\n                        </div>\n                        <DropdownMenu>\n                          <DropdownMenuTrigger asChild>\n                            <Button\n                              variant=\"ghost\"\n                              className=\"h-8 w-8 p-0 ml-2 hover:bg-accent-foreground hover:text-accent\"\n                            >\n                              <MoreHorizontal className=\"h-4 w-4\" />\n                            </Button>\n                          </DropdownMenuTrigger>\n                          <DropdownMenuContent align=\"end\" className=\"w-36\">\n                            <DropdownMenuItem\n                              onClick={() => setIsEditing(conversation._id)}\n                            >\n                              Edit\n                            </DropdownMenuItem>\n                            <DropdownMenuItem\n                              onClick={() => handleShareClick(conversation._id)}\n                            >\n                              Share\n                            </DropdownMenuItem>\n                            <DropdownMenuItem\n                              onClick={() =>\n                                handleDeleteClick(conversation._id)\n                              }\n                            >\n                              Delete\n                            </DropdownMenuItem>\n                          </DropdownMenuContent>\n                        </DropdownMenu>\n                      </div>\n                    ))}\n                </div>\n              ) : null\n          )}\n        </ScrollArea>\n      </div>\n      <div className=\"p-3 border-t flex items-center justify-between\">\n        <div className=\"flex items-center space-x-3\">\n          <Avatar className=\"h-8 w-8\">\n            <AvatarFallback className=\"text-sm\">\n              {firstName?.[0]}\n              {lastName?.[0]}\n            </AvatarFallback>\n          </Avatar>\n          <div className=\"text-sm\">\n            <p className=\"font-medium\">\n              {firstName} {lastName}\n            </p>\n            <p className=\"text-muted-foreground\">{email}</p>\n          </div>\n        </div>\n        <div className=\"flex items-center space-x-3\">\n          <ThemeToggle />\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default function History() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <HistoryComponent />\n    </Suspense>\n  );\n}\n"
  },
  {
    "path": "frontend/components/loading.tsx",
    "content": "import React from 'react';\nimport { Loader2 } from 'lucide-react';\n\nconst Loading: React.FC = () => {\n  return (\n    <div className=\"fixed inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm z-50\">\n      <div className=\"p-4 rounded-md shadow-md flex items-center space-x-2\">\n        <Loader2 className=\"h-5 w-5 animate-spin text-foreground\" />\n        <span className=\"text-sm font-medium text-foreground\">Loading</span>\n      </div>\n    </div>\n  );\n};\n\nexport default Loading;\n"
  },
  {
    "path": "frontend/components/magicui/animated-gradient-text.tsx",
    "content": "import { ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport default function AnimatedGradientText({\n  children,\n  className,\n}: {\n  children: ReactNode;\n  className?: string;\n}) {\n  return (\n    <div\n      className={cn(\n        \"group relative mx-auto flex max-w-fit flex-row items-center justify-center rounded-2xl bg-white/40 px-4 py-1.5 text-sm font-medium shadow-[inset_0_-8px_10px_#8fdfff1f] backdrop-blur-sm transition-shadow duration-500 ease-out [--bg-size:300%] hover:shadow-[inset_0_-5px_10px_#8fdfff3f] dark:bg-black/40\",\n        className,\n      )}\n    >\n      <div\n        className={`absolute inset-0 block h-full w-full animate-gradient bg-gradient-to-r from-[#ffaa40]/50 via-[#9c40ff]/50 to-[#ffaa40]/50 bg-[length:var(--bg-size)_100%] p-[1px] ![mask-composite:subtract] [border-radius:inherit] [mask:linear-gradient(#fff_0_0)_content-box,linear-gradient(#fff_0_0)]`}\n      />\n\n      {children}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/magicui/border-beam.tsx",
    "content": "import { cn } from \"@/lib/utils\";\n\ninterface BorderBeamProps {\n  className?: string;\n  size?: number;\n  duration?: number;\n  borderWidth?: number;\n  anchor?: number;\n  colorFrom?: string;\n  colorTo?: string;\n  delay?: number;\n}\n\nexport const BorderBeam = ({\n  className,\n  size = 200,\n  duration = 15,\n  anchor = 90,\n  borderWidth = 1.5,\n  colorFrom = \"#ffaa40\",\n  colorTo = \"#9c40ff\",\n  delay = 0,\n}: BorderBeamProps) => {\n  return (\n    <div\n      style={\n        {\n          \"--size\": size,\n          \"--duration\": duration,\n          \"--anchor\": anchor,\n          \"--border-width\": borderWidth,\n          \"--color-from\": colorFrom,\n          \"--color-to\": colorTo,\n          \"--delay\": `-${delay}s`,\n        } as React.CSSProperties\n      }\n      className={cn(\n        \"pointer-events-none absolute inset-0 rounded-[inherit] [border:calc(var(--border-width)*1px)_solid_transparent]\",\n\n        // mask styles\n        \"![mask-clip:padding-box,border-box] ![mask-composite:intersect] [mask:linear-gradient(transparent,transparent),linear-gradient(white,white)]\",\n\n        // pseudo styles\n        \"after:absolute after:aspect-square after:w-[calc(var(--size)*1px)] after:animate-border-beam after:[animation-delay:var(--delay)] after:[background:linear-gradient(to_left,var(--color-from),var(--color-to),transparent)] after:[offset-anchor:calc(var(--anchor)*1%)_50%] after:[offset-path:rect(0_auto_auto_0_round_calc(var(--size)*1px))]\",\n        className,\n      )}\n    />\n  );\n};\n"
  },
  {
    "path": "frontend/components/magicui/box-reveal.tsx",
    "content": "\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { motion, useAnimation, useInView } from \"framer-motion\";\n\ninterface BoxRevealProps {\n  children: JSX.Element;\n  width?: \"fit-content\" | \"100%\";\n  boxColor?: string;\n  duration?: number;\n}\n\nexport const BoxReveal = ({\n  children,\n  width = \"fit-content\",\n  boxColor,\n  duration,\n}: BoxRevealProps) => {\n  const mainControls = useAnimation();\n  const slideControls = useAnimation();\n\n  const ref = useRef(null);\n  const isInView = useInView(ref, { once: true });\n\n  useEffect(() => {\n    if (isInView) {\n      slideControls.start(\"visible\");\n      mainControls.start(\"visible\");\n    } else {\n      slideControls.start(\"hidden\");\n      mainControls.start(\"hidden\");\n    }\n  }, [isInView, mainControls, slideControls]);\n\n  return (\n    <div ref={ref} style={{ position: \"relative\", width, overflow: \"hidden\" }}>\n      <motion.div\n        variants={{\n          hidden: { opacity: 0, y: 75 },\n          visible: { opacity: 1, y: 0 },\n        }}\n        initial=\"hidden\"\n        animate={mainControls}\n        transition={{ duration: duration ? duration : 0.5, delay: 0.25 }}\n      >\n        {children}\n      </motion.div>\n\n      <motion.div\n        variants={{\n          hidden: { left: 0 },\n          visible: { left: \"100%\" },\n        }}\n        initial=\"hidden\"\n        animate={slideControls}\n        transition={{ duration: duration ? duration : 0.5, ease: \"easeIn\" }}\n        style={{\n          position: \"absolute\",\n          top: 4,\n          bottom: 4,\n          left: 0,\n          right: 0,\n          zIndex: 20,\n          background: boxColor ? boxColor : \"#5046e6\",\n        }}\n      />\n    </div>\n  );\n};\n\nexport default BoxReveal;\n"
  },
  {
    "path": "frontend/components/magicui/gradual-spacing.tsx",
    "content": "\"use client\";\n\nimport { AnimatePresence, motion, Variants } from \"framer-motion\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface GradualSpacingProps {\n  text: string;\n  duration?: number;\n  delayMultiple?: number;\n  framerProps?: Variants;\n  className?: string;\n}\n\nexport default function GradualSpacing({\n  text,\n  duration = 0.5,\n  delayMultiple = 0.04,\n  framerProps = {\n    hidden: { opacity: 0, x: -20 },\n    visible: { opacity: 1, x: 0 },\n  },\n  className,\n}: GradualSpacingProps) {\n  return (\n    <div className=\"flex justify-center space-x-1\">\n      <AnimatePresence>\n        {text.split(\"\").map((char, i) => (\n          <motion.h1\n            key={i}\n            initial=\"hidden\"\n            animate=\"visible\"\n            exit=\"hidden\"\n            variants={framerProps}\n            transition={{ duration, delay: i * delayMultiple }}\n            className={cn(\"drop-shadow-sm \", className)}\n          >\n            {char === \" \" ? <span>&nbsp;</span> : char}\n          </motion.h1>\n        ))}\n      </AnimatePresence>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/magicui/hyper-text.tsx",
    "content": "\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion, Variants } from \"framer-motion\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface HyperTextProps {\n  text: string;\n  duration?: number;\n  framerProps?: Variants;\n  className?: string;\n  animateOnLoad?: boolean;\n}\n\nconst alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\");\n\nconst getRandomInt = (max: number) => Math.floor(Math.random() * max);\n\nexport default function HyperText({\n  text,\n  duration = 800,\n  framerProps = {\n    initial: { opacity: 0, y: -10 },\n    animate: { opacity: 1, y: 0 },\n    exit: { opacity: 0, y: 3 },\n  },\n  className,\n  animateOnLoad = true,\n}: HyperTextProps) {\n  const [displayText, setDisplayText] = useState(text.split(\"\"));\n  const [trigger, setTrigger] = useState(false);\n  const interations = useRef(0);\n  const isFirstRender = useRef(true);\n\n  const triggerAnimation = () => {\n    interations.current = 0;\n    setTrigger(true);\n  };\n\n  useEffect(() => {\n    const interval = setInterval(\n      () => {\n        if (!animateOnLoad && isFirstRender.current) {\n          clearInterval(interval);\n          isFirstRender.current = false;\n          return;\n        }\n        if (interations.current < text.length) {\n          setDisplayText((t) =>\n            t.map((l, i) =>\n              l === \" \"\n                ? l\n                : i <= interations.current\n                  ? text[i]\n                  : alphabets[getRandomInt(26)],\n            ),\n          );\n          interations.current = interations.current + 0.1;\n        } else {\n          setTrigger(false);\n          clearInterval(interval);\n        }\n      },\n      duration / (text.length * 10),\n    );\n    // Clean up interval on unmount\n    return () => clearInterval(interval);\n  }, [text, duration, trigger, animateOnLoad]);\n\n  return (\n    <div\n      className=\"overflow-hidden py-2 flex cursor-default scale-100\"\n      onMouseEnter={triggerAnimation}\n    >\n      <AnimatePresence mode=\"wait\">\n        {displayText.map((letter, i) => (\n          <motion.h1\n            key={i}\n            className={cn(\"font-mono\", letter === \" \" ? \"w-3\" : \"\", className)}\n            {...framerProps}\n          >\n            {letter.toUpperCase()}\n          </motion.h1>\n        ))}\n      </AnimatePresence>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/magicui/meteors.tsx",
    "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface MeteorsProps {\n  number?: number;\n}\nexport const Meteors = ({ number = 20 }: MeteorsProps) => {\n  const [meteorStyles, setMeteorStyles] = useState<Array<React.CSSProperties>>(\n    [],\n  );\n\n  useEffect(() => {\n    const styles = [...new Array(number)].map(() => ({\n      top: -5,\n      left: Math.floor(Math.random() * window.innerWidth) + \"px\",\n      animationDelay: Math.random() * 1 + 0.2 + \"s\",\n      animationDuration: Math.floor(Math.random() * 8 + 2) + \"s\",\n    }));\n    setMeteorStyles(styles);\n  }, [number]);\n\n  return (\n    <>\n      {[...meteorStyles].map((style, idx) => (\n        // Meteor Head\n        <span\n          key={idx}\n          className={cn(\n            \"pointer-events-none absolute left-1/2 top-1/2 size-0.5 rotate-[215deg] animate-meteor rounded-full bg-slate-500 shadow-[0_0_0_1px_#ffffff10]\",\n          )}\n          style={style}\n        >\n          {/* Meteor Tail */}\n          <div className=\"pointer-events-none absolute top-1/2 -z-10 h-px w-[50px] -translate-y-1/2 bg-gradient-to-r from-slate-500 to-transparent\" />\n        </span>\n      ))}\n    </>\n  );\n};\n\nexport default Meteors;\n"
  },
  {
    "path": "frontend/components/magicui/neon-gradient-card.tsx",
    "content": "\"use client\";\n\nimport {\n  CSSProperties,\n  ReactElement,\n  ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface NeonColorsProps {\n  firstColor: string;\n  secondColor: string;\n}\n\ninterface NeonGradientCardProps {\n  /**\n   * @default <div />\n   * @type ReactElement\n   * @description\n   * The component to be rendered as the card\n   * */\n  as?: ReactElement;\n  /**\n   * @default \"\"\n   * @type string\n   * @description\n   * The className of the card\n   */\n  className?: string;\n\n  /**\n   * @default \"\"\n   * @type ReactNode\n   * @description\n   * The children of the card\n   * */\n  children?: ReactNode;\n\n  /**\n   * @default 5\n   * @type number\n   * @description\n   * The size of the border in pixels\n   * */\n  borderSize?: number;\n\n  /**\n   * @default 20\n   * @type number\n   * @description\n   * The size of the radius in pixels\n   * */\n  borderRadius?: number;\n\n  /**\n   * @default \"{ firstColor: '#ff00aa', secondColor: '#00FFF1' }\"\n   * @type string\n   * @description\n   * The colors of the neon gradient\n   * */\n  neonColors?: NeonColorsProps;\n\n  [key: string]: any;\n}\n\nconst NeonGradientCard: React.FC<NeonGradientCardProps> = ({\n  className,\n  children,\n  borderSize = 2,\n  borderRadius = 20,\n  neonColors = {\n    firstColor: \"#ff00aa\",\n    secondColor: \"#00FFF1\",\n  },\n  ...props\n}) => {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });\n\n  useEffect(() => {\n    const updateDimensions = () => {\n      if (containerRef.current) {\n        const { offsetWidth, offsetHeight } = containerRef.current;\n        setDimensions({ width: offsetWidth, height: offsetHeight });\n      }\n    };\n\n    updateDimensions();\n    window.addEventListener(\"resize\", updateDimensions);\n\n    return () => {\n      window.removeEventListener(\"resize\", updateDimensions);\n    };\n  }, []);\n\n  useEffect(() => {\n    if (containerRef.current) {\n      const { offsetWidth, offsetHeight } = containerRef.current;\n      setDimensions({ width: offsetWidth, height: offsetHeight });\n    }\n  }, [children]);\n\n  return (\n    <div\n      ref={containerRef}\n      style={\n        {\n          \"--border-size\": `${borderSize}px`,\n          \"--border-radius\": `${borderRadius}px`,\n          \"--neon-first-color\": neonColors.firstColor,\n          \"--neon-second-color\": neonColors.secondColor,\n          \"--card-width\": `${dimensions.width}px`,\n          \"--card-height\": `${dimensions.height}px`,\n          \"--card-content-radius\": `${borderRadius - borderSize}px`,\n          \"--pseudo-element-background-image\": `linear-gradient(0deg, ${neonColors.firstColor}, ${neonColors.secondColor})`,\n          \"--pseudo-element-width\": `${dimensions.width + borderSize * 2}px`,\n          \"--pseudo-element-height\": `${dimensions.height + borderSize * 2}px`,\n          \"--after-blur\": `${dimensions.width / 3}px`,\n        } as CSSProperties\n      }\n      className={cn(\n        \"relative z-10 h-full w-full rounded-[var(--border-radius)]\",\n        className,\n      )}\n      {...props}\n    >\n      <div\n        className={cn(\n          \"relative h-full min-h-[inherit] w-full rounded-[var(--card-content-radius)] bg-gray-100 p-6\",\n          \"before:absolute before:-left-[var(--border-size)] before:-top-[var(--border-size)] before:-z-10 before:block\",\n          \"before:h-[var(--pseudo-element-height)] before:w-[var(--pseudo-element-width)] before:rounded-[var(--border-radius)] before:content-['']\",\n          \"before:bg-[linear-gradient(0deg,var(--neon-first-color),var(--neon-second-color))] before:bg-[length:100%_200%]\",\n          \"before:animate-backgroundPositionSpin\",\n          \"after:absolute after:-left-[var(--border-size)] after:-top-[var(--border-size)] after:-z-10 after:block\",\n          \"after:h-[var(--pseudo-element-height)] after:w-[var(--pseudo-element-width)] after:rounded-[var(--border-radius)] after:blur-[var(--after-blur)] after:content-['']\",\n          \"after:bg-[linear-gradient(0deg,var(--neon-first-color),var(--neon-second-color))] after:bg-[length:100%_200%] after:opacity-80\",\n          \"after:animate-backgroundPositionSpin\",\n          \"dark:bg-neutral-900\",\n        )}\n      >\n        {children}\n      </div>\n    </div>\n  );\n};\n\nexport { NeonGradientCard };\n"
  },
  {
    "path": "frontend/components/magicui/number-ticker.tsx",
    "content": "\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { useInView, useMotionValue, useSpring } from \"framer-motion\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport default function NumberTicker({\n  value,\n  direction = \"up\",\n  delay = 0,\n  className,\n}: {\n  value: number;\n  direction?: \"up\" | \"down\";\n  className?: string;\n  delay?: number; // delay in s\n}) {\n  const ref = useRef<HTMLSpanElement>(null);\n  const motionValue = useMotionValue(direction === \"down\" ? value : 0);\n  const springValue = useSpring(motionValue, {\n    damping: 60,\n    stiffness: 100,\n  });\n  const isInView = useInView(ref, { once: true, margin: \"0px\" });\n\n  useEffect(() => {\n    isInView &&\n      setTimeout(() => {\n        motionValue.set(direction === \"down\" ? 0 : value);\n      }, delay * 1000);\n  }, [motionValue, isInView, delay, value, direction]);\n\n  useEffect(\n    () =>\n      springValue.on(\"change\", (latest) => {\n        if (ref.current) {\n          ref.current.textContent = Intl.NumberFormat(\"en-US\").format(\n            Number(latest.toFixed(0)),\n          );\n        }\n      }),\n    [springValue],\n  );\n\n  return (\n    <span\n      className={cn(\n        \"inline-block tabular-nums text-black dark:text-white tracking-wider\",\n        className,\n      )}\n      ref={ref}\n    />\n  );\n}\n"
  },
  {
    "path": "frontend/components/magicui/ripple.tsx",
    "content": "import React, { CSSProperties } from 'react';\n\ninterface RippleProps {\n  mainCircleSize?: number;\n  mainCircleOpacity?: number;\n  numCircles?: number;\n}\n\nconst Ripple = React.memo(function Ripple({\n  mainCircleSize = 210,\n  mainCircleOpacity = 0.24,\n  numCircles = 8,\n}: RippleProps) {\n  return (\n    <div className=\"absolute inset-0 flex items-center justify-center bg-white/5 [mask-image:linear-gradient(to_bottom,white,transparent)]\">\n      {Array.from({ length: numCircles }, (_, i) => {\n        const size = mainCircleSize + i * 70;\n        const opacity = mainCircleOpacity - i * 0.03;\n        const animationDelay = `${i * 0.06}s`;\n        const borderStyle = i === numCircles - 1 ? 'dashed' : 'solid';\n        const borderOpacity = 5 + i * 5;\n\n        return (\n          <div\n            key={i}\n            className={`absolute animate-ripple rounded-full bg-foreground/25 shadow-xl border [--i:${i}]`}\n            style={\n              {\n                width: `${size}px`,\n                height: `${size}px`,\n                opacity,\n                animationDelay,\n                borderStyle,\n                borderWidth: '1px',\n                borderColor: `hsl(var(--foreground), ${borderOpacity / 100})`,\n                top: '50%',\n                left: '50%',\n                transform: 'translate(-50%, -50%) scale(1)',\n              } as CSSProperties\n            }\n          />\n        );\n      })}\n    </div>\n  );\n});\n\nRipple.displayName = 'Ripple';\n\nexport default Ripple;\n"
  },
  {
    "path": "frontend/components/magicui/shimmer-button.tsx",
    "content": "import React, { CSSProperties } from 'react';\n\nimport { cn } from '@/lib/utils';\n\nexport interface ShimmerButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n  shimmerColor?: string;\n  shimmerSize?: string;\n  borderRadius?: string;\n  shimmerDuration?: string;\n  background?: string;\n  className?: string;\n  children?: React.ReactNode;\n}\n\nconst ShimmerButton = React.forwardRef<HTMLButtonElement, ShimmerButtonProps>(\n  (\n    {\n      shimmerColor = '#ffffff',\n      shimmerSize = '0.05em',\n      shimmerDuration = '3s',\n      borderRadius = '100px',\n      background = 'rgba(0, 0, 0, 1)',\n      className,\n      children,\n      ...props\n    },\n    ref\n  ) => {\n    return (\n      <button\n        style={\n          {\n            '--spread': '90deg',\n            '--shimmer-color': shimmerColor,\n            '--radius': borderRadius,\n            '--speed': shimmerDuration,\n            '--cut': shimmerSize,\n            '--bg': background,\n          } as CSSProperties\n        }\n        className={cn(\n          'group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden whitespace-nowrap border border-white/10 px-6 py-2 text-white [background:var(--bg)] [border-radius:var(--radius)] dark:text-black',\n          'transform-gpu transition-transform duration-300 ease-in-out active:translate-y-[1px]',\n          className\n        )}\n        ref={ref}\n        {...props}\n      >\n        {/* spark container */}\n        <div\n          className={cn(\n            '-z-30 blur-[2px]',\n            'absolute inset-0 overflow-visible [container-type:size]'\n          )}\n        >\n          {/* spark */}\n          <div className=\"absolute inset-0 h-[100cqh] animate-slide [aspect-ratio:1] [border-radius:0] [mask:none]\">\n            {/* spark before */}\n            <div className=\"animate-spin-around absolute inset-[-100%] w-auto rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))] [translate:0_0]\" />\n          </div>\n        </div>\n        {children}\n\n        {/* Highlight */}\n        <div\n          className={cn(\n            'insert-0 absolute h-full w-full',\n\n            'rounded-2xl px-4 py-1.5 text-sm font-medium shadow-[inset_0_-8px_10px_#ffffff1f]',\n\n            // transition\n            'transform-gpu transition-all duration-300 ease-in-out',\n\n            // on hover\n            'group-hover:shadow-[inset_0_-6px_10px_#ffffff3f]',\n\n            // on click\n            'group-active:shadow-[inset_0_-10px_10px_#ffffff3f]'\n          )}\n        />\n\n        {/* backdrop */}\n        <div\n          className={cn(\n            'absolute -z-20 [background:var(--bg)] [border-radius:var(--radius)] [inset:var(--cut)]'\n          )}\n        />\n      </button>\n    );\n  }\n);\n\nShimmerButton.displayName = 'ShimmerButton';\n\nexport default ShimmerButton;\n"
  },
  {
    "path": "frontend/components/magicui/shine-border.tsx",
    "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\n\ntype TColorProp = string | string[];\n\ninterface ShineBorderProps {\n  borderRadius?: number;\n  borderWidth?: number;\n  duration?: number;\n  color?: TColorProp;\n  className?: string;\n  children: React.ReactNode;\n}\n\n/**\n * @name Shine Border\n * @description It is an animated background border effect component with easy to use and configurable props.\n * @param borderRadius defines the radius of the border.\n * @param borderWidth defines the width of the border.\n * @param duration defines the animation duration to be applied on the shining border\n * @param color a string or string array to define border color.\n * @param className defines the class name to be applied to the component\n * @param children contains react node elements.\n */\nexport default function ShineBorder({\n  borderRadius = 8,\n  borderWidth = 1,\n  duration = 14,\n  color = \"#000000\",\n  className,\n  children,\n}: ShineBorderProps) {\n  return (\n    <div\n      style={\n        {\n          \"--border-radius\": `${borderRadius}px`,\n        } as React.CSSProperties\n      }\n      className={cn(\n        \"relative grid min-h-[60px] w-fit min-w-[300px] place-items-center rounded-[--border-radius] bg-white p-3 text-black dark:bg-black dark:text-white\",\n        className,\n      )}\n    >\n      <div\n        style={\n          {\n            \"--border-width\": `${borderWidth}px`,\n            \"--border-radius\": `${borderRadius}px`,\n            \"--shine-pulse-duration\": `${duration}s`,\n            \"--mask-linear-gradient\": `linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)`,\n            \"--background-radial-gradient\": `radial-gradient(transparent,transparent, ${color instanceof Array ? color.join(\",\") : color},transparent,transparent)`,\n          } as React.CSSProperties\n        }\n        className={`before:bg-shine-size before:absolute before:inset-0 before:aspect-square before:size-full before:rounded-[--border-radius] before:p-[--border-width] before:will-change-[background-position] before:content-[\"\"] before:![-webkit-mask-composite:xor] before:![mask-composite:exclude] before:[background-image:--background-radial-gradient] before:[background-size:300%_300%] before:[mask:--mask-linear-gradient] motion-safe:before:animate-[shine-pulse_var(--shine-pulse-duration)_infinite_linear]`}\n      ></div>\n      {children}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/magicui/shiny-button.tsx",
    "content": "\"use client\";\n\nimport { motion, type AnimationProps } from \"framer-motion\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst animationProps = {\n  initial: { \"--x\": \"100%\", scale: 0.8 },\n  animate: { \"--x\": \"-100%\", scale: 1 },\n  whileTap: { scale: 0.95 },\n  transition: {\n    repeat: Infinity,\n    repeatType: \"loop\",\n    repeatDelay: 1,\n    type: \"spring\",\n    stiffness: 20,\n    damping: 15,\n    mass: 2,\n    scale: {\n      type: \"spring\",\n      stiffness: 200,\n      damping: 5,\n      mass: 0.5,\n    },\n  },\n} as AnimationProps;\ninterface ShinyButtonProps {\n  text: string;\n  className?: string;\n}\nconst ShinyButton = ({\n  text = \"shiny-button\",\n  className,\n}: ShinyButtonProps) => {\n  return (\n    <motion.button\n      {...animationProps}\n      className={cn(\n        \"relative rounded-lg px-6 py-2 font-medium backdrop-blur-xl transition-[box-shadow] duration-300 ease-in-out hover:shadow dark:bg-[radial-gradient(circle_at_50%_0%,hsl(var(--primary)/10%)_0%,transparent_60%)] dark:hover:shadow-[0_0_20px_hsl(var(--primary)/10%)]\",\n        className,\n      )}\n    >\n      <span\n        className=\"relative block h-full w-full text-sm uppercase tracking-wide text-[rgb(0,0,0,65%)] dark:font-light dark:text-[rgb(255,255,255,90%)]\"\n        style={{\n          maskImage:\n            \"linear-gradient(-75deg,hsl(var(--primary)) calc(var(--x) + 20%),transparent calc(var(--x) + 30%),hsl(var(--primary)) calc(var(--x) + 100%))\",\n        }}\n      >\n        {text}\n      </span>\n      <span\n        style={{\n          mask: \"linear-gradient(rgb(0,0,0), rgb(0,0,0)) content-box,linear-gradient(rgb(0,0,0), rgb(0,0,0))\",\n          maskComposite: \"exclude\",\n        }}\n        className=\"absolute inset-0 z-10 block rounded-[inherit] bg-[linear-gradient(-75deg,hsl(var(--primary)/10%)_calc(var(--x)+20%),hsl(var(--primary)/50%)_calc(var(--x)+25%),hsl(var(--primary)/10%)_calc(var(--x)+100%))] p-px\"\n      ></span>\n    </motion.button>\n  );\n};\n\nexport default ShinyButton;\n"
  },
  {
    "path": "frontend/components/magicui/sparkles-text.tsx",
    "content": "\"use client\";\n\nimport { CSSProperties, ReactElement, useEffect, useState } from \"react\";\nimport { motion } from \"framer-motion\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface Sparkle {\n  id: string;\n  x: string;\n  y: string;\n  color: string;\n  delay: number;\n  scale: number;\n  lifespan: number;\n}\n\ninterface SparklesTextProps {\n  /**\n   * @default <div />\n   * @type ReactElement\n   * @description\n   * The component to be rendered as the text\n   * */\n  as?: ReactElement;\n\n  /**\n   * @default \"\"\n   * @type string\n   * @description\n   * The className of the text\n   */\n  className?: string;\n\n  /**\n   * @required\n   * @type string\n   * @description\n   * The text to be displayed\n   * */\n  text: string;\n\n  /**\n   * @default 10\n   * @type number\n   * @description\n   * The count of sparkles\n   * */\n  sparklesCount?: number;\n\n  /**\n   * @default \"{first: '#9E7AFF', second: '#FE8BBB'}\"\n   * @type string\n   * @description\n   * The colors of the sparkles\n   * */\n  colors?: {\n    first: string;\n    second: string;\n  };\n}\n\nconst SparklesText: React.FC<SparklesTextProps> = ({\n  text,\n  colors = { first: \"#9E7AFF\", second: \"#FE8BBB\" },\n  className,\n  sparklesCount = 10,\n  ...props\n}) => {\n  const [sparkles, setSparkles] = useState<Sparkle[]>([]);\n\n  useEffect(() => {\n    const generateStar = (): Sparkle => {\n      const starX = `${Math.random() * 100}%`;\n      const starY = `${Math.random() * 100}%`;\n      const color = Math.random() > 0.5 ? colors.first : colors.second;\n      const delay = Math.random() * 2;\n      const scale = Math.random() * 1 + 0.3;\n      const lifespan = Math.random() * 10 + 5;\n      const id = `${starX}-${starY}-${Date.now()}`;\n      return { id, x: starX, y: starY, color, delay, scale, lifespan };\n    };\n\n    const initializeStars = () => {\n      const newSparkles = Array.from({ length: sparklesCount }, generateStar);\n      setSparkles(newSparkles);\n    };\n\n    const updateStars = () => {\n      setSparkles((currentSparkles) =>\n        currentSparkles.map((star) => {\n          if (star.lifespan <= 0) {\n            return generateStar();\n          } else {\n            return { ...star, lifespan: star.lifespan - 0.1 };\n          }\n        }),\n      );\n    };\n\n    initializeStars();\n    const interval = setInterval(updateStars, 100);\n\n    return () => clearInterval(interval);\n  }, [colors.first, colors.second]);\n\n  return (\n    <div\n      className={cn(\"text-6xl font-bold\", className)}\n      {...props}\n      style={\n        {\n          \"--sparkles-first-color\": `${colors.first}`,\n          \"--sparkles-second-color\": `${colors.second}`,\n        } as CSSProperties\n      }\n    >\n      <span className=\"relative inline-block\">\n        {sparkles.map((sparkle) => (\n          <Sparkle key={sparkle.id} {...sparkle} />\n        ))}\n        <strong>{text}</strong>\n      </span>\n    </div>\n  );\n};\n\nconst Sparkle: React.FC<Sparkle> = ({ id, x, y, color, delay, scale }) => {\n  return (\n    <motion.svg\n      key={id}\n      className=\"pointer-events-none absolute z-20\"\n      initial={{ opacity: 0, left: x, top: y }}\n      animate={{\n        opacity: [0, 1, 0],\n        scale: [0, scale, 0],\n        rotate: [75, 120, 150],\n      }}\n      transition={{ duration: 0.8, repeat: Infinity, delay }}\n      width=\"21\"\n      height=\"21\"\n      viewBox=\"0 0 21 21\"\n    >\n      <path\n        d=\"M9.82531 0.843845C10.0553 0.215178 10.9446 0.215178 11.1746 0.843845L11.8618 2.72026C12.4006 4.19229 12.3916 6.39157 13.5 7.5C14.6084 8.60843 16.8077 8.59935 18.2797 9.13822L20.1561 9.82534C20.7858 10.0553 20.7858 10.9447 20.1561 11.1747L18.2797 11.8618C16.8077 12.4007 14.6084 12.3916 13.5 13.5C12.3916 14.6084 12.4006 16.8077 11.8618 18.2798L11.1746 20.1562C10.9446 20.7858 10.0553 20.7858 9.82531 20.1562L9.13819 18.2798C8.59932 16.8077 8.60843 14.6084 7.5 13.5C6.39157 12.3916 4.19225 12.4007 2.72023 11.8618L0.843814 11.1747C0.215148 10.9447 0.215148 10.0553 0.843814 9.82534L2.72023 9.13822C4.19225 8.59935 6.39157 8.60843 7.5 7.5C8.60843 6.39157 8.59932 4.19229 9.13819 2.72026L9.82531 0.843845Z\"\n        fill={color}\n      />\n    </motion.svg>\n  );\n};\n\nexport default SparklesText;\n"
  },
  {
    "path": "frontend/components/magicui/typing-animation.tsx",
    "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface TypingAnimationProps {\n  text: string;\n  duration?: number;\n  className?: string;\n}\n\nexport default function TypingAnimation({\n  text,\n  duration = 200,\n  className,\n}: TypingAnimationProps) {\n  const [displayedText, setDisplayedText] = useState<string>(\"\");\n  const [i, setI] = useState<number>(0);\n\n  useEffect(() => {\n    const typingEffect = setInterval(() => {\n      if (i < text.length) {\n        setDisplayedText(text.substring(0, i + 1));\n        setI(i + 1);\n      } else {\n        clearInterval(typingEffect);\n      }\n    }, duration);\n\n    return () => {\n      clearInterval(typingEffect);\n    };\n  }, [duration, i]);\n\n  return (\n    <h1\n      className={cn(\n        \"font-display text-center text-4xl font-bold leading-[5rem] tracking-[-0.02em] drop-shadow-sm\",\n        className,\n      )}\n    >\n      {displayedText ? displayedText : text}\n    </h1>\n  );\n}\n"
  },
  {
    "path": "frontend/components/sidebar.tsx",
    "content": "'use client';\n\nimport React from 'react';\nimport { motion, AnimatePresence } from 'framer-motion';\nimport { useConversationContext } from '@/app/ConversationContext';\nimport History from '@/components/history';\nimport { useAuth } from '@/app/authProvider';\n\nconst Sidebar: React.FC = () => {\n  const { isSidebarOpen, setIsSidebarOpen } = useConversationContext();\n  const { isAuthenticated } = useAuth();\n\n  const sidebarVariants = {\n    open: {\n      width: '20%',\n      minWidth: '350px',\n      transition: { duration: 0.3, ease: 'easeInOut' },\n    },\n    closed: {\n      width: 0,\n      minWidth: 0,\n      transition: { duration: 0.3, ease: 'easeInOut' },\n    },\n  };\n\n  const contentVariants = {\n    open: {\n      opacity: 1,\n      x: 0,\n      transition: { delay: 0.1, duration: 0.2 },\n    },\n    closed: {\n      opacity: 0,\n      x: -20,\n      transition: { duration: 0.2 },\n    },\n  };\n\n  return (\n    <>\n      <AnimatePresence>\n        {isSidebarOpen && (\n          <motion.div\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 0 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: 0.3 }}\n            className=\"fixed inset-0 bg-background bg-opacity-50 z-40 lg:hidden max-w-[350px] \"\n            onClick={() => setIsSidebarOpen(false)}\n          />\n        )}\n      </AnimatePresence>\n\n      <motion.div\n        variants={sidebarVariants}\n        initial=\"closed\"\n        animate={isSidebarOpen ? 'open' : 'closed'}\n        className={`fixed top-14 left-0 h-[calc(100vh-3.5rem)] bg-background overflow-hidden z-50 lg:relative lg:top-0 lg:h-full border-r ${\n          isSidebarOpen ? ' w-max-[350px]' : ''\n        }`}\n      >\n        <motion.div\n          variants={contentVariants}\n          initial=\"closed\"\n          animate={isSidebarOpen ? 'open' : 'closed'}\n          className=\"p-2 h-full\"\n        >\n          <History />\n        </motion.div>\n      </motion.div>\n    </>\n  );\n};\n\nexport default Sidebar;\n"
  },
  {
    "path": "frontend/components/theme-provider.tsx",
    "content": "'use client';\n\nimport * as React from 'react';\nimport { ThemeProvider as NextThemesProvider } from 'next-themes';\nimport { ThemeProviderProps } from 'next-themes/dist/types';\n\nexport function ThemeProvider({ children, ...props }: ThemeProviderProps) {\n  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n"
  },
  {
    "path": "frontend/components/theme-toggle.tsx",
    "content": "'use client';\n\nimport * as React from 'react';\nimport { useTheme } from 'next-themes';\n\nimport { Button } from '@/components/ui/button';\nimport { Moon, Sun } from 'lucide-react';\n\nexport function ThemeToggle() {\n  const { setTheme, theme } = useTheme();\n  const [_, startTransition] = React.useTransition();\n\n  return (\n    <Button\n      variant=\"ghost\"\n      size=\"icon\"\n      onClick={() => {\n        startTransition(() => {\n          setTheme(theme === 'light' ? 'dark' : 'light');\n        });\n      }}\n    >\n      {!theme ? null : theme === 'dark' ? (\n        <Moon className=\"h-5 w-5\" />\n      ) : (\n        <Sun className=\"h-5 w-5\" />\n      )}\n      <span className=\"sr-only\">Toggle theme</span>\n    </Button>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/accordion.tsx",
    "content": "'use client';\n\nimport * as React from 'react';\nimport * as AccordionPrimitive from '@radix-ui/react-accordion';\nimport { ChevronDown } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\n\nconst Accordion = AccordionPrimitive.Root;\n\nconst AccordionItem = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>\n>(({ className, ...props }, ref) => (\n  <AccordionPrimitive.Item\n    ref={ref}\n    className={cn('border-b', className)}\n    {...props}\n  />\n));\nAccordionItem.displayName = 'AccordionItem';\n\nconst AccordionTrigger = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <AccordionPrimitive.Header className=\"flex\">\n    <AccordionPrimitive.Trigger\n      ref={ref}\n      className={cn(\n        'flex flex-1 items-center justify-between py-2 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180',\n        className\n      )}\n      {...props}\n    >\n      {children}\n      <ChevronDown className=\"h-4 w-4 shrink-0 transition-transform duration-200\" />\n    </AccordionPrimitive.Trigger>\n  </AccordionPrimitive.Header>\n));\nAccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;\n\nconst AccordionContent = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <AccordionPrimitive.Content\n    ref={ref}\n    className=\"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down\"\n    {...props}\n  >\n    <div className={cn('pb-4 pt-0', className)}>{children}</div>\n  </AccordionPrimitive.Content>\n));\n\nAccordionContent.displayName = AccordionPrimitive.Content.displayName;\n\nexport { Accordion, AccordionItem, AccordionTrigger, AccordionContent };\n"
  },
  {
    "path": "frontend/components/ui/alert-dialog.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as AlertDialogPrimitive from \"@radix-ui/react-alert-dialog\"\n\nimport { cn } from \"@/lib/utils\"\nimport { buttonVariants } from \"@/components/ui/button\"\n\nconst AlertDialog = AlertDialogPrimitive.Root\n\nconst AlertDialogTrigger = AlertDialogPrimitive.Trigger\n\nconst AlertDialogPortal = AlertDialogPrimitive.Portal\n\nconst AlertDialogOverlay = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Overlay\n    className={cn(\n      \"fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0\",\n      className\n    )}\n    {...props}\n    ref={ref}\n  />\n))\nAlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName\n\nconst AlertDialogContent = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPortal>\n    <AlertDialogOverlay />\n    <AlertDialogPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg\",\n        className\n      )}\n      {...props}\n    />\n  </AlertDialogPortal>\n))\nAlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName\n\nconst AlertDialogHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-2 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nAlertDialogHeader.displayName = \"AlertDialogHeader\"\n\nconst AlertDialogFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nAlertDialogFooter.displayName = \"AlertDialogFooter\"\n\nconst AlertDialogTitle = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Title\n    ref={ref}\n    className={cn(\"text-lg font-semibold\", className)}\n    {...props}\n  />\n))\nAlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName\n\nconst AlertDialogDescription = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nAlertDialogDescription.displayName =\n  AlertDialogPrimitive.Description.displayName\n\nconst AlertDialogAction = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Action>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Action\n    ref={ref}\n    className={cn(buttonVariants(), className)}\n    {...props}\n  />\n))\nAlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName\n\nconst AlertDialogCancel = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Cancel>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Cancel\n    ref={ref}\n    className={cn(\n      buttonVariants({ variant: \"outline\" }),\n      \"mt-2 sm:mt-0\",\n      className\n    )}\n    {...props}\n  />\n))\nAlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName\n\nexport {\n  AlertDialog,\n  AlertDialogPortal,\n  AlertDialogOverlay,\n  AlertDialogTrigger,\n  AlertDialogContent,\n  AlertDialogHeader,\n  AlertDialogFooter,\n  AlertDialogTitle,\n  AlertDialogDescription,\n  AlertDialogAction,\n  AlertDialogCancel,\n}\n"
  },
  {
    "path": "frontend/components/ui/alert.tsx",
    "content": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst alertVariants = cva(\n  \"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-background text-foreground\",\n        destructive:\n          \"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nconst Alert = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>\n>(({ className, variant, ...props }, ref) => (\n  <div\n    ref={ref}\n    role=\"alert\"\n    className={cn(alertVariants({ variant }), className)}\n    {...props}\n  />\n))\nAlert.displayName = \"Alert\"\n\nconst AlertTitle = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLHeadingElement>\n>(({ className, ...props }, ref) => (\n  <h5\n    ref={ref}\n    className={cn(\"mb-1 font-medium leading-none tracking-tight\", className)}\n    {...props}\n  />\n))\nAlertTitle.displayName = \"AlertTitle\"\n\nconst AlertDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"text-sm [&_p]:leading-relaxed\", className)}\n    {...props}\n  />\n))\nAlertDescription.displayName = \"AlertDescription\"\n\nexport { Alert, AlertTitle, AlertDescription }\n"
  },
  {
    "path": "frontend/components/ui/aspect-ratio.tsx",
    "content": "\"use client\"\n\nimport * as AspectRatioPrimitive from \"@radix-ui/react-aspect-ratio\"\n\nconst AspectRatio = AspectRatioPrimitive.Root\n\nexport { AspectRatio }\n"
  },
  {
    "path": "frontend/components/ui/avatar.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Avatar = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full\",\n      className\n    )}\n    {...props}\n  />\n))\nAvatar.displayName = AvatarPrimitive.Root.displayName\n\nconst AvatarImage = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Image>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Image\n    ref={ref}\n    className={cn(\"aspect-square h-full w-full\", className)}\n    {...props}\n  />\n))\nAvatarImage.displayName = AvatarPrimitive.Image.displayName\n\nconst AvatarFallback = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Fallback>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Fallback\n    ref={ref}\n    className={cn(\n      \"flex h-full w-full items-center justify-center rounded-full bg-muted\",\n      className\n    )}\n    {...props}\n  />\n))\nAvatarFallback.displayName = AvatarPrimitive.Fallback.displayName\n\nexport { Avatar, AvatarImage, AvatarFallback }\n"
  },
  {
    "path": "frontend/components/ui/badge.tsx",
    "content": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst badgeVariants = cva(\n  \"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\",\n  {\n    variants: {\n      variant: {\n        default:\n          \"border-transparent bg-primary text-primary-foreground hover:bg-primary/80\",\n        secondary:\n          \"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n        destructive:\n          \"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80\",\n        outline: \"text-foreground\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nexport interface BadgeProps\n  extends React.HTMLAttributes<HTMLDivElement>,\n    VariantProps<typeof badgeVariants> {}\n\nfunction Badge({ className, variant, ...props }: BadgeProps) {\n  return (\n    <div className={cn(badgeVariants({ variant }), className)} {...props} />\n  )\n}\n\nexport { Badge, badgeVariants }\n"
  },
  {
    "path": "frontend/components/ui/breadcrumb.tsx",
    "content": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { ChevronRight, MoreHorizontal } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Breadcrumb = React.forwardRef<\n  HTMLElement,\n  React.ComponentPropsWithoutRef<\"nav\"> & {\n    separator?: React.ReactNode\n  }\n>(({ ...props }, ref) => <nav ref={ref} aria-label=\"breadcrumb\" {...props} />)\nBreadcrumb.displayName = \"Breadcrumb\"\n\nconst BreadcrumbList = React.forwardRef<\n  HTMLOListElement,\n  React.ComponentPropsWithoutRef<\"ol\">\n>(({ className, ...props }, ref) => (\n  <ol\n    ref={ref}\n    className={cn(\n      \"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5\",\n      className\n    )}\n    {...props}\n  />\n))\nBreadcrumbList.displayName = \"BreadcrumbList\"\n\nconst BreadcrumbItem = React.forwardRef<\n  HTMLLIElement,\n  React.ComponentPropsWithoutRef<\"li\">\n>(({ className, ...props }, ref) => (\n  <li\n    ref={ref}\n    className={cn(\"inline-flex items-center gap-1.5\", className)}\n    {...props}\n  />\n))\nBreadcrumbItem.displayName = \"BreadcrumbItem\"\n\nconst BreadcrumbLink = React.forwardRef<\n  HTMLAnchorElement,\n  React.ComponentPropsWithoutRef<\"a\"> & {\n    asChild?: boolean\n  }\n>(({ asChild, className, ...props }, ref) => {\n  const Comp = asChild ? Slot : \"a\"\n\n  return (\n    <Comp\n      ref={ref}\n      className={cn(\"transition-colors hover:text-foreground\", className)}\n      {...props}\n    />\n  )\n})\nBreadcrumbLink.displayName = \"BreadcrumbLink\"\n\nconst BreadcrumbPage = React.forwardRef<\n  HTMLSpanElement,\n  React.ComponentPropsWithoutRef<\"span\">\n>(({ className, ...props }, ref) => (\n  <span\n    ref={ref}\n    role=\"link\"\n    aria-disabled=\"true\"\n    aria-current=\"page\"\n    className={cn(\"font-normal text-foreground\", className)}\n    {...props}\n  />\n))\nBreadcrumbPage.displayName = \"BreadcrumbPage\"\n\nconst BreadcrumbSeparator = ({\n  children,\n  className,\n  ...props\n}: React.ComponentProps<\"li\">) => (\n  <li\n    role=\"presentation\"\n    aria-hidden=\"true\"\n    className={cn(\"[&>svg]:size-3.5\", className)}\n    {...props}\n  >\n    {children ?? <ChevronRight />}\n  </li>\n)\nBreadcrumbSeparator.displayName = \"BreadcrumbSeparator\"\n\nconst BreadcrumbEllipsis = ({\n  className,\n  ...props\n}: React.ComponentProps<\"span\">) => (\n  <span\n    role=\"presentation\"\n    aria-hidden=\"true\"\n    className={cn(\"flex h-9 w-9 items-center justify-center\", className)}\n    {...props}\n  >\n    <MoreHorizontal className=\"h-4 w-4\" />\n    <span className=\"sr-only\">More</span>\n  </span>\n)\nBreadcrumbEllipsis.displayName = \"BreadcrumbElipssis\"\n\nexport {\n  Breadcrumb,\n  BreadcrumbList,\n  BreadcrumbItem,\n  BreadcrumbLink,\n  BreadcrumbPage,\n  BreadcrumbSeparator,\n  BreadcrumbEllipsis,\n}\n"
  },
  {
    "path": "frontend/components/ui/button.tsx",
    "content": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst buttonVariants = cva(\n  \"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n        destructive:\n          \"bg-destructive text-destructive-foreground hover:bg-destructive/90\",\n        outline:\n          \"border border-input bg-background hover:bg-accent hover:text-accent-foreground\",\n        secondary:\n          \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n        ghost: \"hover:bg-accent hover:text-accent-foreground\",\n        link: \"text-primary underline-offset-4 hover:underline\",\n      },\n      size: {\n        default: \"h-10 px-4 py-2\",\n        sm: \"h-9 rounded-md px-3\",\n        lg: \"h-11 rounded-md px-8\",\n        icon: \"h-10 w-10\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n      size: \"default\",\n    },\n  }\n)\n\nexport interface ButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n    VariantProps<typeof buttonVariants> {\n  asChild?: boolean\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n  ({ className, variant, size, asChild = false, ...props }, ref) => {\n    const Comp = asChild ? Slot : \"button\"\n    return (\n      <Comp\n        className={cn(buttonVariants({ variant, size, className }))}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nButton.displayName = \"Button\"\n\nexport { Button, buttonVariants }\n"
  },
  {
    "path": "frontend/components/ui/card-hover-effect.tsx",
    "content": "import { cn } from '@/lib/utils';\nimport { AnimatePresence, motion } from 'framer-motion';\nimport Link from 'next/link';\nimport { useState } from 'react';\n\nexport const HoverEffect = ({\n  items,\n  className,\n}: {\n  items: {\n    title: string;\n    description: string;\n    link: string;\n  }[];\n  className?: string;\n}) => {\n  let [hoveredIndex, setHoveredIndex] = useState<number | null>(null);\n\n  return (\n    <div\n      className={cn(\n        'grid grid-cols-1 md:grid-cols-2  lg:grid-cols-3  py-10',\n        className\n      )}\n    >\n      {items.map((item, idx) => (\n        <div\n          // href={item?.link}\n          key={item?.link}\n          className=\"relative group  block p-2 h-full w-full\"\n          onMouseEnter={() => setHoveredIndex(idx)}\n          onMouseLeave={() => setHoveredIndex(null)}\n        >\n          <AnimatePresence>\n            {hoveredIndex === idx && (\n              <motion.span\n                className=\"absolute inset-0 h-full w-full bg-neutral-200 dark:bg-muted block  rounded-xl\"\n                layoutId=\"hoverBackground\"\n                initial={{ opacity: 0 }}\n                animate={{\n                  opacity: 1,\n                  transition: { duration: 0.15 },\n                }}\n                exit={{\n                  opacity: 0,\n                  transition: { duration: 0.15, delay: 0.2 },\n                }}\n              />\n            )}\n          </AnimatePresence>\n          <Card>\n            <CardTitle>{item.title}</CardTitle>\n            <CardDescription>{item.description}</CardDescription>\n          </Card>\n        </div>\n      ))}\n    </div>\n  );\n};\n\nexport const Card = ({\n  className,\n  children,\n}: {\n  className?: string;\n  children: React.ReactNode;\n}) => {\n  return (\n    <div\n      className={cn(\n        'rounded-xl h-full w-full p-4 overflow-hidden bg-background border border-zinc-200  dark:border-white/[0.1] dark:group-hover:border-zinc-900  relative z-20',\n        className\n      )}\n    >\n      <div className=\"relative z-50\">\n        <div className=\"p-4\">{children}</div>\n      </div>\n    </div>\n  );\n};\nexport const CardTitle = ({\n  className,\n  children,\n}: {\n  className?: string;\n  children: React.ReactNode;\n}) => {\n  return (\n    <h4\n      className={cn('text-foreground font-bold tracking-wide mt-4', className)}\n    >\n      {children}\n    </h4>\n  );\n};\nexport const CardDescription = ({\n  className,\n  children,\n}: {\n  className?: string;\n  children: React.ReactNode;\n}) => {\n  return (\n    <p\n      className={cn(\n        'mt-8 text-muted-foreground tracking-wide leading-relaxed text-sm',\n        className\n      )}\n    >\n      {children}\n    </p>\n  );\n};\n"
  },
  {
    "path": "frontend/components/ui/card.tsx",
    "content": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Card = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\n      \"rounded-lg border bg-card text-card-foreground shadow-sm\",\n      className\n    )}\n    {...props}\n  />\n))\nCard.displayName = \"Card\"\n\nconst CardHeader = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"flex flex-col space-y-1.5 p-6\", className)}\n    {...props}\n  />\n))\nCardHeader.displayName = \"CardHeader\"\n\nconst CardTitle = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLHeadingElement>\n>(({ className, ...props }, ref) => (\n  <h3\n    ref={ref}\n    className={cn(\n      \"text-2xl font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nCardTitle.displayName = \"CardTitle\"\n\nconst CardDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n  <p\n    ref={ref}\n    className={cn(\"text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nCardDescription.displayName = \"CardDescription\"\n\nconst CardContent = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div ref={ref} className={cn(\"p-6 pt-0\", className)} {...props} />\n))\nCardContent.displayName = \"CardContent\"\n\nconst CardFooter = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"flex items-center p-6 pt-0\", className)}\n    {...props}\n  />\n))\nCardFooter.displayName = \"CardFooter\"\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-actions.tsx",
    "content": "import { PauseCircle, RefreshCw } from \"lucide-react\";\n\nimport { Button } from \"../button\";\nimport { ChatHandler } from \"./chat.interface\";\n\nexport default function ChatActions(\n  props: Pick<ChatHandler, \"stop\" | \"reload\"> & {\n    showReload?: boolean;\n    showStop?: boolean;\n  },\n) {\n  return (\n    <div className=\"space-x-4\">\n      {props.showStop && (\n        <Button variant=\"outline\" size=\"sm\" onClick={props.stop}>\n          <PauseCircle className=\"mr-2 h-4 w-4\" />\n          Stop generating\n        </Button>\n      )}\n      {props.showReload && (\n        <Button variant=\"outline\" size=\"sm\" onClick={props.reload}>\n          <RefreshCw className=\"mr-2 h-4 w-4\" />\n          Regenerate\n        </Button>\n      )}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-input.tsx",
    "content": "'use client';\nimport React, { useRef, useEffect, ChangeEvent } from 'react';\nimport { JSONValue } from 'ai';\nimport { Button } from '../button';\nimport { DocumentPreview } from '../document-preview';\nimport FileUploader from '../file-uploader';\nimport { Textarea } from '../textarea';\nimport UploadImagePreview from '../upload-image-preview';\nimport { ChatHandler } from './chat.interface';\nimport { useFile } from './hooks/use-file';\nimport { CornerRightUp, SendHorizontal } from 'lucide-react';\n\nconst ALLOWED_EXTENSIONS = ['pdf', 'txt', 'docx'];\n\nexport default function ChatInput(\n  props: Pick<\n    ChatHandler,\n    | 'isLoading'\n    | 'input'\n    | 'onFileUpload'\n    | 'onFileError'\n    | 'handleSubmit'\n    | 'handleInputChange'\n    | 'messages'\n    | 'setInput'\n    | 'append'\n  > & {\n    requestParams?: any;\n  }\n) {\n  const {\n    imageUrl,\n    setImageUrl,\n    uploadFile,\n    files,\n    removeDoc,\n    reset,\n    getAnnotations,\n  } = useFile();\n\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n  useEffect(() => {\n    if (textareaRef.current) {\n      textareaRef.current.style.height = 'auto';\n      const scrollHeight = textareaRef.current.scrollHeight;\n      const lines = scrollHeight / 20; // Assuming 20px per line\n      const newHeight = Math.min(lines, 10) * 20;\n      textareaRef.current.style.height = `${newHeight}px`;\n    }\n  }, [props.input]);\n\n  const handleSubmitWithAnnotations = (\n    e: React.FormEvent<HTMLFormElement>,\n    annotations: JSONValue[] | undefined\n  ) => {\n    e.preventDefault();\n    props.append!({\n      content: props.input,\n      role: 'user',\n      createdAt: new Date(),\n      annotations,\n    });\n    props.setInput!('');\n  };\n\n  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    const annotations = getAnnotations();\n    if (annotations.length) {\n      handleSubmitWithAnnotations(e, annotations);\n      return reset();\n    }\n    props.handleSubmit(e);\n  };\n\n  const handleUploadFile = async (file: File) => {\n    if (imageUrl || files.length > 0) {\n      alert('You can only upload one file at a time.');\n      return;\n    }\n    try {\n      await uploadFile(file, props.requestParams);\n      props.onFileUpload?.(file);\n    } catch (error: any) {\n      props.onFileError?.(error.message);\n    }\n  };\n\n  const handleInputChange = (e: ChangeEvent<HTMLTextAreaElement>) => {\n    props.handleInputChange(e as any);\n  };\n\n  return (\n    <form\n      onSubmit={onSubmit}\n      className=\"rounded-3xl p-2 shadow-md shadow-black/10 space-y-4 shrink-0 border-2 border-slate-500/10 bg-background\"\n    >\n      {imageUrl && (\n        <UploadImagePreview url={imageUrl} onRemove={() => setImageUrl(null)} />\n      )}\n      {files.length > 0 && (\n        <div className=\"flex gap-4 w-full overflow-auto py-2\">\n          {files.map((file) => (\n            <DocumentPreview\n              key={file.id}\n              file={file}\n              onRemove={() => removeDoc(file)}\n            />\n          ))}\n        </div>\n      )}\n      <div className=\"flex w-full items-end justify-between gap-4 \">\n        <Textarea\n          ref={textareaRef}\n          name=\"message\"\n          placeholder=\"Type a message\"\n          // className=\"flex-1 overflow-y-auto resize-none rounded-2xl bg-transparent\"\n          className=\"flex-1 resize-none rounded-2xl bg-transparent focus:outline-none focus:ring-0 text-base\"\n          rows={1}\n          value={props.input}\n          onChange={handleInputChange}\n          onKeyDown={(e) => {\n            if (e.key === 'Enter' && !e.shiftKey) {\n              e.preventDefault();\n              onSubmit(e as any);\n            }\n          }}\n          style={{\n            minHeight: '30px',\n            maxHeight: '200px',\n            overflow: 'hidden',\n            border: 'none',\n            boxShadow: 'none',\n          }}\n        />\n        {/* <FileUploader\n          onFileUpload={handleUploadFile}\n          onFileError={props.onFileError}\n          config={{\n            allowedExtensions: ALLOWED_EXTENSIONS,\n            disabled: props.isLoading,\n          }}\n        /> */}\n        <Button\n          type=\"submit\"\n          disabled={props.isLoading || !props.input.trim()}\n          className=\"w-fit h-fit rounded-2xl\"\n        >\n          <CornerRightUp className=\"w-5 h-5 font-bold\" />\n        </Button>\n      </div>\n    </form>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-avatar.tsx",
    "content": "import { User2 } from 'lucide-react';\nimport Image from 'next/image';\nimport { useTheme } from 'next-themes';\n\nexport default function ChatAvatar({ role }: { role: string }) {\n  const { theme, setTheme } = useTheme();\n  if (role === 'user') {\n    return (\n      <div className=\"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border bg-background shadow\">\n        <User2 className=\"h-4 w-4\" />\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"hidden md:flex h-fit w-fit shrink-0 select-none items-center justify-center rounded-xl border bg-white text-white shadow\">\n      <Image\n        src={\n          theme == 'dark' ? '/images/icon_light.png' : '/images/icon_dark.png'\n        }\n        alt=\"logo\"\n        width={30}\n        height={30}\n        priority\n      />\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-events.tsx",
    "content": "import { ChevronDown, ChevronRight, Loader2 } from \"lucide-react\";\nimport { useState } from \"react\";\nimport { Button } from \"../../button\";\nimport {\n  Collapsible,\n  CollapsibleContent,\n  CollapsibleTrigger,\n} from \"../../collapsible\";\nimport { EventData } from \"../index\";\n\nexport function ChatEvents({\n  data,\n  isLoading,\n}: {\n  data: EventData[];\n  isLoading: boolean;\n}) {\n  const [isOpen, setIsOpen] = useState(false);\n\n  const buttonLabel = isOpen ? \"Hide events\" : \"Show events\";\n\n  const EventIcon = isOpen ? (\n    <ChevronDown className=\"h-4 w-4\" />\n  ) : (\n    <ChevronRight className=\"h-4 w-4\" />\n  );\n\n  return (\n    <div className=\"border-l-2 border-indigo-400 pl-2\">\n      <Collapsible open={isOpen} onOpenChange={setIsOpen}>\n        <CollapsibleTrigger asChild>\n          <Button variant=\"secondary\" className=\"space-x-2\">\n            {isLoading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : null}\n            <span>{buttonLabel}</span>\n            {EventIcon}\n          </Button>\n        </CollapsibleTrigger>\n        <CollapsibleContent asChild>\n          <div className=\"mt-4 text-sm space-y-2\">\n            {data.map((eventItem, index) => (\n              <div className=\"whitespace-break-spaces\" key={index}>\n                {eventItem.title}\n              </div>\n            ))}\n          </div>\n        </CollapsibleContent>\n      </Collapsible>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-files.tsx",
    "content": "import { DocumentPreview } from \"../../document-preview\";\nimport { DocumentFileData } from \"../index\";\n\nexport function ChatFiles({ data }: { data: DocumentFileData }) {\n  if (!data.files.length) return null;\n  return (\n    <div className=\"flex gap-2 items-center\">\n      {data.files.map((file) => (\n        <DocumentPreview key={file.id} file={file} />\n      ))}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-image.tsx",
    "content": "import Image from \"next/image\";\nimport { type ImageData } from \"../index\";\n\nexport function ChatImage({ data }: { data: ImageData }) {\n  return (\n    <div className=\"rounded-md max-w-[200px] shadow-md\">\n      <Image\n        src={data.url}\n        width={0}\n        height={0}\n        sizes=\"100vw\"\n        style={{ width: \"100%\", height: \"auto\" }}\n        alt=\"\"\n      />\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-sources.tsx",
    "content": "'use client';\n'use client';\nimport React, { useMemo } from 'react';\nimport { Check, Copy } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n  HoverCard,\n  HoverCardContent,\n  HoverCardTrigger,\n} from '@/components/ui/hover-card';\nimport { useCopyToClipboard } from '../hooks/use-copy-to-clipboard';\nimport PdfDialog from '../widgets/PdfDialog';\n\nconst SCORE_THRESHOLD = 0.3;\n\ninterface SourceNode {\n  id: string;\n  metadata: {\n    url?: string;\n    [key: string]: unknown;\n  };\n  score?: number;\n  url?: string;\n}\n\ninterface SourceData {\n  nodes: SourceNode[];\n}\n\ninterface NodeInfo {\n  id: string;\n  url?: string;\n  metadata: {\n    url?: string;\n    [key: string]: unknown;\n  };\n}\n\ninterface SourceNumberButtonProps {\n  index: number;\n}\n\nfunction SourceNumberButton({ index }: SourceNumberButtonProps) {\n  return (\n    <div className=\"text-xs w-5 h-5 rounded-full text-accent-foreground bg-background mb-2 flex items-center justify-center hover:text-primary-foreground hover:bg-secondary-foreground hover:cursor-pointer\">\n      {index + 1}\n    </div>\n  );\n}\n\nfunction prefixUrl(url: string): string {\n  if (url.match(/^\\/api\\/file/)) {\n    return `${process.env.NEXT_PUBLIC_SERVER_URL}${url}`;\n  }\n  return url;\n}\n\ninterface NodeInfoProps {\n  nodeInfo: NodeInfo;\n}\n\nfunction NodeInfo({ nodeInfo }: NodeInfoProps) {\n  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 1000 });\n  const originalUrl = nodeInfo.metadata?.url || nodeInfo.url;\n  const url = originalUrl ? prefixUrl(originalUrl) : undefined;\n\n  if (url) {\n    return (\n      <div className=\"flex items-center my-2\">\n        <a\n          className=\"hover:text-blue-900 truncate\"\n          href={url}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n        >\n          <span>{url}</span>\n        </a>\n        <Button\n          onClick={() => copyToClipboard(url)}\n          size=\"icon\"\n          variant=\"ghost\"\n          className=\"h-12 w-12 shrink-0\"\n        >\n          {isCopied ? (\n            <Check className=\"h-4 w-4\" />\n          ) : (\n            <Copy className=\"h-4 w-4\" />\n          )}\n        </Button>\n      </div>\n    );\n  }\n\n  return (\n    <p>\n      Sorry, unknown node type. Please add a new renderer in the NodeInfo\n      component.\n    </p>\n  );\n}\n\ninterface ChatSourcesProps {\n  data: SourceData;\n}\n\nexport function ChatSources({ data }: ChatSourcesProps) {\n  const sources: NodeInfo[] = useMemo(() => {\n    const nodesByPath: Record<string, NodeInfo> = {};\n\n    data.nodes\n      .filter((node) => (node.score ?? 1) > SCORE_THRESHOLD)\n      .sort((a, b) => (b.score ?? 1) - (a.score ?? 1))\n      .forEach((node) => {\n        const nodeInfo: NodeInfo = {\n          id: node.id,\n          url: node.metadata?.url || node.url,\n          metadata: node.metadata,\n        };\n        const key = nodeInfo.url ?? nodeInfo.id;\n        if (!nodesByPath[key]) {\n          nodesByPath[key] = nodeInfo;\n        }\n      });\n\n    return Object.values(nodesByPath);\n  }, [data.nodes]);\n\n  if (sources.length === 0) return null;\n\n  return (\n    <div className=\"space-x-2 text-sm\">\n      <span className=\"font-semibold\">Sources:</span>\n      <div className=\"inline-flex gap-1 items-center\">\n        {sources.map((nodeInfo, index) => {\n          const originalUrl = nodeInfo.metadata?.url || nodeInfo.url;\n          const url = originalUrl ? prefixUrl(originalUrl) : undefined;\n          if (url?.endsWith('.pdf')) {\n            return (\n              <PdfDialog\n                key={nodeInfo.id}\n                documentId={nodeInfo.id}\n                url={url}\n                trigger={<SourceNumberButton index={index} />}\n              />\n            );\n          }\n          return (\n            <div key={nodeInfo.id}>\n              <HoverCard>\n                <HoverCardTrigger>\n                  <SourceNumberButton index={index} />\n                </HoverCardTrigger>\n                <HoverCardContent className=\"w-[320px]\">\n                  <NodeInfo nodeInfo={nodeInfo} />\n                </HoverCardContent>\n              </HoverCard>\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-suggestedQuestions.tsx",
    "content": "import { useState } from \"react\";\nimport { ChatHandler, SuggestedQuestionsData } from \"..\";\n\nexport function SuggestedQuestions({\n  questions,\n  append,\n}: {\n  questions: SuggestedQuestionsData;\n  append: Pick<ChatHandler, \"append\">[\"append\"];\n}) {\n  const [showQuestions, setShowQuestions] = useState(questions.length > 0);\n\n  return (\n    showQuestions &&\n    append !== undefined && (\n      <div className=\"flex flex-col space-y-2\">\n        {questions.map((question, index) => (\n          <a\n            key={index}\n            onClick={() => {\n              append({ role: \"user\", content: question });\n              setShowQuestions(false);\n            }}\n            className=\"text-sm italic hover:underline cursor-pointer\"\n          >\n            {\"->\"} {question}\n          </a>\n        ))}\n      </div>\n    )\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/chat-tools.tsx",
    "content": "import { ToolData } from '../index';\nimport { WeatherCard, WeatherData } from '../widgets/WeatherCard';\n\n// TODO: If needed, add displaying more tool outputs here\nexport default function ChatTools({ data }: { data: ToolData }) {\n  if (!data) return null;\n\n  const { toolCall, toolOutput } = data;\n\n  // Check if toolOutput is defined and has the isError property\n  if (\n    toolOutput &&\n    typeof toolOutput.isError === 'boolean' &&\n    toolOutput.isError\n  ) {\n    return (\n      <div className=\"border-l-2 border-red-400 pl-2\">\n        There was an error when calling the tool {toolCall.name} with input:{' '}\n        <br />\n        {JSON.stringify(toolCall.input)}\n      </div>\n    );\n  }\n\n  // Ensure toolOutput is defined before trying to access output\n  if (toolOutput) {\n    switch (toolCall.name) {\n      case 'get_weather_information':\n        const weatherData = toolOutput.output as unknown as WeatherData;\n        return <WeatherCard data={weatherData} />;\n      default:\n        return null;\n    }\n  }\n\n  return null;\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/codeblock.tsx",
    "content": "\"use client\";\n\nimport { Check, Copy, Download } from \"lucide-react\";\nimport { FC, memo } from \"react\";\nimport { Prism, SyntaxHighlighterProps } from \"react-syntax-highlighter\";\nimport { coldarkDark } from \"react-syntax-highlighter/dist/cjs/styles/prism\";\n\nimport { Button } from \"../../button\";\nimport { useCopyToClipboard } from \"../hooks/use-copy-to-clipboard\";\n\n// TODO: Remove this when @type/react-syntax-highlighter is updated\nconst SyntaxHighlighter = Prism as unknown as FC<SyntaxHighlighterProps>;\n\ninterface Props {\n  language: string;\n  value: string;\n}\n\ninterface languageMap {\n  [key: string]: string | undefined;\n}\n\nexport const programmingLanguages: languageMap = {\n  javascript: \".js\",\n  python: \".py\",\n  java: \".java\",\n  c: \".c\",\n  cpp: \".cpp\",\n  \"c++\": \".cpp\",\n  \"c#\": \".cs\",\n  ruby: \".rb\",\n  php: \".php\",\n  swift: \".swift\",\n  \"objective-c\": \".m\",\n  kotlin: \".kt\",\n  typescript: \".ts\",\n  go: \".go\",\n  perl: \".pl\",\n  rust: \".rs\",\n  scala: \".scala\",\n  haskell: \".hs\",\n  lua: \".lua\",\n  shell: \".sh\",\n  sql: \".sql\",\n  html: \".html\",\n  css: \".css\",\n  // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component\n};\n\nexport const generateRandomString = (length: number, lowercase = false) => {\n  const chars = \"ABCDEFGHJKLMNPQRSTUVWXY3456789\"; // excluding similar looking characters like Z, 2, I, 1, O, 0\n  let result = \"\";\n  for (let i = 0; i < length; i++) {\n    result += chars.charAt(Math.floor(Math.random() * chars.length));\n  }\n  return lowercase ? result.toLowerCase() : result;\n};\n\nconst CodeBlock: FC<Props> = memo(({ language, value }) => {\n  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 });\n\n  const downloadAsFile = () => {\n    if (typeof window === \"undefined\") {\n      return;\n    }\n    const fileExtension = programmingLanguages[language] || \".file\";\n    const suggestedFileName = `file-${generateRandomString(\n      3,\n      true,\n    )}${fileExtension}`;\n    const fileName = window.prompt(\"Enter file name\" || \"\", suggestedFileName);\n\n    if (!fileName) {\n      // User pressed cancel on prompt.\n      return;\n    }\n\n    const blob = new Blob([value], { type: \"text/plain\" });\n    const url = URL.createObjectURL(blob);\n    const link = document.createElement(\"a\");\n    link.download = fileName;\n    link.href = url;\n    link.style.display = \"none\";\n    document.body.appendChild(link);\n    link.click();\n    document.body.removeChild(link);\n    URL.revokeObjectURL(url);\n  };\n\n  const onCopy = () => {\n    if (isCopied) return;\n    copyToClipboard(value);\n  };\n\n  return (\n    <div className=\"codeblock relative w-full bg-zinc-950 font-sans\">\n      <div className=\"flex w-full items-center justify-between bg-zinc-800 px-6 py-2 pr-4 text-zinc-100\">\n        <span className=\"text-xs lowercase\">{language}</span>\n        <div className=\"flex items-center space-x-1\">\n          <Button variant=\"ghost\" onClick={downloadAsFile} size=\"icon\">\n            <Download />\n            <span className=\"sr-only\">Download</span>\n          </Button>\n          <Button variant=\"ghost\" size=\"icon\" onClick={onCopy}>\n            {isCopied ? (\n              <Check className=\"h-4 w-4\" />\n            ) : (\n              <Copy className=\"h-4 w-4\" />\n            )}\n            <span className=\"sr-only\">Copy code</span>\n          </Button>\n        </div>\n      </div>\n      <SyntaxHighlighter\n        language={language}\n        style={coldarkDark}\n        PreTag=\"div\"\n        showLineNumbers\n        customStyle={{\n          width: \"100%\",\n          background: \"transparent\",\n          padding: \"1.5rem 1rem\",\n          borderRadius: \"0.5rem\",\n        }}\n        codeTagProps={{\n          style: {\n            fontSize: \"0.9rem\",\n            fontFamily: \"var(--font-mono)\",\n          },\n        }}\n      >\n        {value}\n      </SyntaxHighlighter>\n    </div>\n  );\n});\nCodeBlock.displayName = \"CodeBlock\";\n\nexport { CodeBlock };\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/index.tsx",
    "content": "import { Check, Copy, Pencil, ThumbsDown, ThumbsUp } from 'lucide-react';\nimport { useEffect, useState } from 'react';\nimport { Message } from 'ai';\nimport { Fragment } from 'react';\nimport { Button } from '../../button';\nimport { useCopyToClipboard } from '../hooks/use-copy-to-clipboard';\nimport {\n  ChatHandler,\n  DocumentFileData,\n  EventData,\n  ImageData,\n  MessageAnnotation,\n  MessageAnnotationType,\n  SourceData,\n  SuggestedQuestionsData,\n  ToolData,\n  getAnnotationData,\n} from '../index';\nimport ChatAvatar from './chat-avatar';\nimport { ChatEvents } from './chat-events';\nimport { ChatFiles } from './chat-files';\nimport { ChatImage } from './chat-image';\nimport { ChatSources } from './chat-sources';\nimport { SuggestedQuestions } from './chat-suggestedQuestions';\nimport ChatTools from './chat-tools';\nimport Markdown from './markdown';\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogHeader,\n  DialogTitle,\n  DialogTrigger,\n} from '@/components/ui/dialog';\n\ntype ContentDisplayConfig = {\n  order: number;\n  component: JSX.Element | null;\n};\n\nfunction ChatMessageContent({\n  message,\n  isLoading,\n  append,\n}: {\n  message: Message;\n  isLoading: boolean;\n  append: Pick<ChatHandler, 'append'>['append'];\n}) {\n  const annotations = message.annotations as MessageAnnotation[] | undefined;\n  if (!annotations?.length) return <Markdown content={message.content} />;\n\n  const imageData = getAnnotationData<ImageData>(\n    annotations,\n    MessageAnnotationType.IMAGE\n  );\n  const contentFileData = getAnnotationData<DocumentFileData>(\n    annotations,\n    MessageAnnotationType.DOCUMENT_FILE\n  );\n  const eventData = getAnnotationData<EventData>(\n    annotations,\n    MessageAnnotationType.EVENTS\n  );\n  const sourceData = getAnnotationData<SourceData>(\n    annotations,\n    MessageAnnotationType.SOURCES\n  );\n  const toolData = getAnnotationData<ToolData>(\n    annotations,\n    MessageAnnotationType.TOOLS\n  );\n  const suggestedQuestionsData = getAnnotationData<SuggestedQuestionsData>(\n    annotations,\n    MessageAnnotationType.SUGGESTED_QUESTIONS\n  );\n\n  const contents: ContentDisplayConfig[] = [\n    {\n      order: 1,\n      component: imageData[0] ? <ChatImage data={imageData[0]} /> : null,\n    },\n    {\n      order: -3,\n      component:\n        eventData.length > 0 ? (\n          <ChatEvents isLoading={isLoading} data={eventData} />\n        ) : null,\n    },\n    {\n      order: 2,\n      component: contentFileData[0] ? (\n        <ChatFiles data={contentFileData[0]} />\n      ) : null,\n    },\n    {\n      order: -1,\n      component: toolData[0] ? <ChatTools data={toolData[0]} /> : null,\n    },\n    {\n      order: 0,\n      component: <Markdown content={message.content} />,\n    },\n    {\n      order: 3,\n      component: sourceData[0] ? <ChatSources data={sourceData[0]} /> : null,\n    },\n    {\n      order: 4,\n      component: suggestedQuestionsData[0] ? (\n        <SuggestedQuestions\n          questions={suggestedQuestionsData[0]}\n          append={append}\n        />\n      ) : null,\n    },\n  ];\n\n  return (\n    <div className=\"flex-1 gap-4 flex flex-col\">\n      {contents\n        .sort((a, b) => a.order - b.order)\n        .map((content, index) => (\n          <Fragment key={index}>{content.component}</Fragment>\n        ))}\n    </div>\n  );\n}\n\nexport default function ChatMessage({\n  chatMessage,\n  isLoading,\n  append,\n  updateMessageContent,\n}: // onSave,\n{\n  chatMessage: Message;\n  isLoading: boolean;\n  append: Pick<ChatHandler, 'append'>['append'];\n  updateMessageContent: (\n    id: string,\n    oldContent: string,\n    newContent: string\n  ) => void;\n  // onSave: (newContent: string) => void; // Add onSave prop\n}) {\n  const [isLiked, setIsLiked] = useState(false);\n  const [isDisliked, setIsDisliked] = useState(false);\n  const [isModalOpen, setIsModalOpen] = useState(false);\n  const [editedContent, setEditedContent] = useState(chatMessage.content);\n  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 });\n\n  const handleSave = () => {\n    console.log(chatMessage.id);\n    console.log('Handling edit');\n    updateMessageContent(chatMessage.id, chatMessage.content, editedContent);\n    // onSave(editedContent); // Use the onSave prop\n    setIsModalOpen(false);\n  };\n  const messageClass = chatMessage.role === 'user' ? 'bg-gray-400/10' : '';\n\n  return (\n    <div\n      className={`flex items-start gap-4 py-5 pl-2 md:pr-5 md:pt-5 md:pb-5 md:pl-4 rounded-md ${messageClass}`}\n    >\n      <ChatAvatar role={chatMessage.role} />\n      <div className=\"group flex flex-1 justify-between gap-2\">\n        <ChatMessageContent\n          message={chatMessage}\n          isLoading={isLoading}\n          append={append}\n        />\n        {chatMessage.role == 'assistant' ? (\n          <>\n            <div className=\"hidden md:flex flex-col h-fit\">\n              <Button\n                onClick={() => copyToClipboard(chatMessage.content)}\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n              >\n                {isCopied ? (\n                  <Check className=\"h-4 w-4\" />\n                ) : (\n                  <Copy className=\"h-4 w-4\" />\n                )}\n              </Button>\n              <Button\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n                onClick={() => setIsLiked(!isLiked)}\n              >\n                {isLiked ? (\n                  <Check className=\"h-4 w-4\" />\n                ) : (\n                  <ThumbsUp className=\"h-4 w-4\" />\n                )}\n              </Button>\n              <Button\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n                onClick={() => setIsDisliked(!isDisliked)}\n              >\n                {isDisliked ? (\n                  <Check className=\"h-4 w-4\" />\n                ) : (\n                  <ThumbsDown className=\"h-4 w-4\" />\n                )}\n              </Button>\n            </div>\n          </>\n        ) : (\n          <>\n            <div className=\"hidden md:flex flex-row h-fit\">\n              {/* <Button\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n                // onClick={() => setIsDisliked(!isDisliked)}\n              >\n                <Pencil className=\"h-4 w-4\" />\n              </Button> */}\n              <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>\n                <DialogTrigger asChild>\n                  <Button\n                    size=\"icon\"\n                    variant=\"ghost\"\n                    className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n                    onClick={() => setIsModalOpen(true)}\n                  >\n                    <Pencil className=\"h-4 w-4\" />\n                  </Button>\n                </DialogTrigger>\n                <DialogContent>\n                  <DialogHeader>\n                    <DialogTitle>Edit Prompt</DialogTitle>\n                    <DialogDescription>\n                      Modify the prompt content below:\n                    </DialogDescription>\n                  </DialogHeader>\n                  <textarea\n                    value={editedContent}\n                    onChange={(e) => setEditedContent(e.target.value)}\n                    className=\"w-full h-32 p-2 border rounded\"\n                  />\n                  <div className=\"flex justify-end mt-4 gap-2\">\n                    <Button onClick={() => setIsModalOpen(false)}>\n                      Cancel\n                    </Button>\n                    <Button onClick={handleSave}>Save</Button>\n                  </div>\n                </DialogContent>\n              </Dialog>\n              <Button\n                onClick={() => copyToClipboard(chatMessage.content)}\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 opacity-0 group-hover:opacity-100\"\n              >\n                {isCopied ? (\n                  <Check className=\"h-4 w-4\" />\n                ) : (\n                  <Copy className=\"h-4 w-4\" />\n                )}\n              </Button>\n            </div>\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-message/markdown.tsx",
    "content": "// import 'katex/dist/katex.min.css';\n// import { FC, memo } from 'react';\n// import ReactMarkdown, { Options } from 'react-markdown';\n// import rehypeKatex from 'rehype-katex';\n// import remarkGfm from 'remark-gfm';\n// import remarkMath from 'remark-math';\n\n// import { CodeBlock } from './codeblock';\n// import Link from 'next/link';\n\n// const MemoizedReactMarkdown: FC<Options> = memo(\n//   ReactMarkdown,\n//   (prevProps, nextProps) =>\n//     prevProps.children === nextProps.children &&\n//     prevProps.className === nextProps.className\n// );\n\n// const preprocessLaTeX = (content: string) => {\n//   // Replace block-level LaTeX delimiters \\[ \\] with $$ $$\n//   const blockProcessedContent = content.replace(\n//     /\\\\\\[([\\s\\S]*?)\\\\\\]/g,\n//     (_, equation) => `$$${equation}$$`\n//   );\n//   // Replace inline LaTeX delimiters \\( \\) with $ $\n//   const inlineProcessedContent = blockProcessedContent.replace(\n//     /\\\\\\[([\\s\\S]*?)\\\\\\]/g,\n//     (_, equation) => `$${equation}$`\n//   );\n//   return inlineProcessedContent;\n// };\n\n// const preprocessMedia = (content: string) => {\n//   // Remove `sandbox:` from the beginning of the URL\n//   // to fix OpenAI's models issue appending `sandbox:` to the relative URL\n//   return content.replace(/(sandbox|attachment|snt):/g, '');\n// };\n\n// const preprocessContent = (content: string) => {\n//   return preprocessMedia(preprocessLaTeX(content));\n// };\n\n// export default function Markdown({ content }: { content: string }) {\n//   const processedContent = preprocessContent(content);\n\n//   return (\n//     <MemoizedReactMarkdown\n//       className=\"prose dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 break-words custom-markdown\"\n//       remarkPlugins={[remarkGfm, remarkMath]}\n//       rehypePlugins={[rehypeKatex as any]}\n//       components={{\n//         p({ children }) {\n//           return <p className=\"mb-2 last:mb-0\">{children}</p>;\n//         },\n\n//         a: ({ children, href, ...props }) => (\n//           <a\n//             href={href}\n//             target=\"_blank\"\n//             className=\"text-blue-400 hover:underline\"\n//             {...props}\n//           >\n//             {children}\n//           </a>\n//         ),\n\n//         code({ node, inline, className, children, ...props }) {\n//           if (children.length) {\n//             if (children[0] == '▍') {\n//               return (\n//                 <span className=\"mt-1 animate-pulse cursor-default\">▍</span>\n//               );\n//             }\n\n//             children[0] = (children[0] as string).replace('`▍`', '▍');\n//           }\n\n//           const match = /language-(\\w+)/.exec(className || '');\n\n//           if (inline) {\n//             return (\n//               <code className={className} {...props}>\n//                 {children}\n//               </code>\n//             );\n//           }\n\n//           return (\n//             <CodeBlock\n//               key={Math.random()}\n//               language={(match && match[1]) || ''}\n//               value={String(children).replace(/\\n$/, '')}\n//               {...props}\n//             />\n//           );\n//         },\n//       }}\n//     >\n//       {processedContent}\n//     </MemoizedReactMarkdown>\n//   );\n// }\n\nimport 'katex/dist/katex.min.css';\nimport { FC, memo } from 'react';\nimport ReactMarkdown, { Options } from 'react-markdown';\nimport rehypeKatex from 'rehype-katex';\nimport remarkGfm from 'remark-gfm';\nimport remarkMath from 'remark-math';\n\nimport { CodeBlock } from './codeblock';\nimport Link from 'next/link';\n\nconst MemoizedReactMarkdown: FC<Options> = memo(\n  ReactMarkdown,\n  (prevProps, nextProps) =>\n    prevProps.children === nextProps.children &&\n    prevProps.className === nextProps.className\n);\n\nconst preprocessLaTeX = (content: string) => {\n  // Replace block-level LaTeX delimiters \\[ \\] with $$ $$\n  let processedContent = content.replace(\n    /\\\\\\[([\\s\\S]*?)\\\\\\]/g,\n    (_, equation) => `$$${equation}$$`\n  );\n  // Replace inline LaTeX delimiters \\( \\) with $ $\n  processedContent = processedContent.replace(\n    /\\\\\\(([\\s\\S]*?)\\\\\\)/g,\n    (_, equation) => `$${equation}$`\n  );\n  // Replace \\begin{equation} and \\end{equation} with $$ $$\n  processedContent = processedContent.replace(\n    /\\\\begin\\{equation\\}([\\s\\S]*?)\\\\end\\{equation\\}/g,\n    (_, equation) => `$$${equation}$$`\n  );\n  // Replace \\begin{align} and \\end{align} with $$ $$\n  processedContent = processedContent.replace(\n    /\\\\begin\\{align\\}([\\s\\S]*?)\\\\end\\{align\\}/g,\n    (_, equation) => `$$\\\\begin{aligned}${equation}\\\\end{aligned}$$`\n  );\n  return processedContent;\n};\n\nconst preprocessMedia = (content: string) => {\n  // Remove `sandbox:`, `attachment:`, and `snt:` from the beginning of URLs\n  return content.replace(/(sandbox|attachment|snt):/g, '');\n};\n\nconst preprocessContent = (content: string) => {\n  return preprocessMedia(preprocessLaTeX(content));\n};\n\nexport default function Markdown({ content }: { content: string }) {\n  const processedContent = preprocessContent(content);\n\n  return (\n    <MemoizedReactMarkdown\n      className=\"prose dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 break-words custom-markdown\"\n      // remarkPlugins={[remarkGfm, remarkMath]}\n      remarkPlugins={[remarkMath]}\n      rehypePlugins={[rehypeKatex as any]}\n      components={{\n        h1({ children }) {\n          return <h1 className=\"text-3xl font-bold mt-6 mb-4\">{children}</h1>;\n        },\n        h2({ children }) {\n          return (\n            <h2 className=\"text-2xl font-semibold mt-5 mb-3\">{children}</h2>\n          );\n        },\n        h3({ children }) {\n          return <h3 className=\"text-xl font-medium mt-4 mb-2\">{children}</h3>;\n        },\n        p({ children }) {\n          return <p className=\"mb-2 last:mb-0\">{children}</p>;\n        },\n        a: ({ children, href, ...props }) => (\n          <a\n            href={href}\n            target=\"_blank\"\n            className=\"text-blue-400 hover:underline\"\n            {...props}\n          >\n            {children}\n          </a>\n        ),\n        // code({ node, inline, className, children, ...props }) {\n        //   if (children.length) {\n        //     if (children[0] == '▍') {\n        //       return (\n        //         <span className=\"mt-1 animate-pulse cursor-default\">▍</span>\n        //       );\n        //     }\n\n        //     children[0] = (children[0] as string).replace('`▍`', '▍');\n        //   }\n\n        //   const match = /language-(\\w+)/.exec(className || '');\n\n        //   if (inline) {\n        //     return (\n        //       <code className={className} {...props}>\n        //         {children}\n        //       </code>\n        //     );\n        //   }\n\n        //   return (\n        //     <CodeBlock\n        //       key={Math.random()}\n        //       language={(match && match[1]) || ''}\n        //       value={String(children).replace(/\\n$/, '')}\n        //       {...props}\n        //     />\n        //   );\n        // },\n        table({ children }) {\n          return (\n            <div className=\"overflow-x-auto\">\n              <table className=\"border-collapse border border-gray-800 dark:border-gray-200\">\n                {children}\n              </table>\n            </div>\n          );\n        },\n        th({ children }) {\n          return (\n            <th className=\"border border-gray-800 dark:border-gray-200 px-4 py-2 bg-gray-100 dark:bg-gray-700\">\n              {children}\n            </th>\n          );\n        },\n        td({ children }) {\n          return (\n            <td className=\"border border-gray-800 dark:border-gray-200 px-4 py-2\">\n              {children}\n            </td>\n          );\n        },\n      }}\n    >\n      {processedContent}\n    </MemoizedReactMarkdown>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat-messages.tsx",
    "content": "'use client';\n\nimport { Loader2 } from 'lucide-react';\nimport { useEffect, useRef, useState } from 'react';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport { Button } from '../button';\nimport ChatActions from './chat-actions';\nimport ChatMessage from './chat-message';\nimport { ChatHandler } from './chat.interface';\nimport { useClientConfig } from './hooks/use-config';\nimport Image from 'next/image';\nimport BannerCard from '@/components/banner-card';\n\nexport default function ChatMessages(\n  props: Pick<\n    ChatHandler,\n    | 'messages'\n    | 'isLoading'\n    | 'reload'\n    | 'stop'\n    | 'append'\n    | 'updateMessageContent'\n  >\n) {\n  const { starterQuestions } = useClientConfig();\n  const scrollableChatContainerRef = useRef<HTMLDivElement>(null);\n  const messageLength = props.messages.length;\n  const lastMessage = props.messages[messageLength - 1];\n  const [isMobile, setIsMobile] = useState(false);\n  const scrollToBottom = () => {\n    if (scrollableChatContainerRef.current) {\n      scrollableChatContainerRef.current.scrollTop =\n        scrollableChatContainerRef.current.scrollHeight;\n    }\n  };\n\n  const isLastMessageFromAssistant =\n    messageLength > 0 && lastMessage?.role !== 'user';\n  const showReload =\n    props.reload && !props.isLoading && isLastMessageFromAssistant;\n  const showStop = props.stop && props.isLoading;\n\n  // `isPending` indicate\n  // that stream response is not yet received from the server,\n  // so we show a loading indicator to give a better UX.\n  const isPending = props.isLoading && !isLastMessageFromAssistant;\n\n  useEffect(() => {\n    scrollToBottom();\n  }, [messageLength, lastMessage]);\n  useEffect(() => {\n    const checkMobile = () => {\n      setIsMobile(window.innerWidth <= 768); // Adjust this breakpoint as needed\n    };\n\n    checkMobile();\n    window.addEventListener('resize', checkMobile);\n\n    return () => window.removeEventListener('resize', checkMobile);\n  }, []);\n  return (\n    <ScrollArea className=\"w-full h-full relative\">\n      <div className=\"flex flex-col h-full \">\n        <div\n          className=\"flex-1 w-full md:p-4 relative overflow-y-auto \"\n          ref={scrollableChatContainerRef}\n        >\n          {!messageLength && (\n            <div className=\"flex-1 flex justify-center items-center\">\n              <BannerCard />\n            </div>\n          )}\n          <div className=\"flex flex-col divide-y\">\n            {props.messages.map((m, i) => {\n              const isLoadingMessage =\n                i === messageLength - 1 && props.isLoading;\n              return (\n                <ChatMessage\n                  key={m.id}\n                  chatMessage={m}\n                  isLoading={isLoadingMessage}\n                  append={props.append!}\n                  updateMessageContent={props.updateMessageContent!}\n                />\n              );\n            })}\n            {isPending && (\n              <div className=\"flex justify-center items-center pt-10\">\n                <Loader2 className=\"h-4 w-4 animate-spin\" />\n              </div>\n            )}\n          </div>\n          {(showReload || showStop) && (\n            <div className=\"flex justify-end py-4\">\n              <ChatActions\n                reload={props.reload}\n                stop={props.stop}\n                showReload={showReload}\n                showStop={showStop}\n              />\n            </div>\n          )}\n        </div>\n\n        {!messageLength && starterQuestions?.length && props.append && (\n          <div className=\"w-full mt-auto p-6\">\n            <div\n              className={`grid gap-4 max-w-full ${\n                isMobile ? 'grid-cols-1' : 'grid-cols-2'\n              }`}\n            >\n              {starterQuestions.slice(0, 4).map((question, i) => (\n                <Button\n                  key={i}\n                  onClick={() =>\n                    props.append!({ role: 'user', content: question })\n                  }\n                  className=\"w-full whitespace-normal p-4 h-auto min-h-[70px] rounded-xl text-md font-medium transition-all bg-background text-muted-foreground hover:bg-muted-foreground hover:text-primary-foreground border-2 border-slate-500/10\"\n                >\n                  {question}\n                </Button>\n              ))}\n            </div>\n          </div>\n        )}\n      </div>\n    </ScrollArea>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/chat.interface.ts",
    "content": "import { Message } from 'ai';\n\nexport interface ChatHandler {\n  messages: Message[];\n  input: string;\n  isLoading: boolean;\n  handleSubmit: (\n    e: React.FormEvent<HTMLFormElement>,\n    ops?: {\n      data?: any;\n    }\n  ) => void;\n  handleInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n  reload?: () => void;\n  stop?: () => void;\n  onFileUpload?: (file: File) => Promise<void>;\n  onFileError?: (errMsg: string) => void;\n  setInput?: (input: string) => void;\n  append?: (\n    message: Message | Omit<Message, 'id'>,\n    ops?: {\n      data: any;\n    }\n  ) => Promise<string | null | undefined>;\n  updateMessageContent?: (\n    id: string,\n    oldContent: string,\n    newContent: string\n  ) => void;\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/hooks/use-config.ts",
    "content": "// \"use client\";\n\n// import { useEffect, useMemo, useState } from \"react\";\n\n// export interface ChatConfig {\n//   backend?: string;\n//   starterQuestions?: string[];\n// }\n\n// export function useClientConfig(): ChatConfig {\n//   const chatAPI = process.env.NEXT_PUBLIC_CHAT_API;\n//   const [config, setConfig] = useState<ChatConfig>();\n\n//   const backendOrigin = useMemo(() => {\n//     return chatAPI ? new URL(chatAPI).origin : \"\";\n//   }, [chatAPI]);\n\n//   const configAPI = `${backendOrigin}/api/chat/config`;\n\n//   useEffect(() => {\n//     fetch(configAPI)\n//       .then((response) => response.json())\n//       .then((data) => setConfig({ ...data, chatAPI }))\n//       .catch((error) => console.error(\"Error fetching config\", error));\n//   }, [chatAPI, configAPI]);\n\n//   return {\n//     backend: backendOrigin,\n//     starterQuestions: config?.starterQuestions,\n//   };\n// }\n\n'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { useAuth } from '@/app/authProvider'; // Make sure to import useAuth from your AuthContext\nimport { useRouter } from 'next/navigation';\n\nexport interface ChatConfig {\n  backend?: string;\n  starterQuestions?: string[];\n}\n\nexport function useClientConfig(): ChatConfig {\n  const chatAPI = process.env.NEXT_PUBLIC_CHAT_API;\n  const [config, setConfig] = useState<ChatConfig>();\n  const { accessToken } = useAuth(); // Get the access token from the auth context\n  const router = useRouter();\n  const backendOrigin = useMemo(() => {\n    return chatAPI ? new URL(chatAPI).origin : '';\n  }, [chatAPI]);\n\n  const configAPI = `${backendOrigin}/api/chat/config`;\n\n  useEffect(() => {\n    if (!accessToken) return; // Don't fetch if there's no access token\n\n    fetch(configAPI, {\n      headers: {\n        Authorization: `Bearer ${accessToken}`, // Include the access token in the request\n      },\n    })\n      .then((response) => {\n        if (!response.ok) {\n          throw new Error('Network response was not ok');\n        }\n        return response.json();\n      })\n      .then((data) => setConfig({ ...data, chatAPI }))\n      .catch((error) => console.error('Error fetching config', error))\n      .catch((error) => {\n        router.push(`/signin`);\n      });\n  }, [chatAPI, configAPI, accessToken]);\n\n  return {\n    backend: backendOrigin,\n    starterQuestions: config?.starterQuestions,\n  };\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/hooks/use-copy-to-clipboard.tsx",
    "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface useCopyToClipboardProps {\n  timeout?: number;\n}\n\nexport function useCopyToClipboard({\n  timeout = 2000,\n}: useCopyToClipboardProps) {\n  const [isCopied, setIsCopied] = React.useState<Boolean>(false);\n\n  const copyToClipboard = (value: string) => {\n    if (typeof window === \"undefined\" || !navigator.clipboard?.writeText) {\n      return;\n    }\n\n    if (!value) {\n      return;\n    }\n\n    navigator.clipboard.writeText(value).then(() => {\n      setIsCopied(true);\n\n      setTimeout(() => {\n        setIsCopied(false);\n      }, timeout);\n    });\n  };\n\n  return { isCopied, copyToClipboard };\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/hooks/use-file.ts",
    "content": "'use client';\n\nimport { JSONValue } from 'llamaindex';\nimport { useState } from 'react';\nimport { v4 as uuidv4 } from 'uuid';\nimport {\n  DocumentFile,\n  DocumentFileType,\n  MessageAnnotation,\n  MessageAnnotationType,\n} from '..';\nimport { useClientConfig } from './use-config';\nimport { useAuth } from '@/app/authProvider';\n\nconst docMineTypeMap: Record<string, DocumentFileType> = {\n  'text/csv': 'csv',\n  'application/pdf': 'pdf',\n  'text/plain': 'txt',\n  'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n    'docx',\n};\n\nexport function useFile() {\n  const { backend } = useClientConfig();\n  const [imageUrl, setImageUrl] = useState<string | null>(null);\n  const [files, setFiles] = useState<DocumentFile[]>([]);\n  const { accessToken } = useAuth();\n\n  const docEqual = (a: DocumentFile, b: DocumentFile) => {\n    if (a.id === b.id) return true;\n    if (a.filename === b.filename && a.filesize === b.filesize) return true;\n    return false;\n  };\n\n  const addDoc = (file: DocumentFile) => {\n    const existedFile = files.find((f) => docEqual(f, file));\n    if (!existedFile) {\n      setFiles((prev) => [...prev, file]);\n      return true;\n    }\n    return false;\n  };\n\n  const removeDoc = (file: DocumentFile) => {\n    setFiles((prev) => prev.filter((f) => f.id !== file.id));\n  };\n\n  const reset = () => {\n    imageUrl && setImageUrl(null);\n    files.length && setFiles([]);\n  };\n\n  const uploadContent = async (\n    base64: string,\n    requestParams: any = {}\n  ): Promise<string[]> => {\n    const uploadAPI = `${backend}/api/chat/upload`;\n    const response = await fetch(uploadAPI, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${accessToken}`, // Include the access token\n      },\n      body: JSON.stringify({\n        base64,\n        ...requestParams,\n      }),\n    });\n    if (!response.ok) throw new Error('Failed to upload document.');\n    return await response.json();\n  };\n\n  const getAnnotations = () => {\n    const annotations: MessageAnnotation[] = [];\n    if (imageUrl) {\n      annotations.push({\n        type: MessageAnnotationType.IMAGE,\n        data: { url: imageUrl },\n      });\n    }\n    if (files.length > 0) {\n      annotations.push({\n        type: MessageAnnotationType.DOCUMENT_FILE,\n        data: { files },\n      });\n    }\n    return annotations as JSONValue[];\n  };\n\n  const readContent = async (input: {\n    file: File;\n    asUrl?: boolean;\n  }): Promise<string> => {\n    const { file, asUrl } = input;\n    const content = await new Promise<string>((resolve, reject) => {\n      const reader = new FileReader();\n      if (asUrl) {\n        reader.readAsDataURL(file);\n      } else {\n        reader.readAsText(file);\n      }\n      reader.onload = () => resolve(reader.result as string);\n      reader.onerror = (error) => reject(error);\n    });\n    return content;\n  };\n\n  const uploadFile = async (file: File, requestParams: any = {}) => {\n    if (file.type.startsWith('image/')) {\n      const base64 = await readContent({ file, asUrl: true });\n      return setImageUrl(base64);\n    }\n\n    const filetype = docMineTypeMap[file.type];\n    if (!filetype) throw new Error('Unsupported document type.');\n    const newDoc: Omit<DocumentFile, 'content'> = {\n      id: uuidv4(),\n      filetype,\n      filename: file.name,\n      filesize: file.size,\n    };\n    switch (file.type) {\n      case 'text/csv': {\n        const content = await readContent({ file });\n        return addDoc({\n          ...newDoc,\n          content: {\n            type: 'text',\n            value: content,\n          },\n        });\n      }\n      default: {\n        const base64 = await readContent({ file, asUrl: true });\n        const ids = await uploadContent(base64, requestParams);\n        return addDoc({\n          ...newDoc,\n          content: {\n            type: 'ref',\n            value: ids,\n          },\n        });\n      }\n    }\n  };\n\n  return {\n    imageUrl,\n    setImageUrl,\n    files,\n    removeDoc,\n    reset,\n    getAnnotations,\n    uploadFile,\n  };\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/index.ts",
    "content": "import { JSONValue } from \"ai\";\nimport ChatInput from \"./chat-input\";\nimport ChatMessages from \"./chat-messages\";\n\nexport { type ChatHandler } from \"./chat.interface\";\nexport { ChatInput, ChatMessages };\n\nexport enum MessageAnnotationType {\n  IMAGE = \"image\",\n  DOCUMENT_FILE = \"document_file\",\n  SOURCES = \"sources\",\n  EVENTS = \"events\",\n  TOOLS = \"tools\",\n  SUGGESTED_QUESTIONS = \"suggested_questions\",\n}\n\nexport type ImageData = {\n  url: string;\n};\n\nexport type DocumentFileType = \"csv\" | \"pdf\" | \"txt\" | \"docx\";\n\nexport type DocumentFileContent = {\n  type: \"ref\" | \"text\";\n  value: string[] | string;\n};\n\nexport type DocumentFile = {\n  id: string;\n  filename: string;\n  filesize: number;\n  filetype: DocumentFileType;\n  content: DocumentFileContent;\n};\n\nexport type DocumentFileData = {\n  files: DocumentFile[];\n};\n\nexport type SourceNode = {\n  id: string;\n  metadata: Record<string, unknown>;\n  score?: number;\n  text: string;\n  url?: string;\n};\n\nexport type SourceData = {\n  nodes: SourceNode[];\n};\n\nexport type EventData = {\n  title: string;\n  isCollapsed: boolean;\n};\n\nexport type ToolData = {\n  toolCall: {\n    id: string;\n    name: string;\n    input: {\n      [key: string]: JSONValue;\n    };\n  };\n  toolOutput: {\n    output: JSONValue;\n    isError: boolean;\n  };\n};\n\nexport type SuggestedQuestionsData = string[];\n\nexport type AnnotationData =\n  | ImageData\n  | DocumentFileData\n  | SourceData\n  | EventData\n  | ToolData\n  | SuggestedQuestionsData;\n\nexport type MessageAnnotation = {\n  type: MessageAnnotationType;\n  data: AnnotationData;\n};\n\nexport function getAnnotationData<T extends AnnotationData>(\n  annotations: MessageAnnotation[],\n  type: MessageAnnotationType,\n): T[] {\n  return annotations.filter((a) => a.type === type).map((a) => a.data as T);\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/widgets/PdfDialog.tsx",
    "content": "import dynamic from 'next/dynamic';\nimport { Button } from '../../button';\nimport {\n  Drawer,\n  DrawerClose,\n  DrawerContent,\n  DrawerDescription,\n  DrawerHeader,\n  DrawerTitle,\n  DrawerTrigger,\n} from '../../drawer';\n\nexport interface PdfDialogProps {\n  documentId: string;\n  url: string;\n  trigger: React.ReactNode;\n}\n\n// Dynamic imports for client-side rendering only\nconst PDFViewer = dynamic(\n  () => import('@llamaindex/pdf-viewer').then((module) => module.PDFViewer),\n  { ssr: false }\n);\n\nconst PdfFocusProvider = dynamic(\n  () =>\n    import('@llamaindex/pdf-viewer').then((module) => module.PdfFocusProvider),\n  { ssr: false }\n);\n\nexport default function PdfDialog(props: PdfDialogProps) {\n  return (\n    <Drawer direction=\"left\">\n      <DrawerTrigger>{props.trigger}</DrawerTrigger>\n      <DrawerContent className=\"w-3/5 mt-24 h-full max-h-[96%] \">\n        <DrawerHeader className=\"flex justify-between\">\n          <div className=\"space-y-2\">\n            <DrawerTitle>PDF Content</DrawerTitle>\n            <DrawerDescription>\n              File URL:{' '}\n              <a\n                className=\"hover:text-blue-900\"\n                href={props.url}\n                target=\"_blank\"\n              >\n                {props.url}\n              </a>\n            </DrawerDescription>\n          </div>\n          <DrawerClose asChild>\n            <Button variant=\"outline\">Close</Button>\n          </DrawerClose>\n        </DrawerHeader>\n        <div className=\"m-4\">\n          <PdfFocusProvider>\n            <PDFViewer\n              file={{\n                id: props.url,\n                url: props.url,\n              }}\n            />\n          </PdfFocusProvider>\n        </div>\n      </DrawerContent>\n    </Drawer>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/chat/widgets/WeatherCard.tsx",
    "content": "export interface WeatherData {\n  latitude: number;\n  longitude: number;\n  generationtime_ms: number;\n  utc_offset_seconds: number;\n  timezone: string;\n  timezone_abbreviation: string;\n  elevation: number;\n  current_units: {\n    time: string;\n    interval: string;\n    temperature_2m: string;\n    weather_code: string;\n  };\n  current: {\n    time: string;\n    interval: number;\n    temperature_2m: number;\n    weather_code: number;\n  };\n  hourly_units: {\n    time: string;\n    temperature_2m: string;\n    weather_code: string;\n  };\n  hourly: {\n    time: string[];\n    temperature_2m: number[];\n    weather_code: number[];\n  };\n  daily_units: {\n    time: string;\n    weather_code: string;\n  };\n  daily: {\n    time: string[];\n    weather_code: number[];\n  };\n}\n\n// Follow WMO Weather interpretation codes (WW)\nconst weatherCodeDisplayMap: Record<\n  string,\n  {\n    icon: JSX.Element;\n    status: string;\n  }\n> = {\n  \"0\": {\n    icon: <span>☀️</span>,\n    status: \"Clear sky\",\n  },\n  \"1\": {\n    icon: <span>🌤️</span>,\n    status: \"Mainly clear\",\n  },\n  \"2\": {\n    icon: <span>☁️</span>,\n    status: \"Partly cloudy\",\n  },\n  \"3\": {\n    icon: <span>☁️</span>,\n    status: \"Overcast\",\n  },\n  \"45\": {\n    icon: <span>🌫️</span>,\n    status: \"Fog\",\n  },\n  \"48\": {\n    icon: <span>🌫️</span>,\n    status: \"Depositing rime fog\",\n  },\n  \"51\": {\n    icon: <span>🌧️</span>,\n    status: \"Drizzle\",\n  },\n  \"53\": {\n    icon: <span>🌧️</span>,\n    status: \"Drizzle\",\n  },\n  \"55\": {\n    icon: <span>🌧️</span>,\n    status: \"Drizzle\",\n  },\n  \"56\": {\n    icon: <span>🌧️</span>,\n    status: \"Freezing Drizzle\",\n  },\n  \"57\": {\n    icon: <span>🌧️</span>,\n    status: \"Freezing Drizzle\",\n  },\n  \"61\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain\",\n  },\n  \"63\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain\",\n  },\n  \"65\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain\",\n  },\n  \"66\": {\n    icon: <span>🌧️</span>,\n    status: \"Freezing Rain\",\n  },\n  \"67\": {\n    icon: <span>🌧️</span>,\n    status: \"Freezing Rain\",\n  },\n  \"71\": {\n    icon: <span>❄️</span>,\n    status: \"Snow fall\",\n  },\n  \"73\": {\n    icon: <span>❄️</span>,\n    status: \"Snow fall\",\n  },\n  \"75\": {\n    icon: <span>❄️</span>,\n    status: \"Snow fall\",\n  },\n  \"77\": {\n    icon: <span>❄️</span>,\n    status: \"Snow grains\",\n  },\n  \"80\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain showers\",\n  },\n  \"81\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain showers\",\n  },\n  \"82\": {\n    icon: <span>🌧️</span>,\n    status: \"Rain showers\",\n  },\n  \"85\": {\n    icon: <span>❄️</span>,\n    status: \"Snow showers\",\n  },\n  \"86\": {\n    icon: <span>❄️</span>,\n    status: \"Snow showers\",\n  },\n  \"95\": {\n    icon: <span>⛈️</span>,\n    status: \"Thunderstorm\",\n  },\n  \"96\": {\n    icon: <span>⛈️</span>,\n    status: \"Thunderstorm\",\n  },\n  \"99\": {\n    icon: <span>⛈️</span>,\n    status: \"Thunderstorm\",\n  },\n};\n\nconst displayDay = (time: string) => {\n  return new Date(time).toLocaleDateString(\"en-US\", {\n    weekday: \"long\",\n  });\n};\n\nexport function WeatherCard({ data }: { data: WeatherData }) {\n  const currentDayString = new Date(data.current.time).toLocaleDateString(\n    \"en-US\",\n    {\n      weekday: \"long\",\n      month: \"long\",\n      day: \"numeric\",\n    },\n  );\n\n  return (\n    <div className=\"bg-[#61B9F2] rounded-2xl shadow-xl p-5 space-y-4 text-white w-fit\">\n      <div className=\"flex justify-between\">\n        <div className=\"space-y-2\">\n          <div className=\"text-xl\">{currentDayString}</div>\n          <div className=\"text-5xl font-semibold flex gap-4\">\n            <span>\n              {data.current.temperature_2m} {data.current_units.temperature_2m}\n            </span>\n            {weatherCodeDisplayMap[data.current.weather_code].icon}\n          </div>\n        </div>\n        <span className=\"text-xl\">\n          {weatherCodeDisplayMap[data.current.weather_code].status}\n        </span>\n      </div>\n      <div className=\"gap-2 grid grid-cols-6\">\n        {data.daily.time.map((time, index) => {\n          if (index === 0) return null; // skip the current day\n          return (\n            <div key={time} className=\"flex flex-col items-center gap-4\">\n              <span>{displayDay(time)}</span>\n              <div className=\"text-4xl\">\n                {weatherCodeDisplayMap[data.daily.weather_code[index]].icon}\n              </div>\n              <span className=\"text-sm\">\n                {weatherCodeDisplayMap[data.daily.weather_code[index]].status}\n              </span>\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/checkbox.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as CheckboxPrimitive from \"@radix-ui/react-checkbox\"\nimport { Check } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Checkbox = React.forwardRef<\n  React.ElementRef<typeof CheckboxPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <CheckboxPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground\",\n      className\n    )}\n    {...props}\n  >\n    <CheckboxPrimitive.Indicator\n      className={cn(\"flex items-center justify-center text-current\")}\n    >\n      <Check className=\"h-4 w-4\" />\n    </CheckboxPrimitive.Indicator>\n  </CheckboxPrimitive.Root>\n))\nCheckbox.displayName = CheckboxPrimitive.Root.displayName\n\nexport { Checkbox }\n"
  },
  {
    "path": "frontend/components/ui/collapsible.tsx",
    "content": "\"use client\"\n\nimport * as CollapsiblePrimitive from \"@radix-ui/react-collapsible\"\n\nconst Collapsible = CollapsiblePrimitive.Root\n\nconst CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger\n\nconst CollapsibleContent = CollapsiblePrimitive.CollapsibleContent\n\nexport { Collapsible, CollapsibleTrigger, CollapsibleContent }\n"
  },
  {
    "path": "frontend/components/ui/command.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { type DialogProps } from \"@radix-ui/react-dialog\"\nimport { Command as CommandPrimitive } from \"cmdk\"\nimport { Search } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Dialog, DialogContent } from \"@/components/ui/dialog\"\n\nconst Command = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive\n    ref={ref}\n    className={cn(\n      \"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground\",\n      className\n    )}\n    {...props}\n  />\n))\nCommand.displayName = CommandPrimitive.displayName\n\ninterface CommandDialogProps extends DialogProps {}\n\nconst CommandDialog = ({ children, ...props }: CommandDialogProps) => {\n  return (\n    <Dialog {...props}>\n      <DialogContent className=\"overflow-hidden p-0 shadow-lg\">\n        <Command className=\"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5\">\n          {children}\n        </Command>\n      </DialogContent>\n    </Dialog>\n  )\n}\n\nconst CommandInput = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Input>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>\n>(({ className, ...props }, ref) => (\n  <div className=\"flex items-center border-b px-3\" cmdk-input-wrapper=\"\">\n    <Search className=\"mr-2 h-4 w-4 shrink-0 opacity-50\" />\n    <CommandPrimitive.Input\n      ref={ref}\n      className={cn(\n        \"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50\",\n        className\n      )}\n      {...props}\n    />\n  </div>\n))\n\nCommandInput.displayName = CommandPrimitive.Input.displayName\n\nconst CommandList = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.List\n    ref={ref}\n    className={cn(\"max-h-[300px] overflow-y-auto overflow-x-hidden\", className)}\n    {...props}\n  />\n))\n\nCommandList.displayName = CommandPrimitive.List.displayName\n\nconst CommandEmpty = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Empty>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>\n>((props, ref) => (\n  <CommandPrimitive.Empty\n    ref={ref}\n    className=\"py-6 text-center text-sm\"\n    {...props}\n  />\n))\n\nCommandEmpty.displayName = CommandPrimitive.Empty.displayName\n\nconst CommandGroup = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Group>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Group\n    ref={ref}\n    className={cn(\n      \"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground\",\n      className\n    )}\n    {...props}\n  />\n))\n\nCommandGroup.displayName = CommandPrimitive.Group.displayName\n\nconst CommandSeparator = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 h-px bg-border\", className)}\n    {...props}\n  />\n))\nCommandSeparator.displayName = CommandPrimitive.Separator.displayName\n\nconst CommandItem = React.forwardRef<\n  React.ElementRef<typeof CommandPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>\n>(({ className, ...props }, ref) => (\n  <CommandPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50\",\n      className\n    )}\n    {...props}\n  />\n))\n\nCommandItem.displayName = CommandPrimitive.Item.displayName\n\nconst CommandShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\n        \"ml-auto text-xs tracking-widest text-muted-foreground\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\nCommandShortcut.displayName = \"CommandShortcut\"\n\nexport {\n  Command,\n  CommandDialog,\n  CommandInput,\n  CommandList,\n  CommandEmpty,\n  CommandGroup,\n  CommandItem,\n  CommandShortcut,\n  CommandSeparator,\n}\n"
  },
  {
    "path": "frontend/components/ui/context-menu.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as ContextMenuPrimitive from \"@radix-ui/react-context-menu\"\nimport { Check, ChevronRight, Circle } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst ContextMenu = ContextMenuPrimitive.Root\n\nconst ContextMenuTrigger = ContextMenuPrimitive.Trigger\n\nconst ContextMenuGroup = ContextMenuPrimitive.Group\n\nconst ContextMenuPortal = ContextMenuPrimitive.Portal\n\nconst ContextMenuSub = ContextMenuPrimitive.Sub\n\nconst ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup\n\nconst ContextMenuSubTrigger = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {\n    inset?: boolean\n  }\n>(({ className, inset, children, ...props }, ref) => (\n  <ContextMenuPrimitive.SubTrigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <ChevronRight className=\"ml-auto h-4 w-4\" />\n  </ContextMenuPrimitive.SubTrigger>\n))\nContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName\n\nconst ContextMenuSubContent = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.SubContent>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>\n>(({ className, ...props }, ref) => (\n  <ContextMenuPrimitive.SubContent\n    ref={ref}\n    className={cn(\n      \"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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))\nContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName\n\nconst ContextMenuContent = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <ContextMenuPrimitive.Portal>\n    <ContextMenuPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 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  </ContextMenuPrimitive.Portal>\n))\nContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName\n\nconst ContextMenuItem = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <ContextMenuPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName\n\nconst ContextMenuCheckboxItem = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>\n>(({ className, children, checked, ...props }, ref) => (\n  <ContextMenuPrimitive.CheckboxItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    checked={checked}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <ContextMenuPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </ContextMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </ContextMenuPrimitive.CheckboxItem>\n))\nContextMenuCheckboxItem.displayName =\n  ContextMenuPrimitive.CheckboxItem.displayName\n\nconst ContextMenuRadioItem = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>\n>(({ className, children, ...props }, ref) => (\n  <ContextMenuPrimitive.RadioItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <ContextMenuPrimitive.ItemIndicator>\n        <Circle className=\"h-2 w-2 fill-current\" />\n      </ContextMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </ContextMenuPrimitive.RadioItem>\n))\nContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName\n\nconst ContextMenuLabel = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <ContextMenuPrimitive.Label\n    ref={ref}\n    className={cn(\n      \"px-2 py-1.5 text-sm font-semibold text-foreground\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName\n\nconst ContextMenuSeparator = React.forwardRef<\n  React.ElementRef<typeof ContextMenuPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <ContextMenuPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-border\", className)}\n    {...props}\n  />\n))\nContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName\n\nconst ContextMenuShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\n        \"ml-auto text-xs tracking-widest text-muted-foreground\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\nContextMenuShortcut.displayName = \"ContextMenuShortcut\"\n\nexport {\n  ContextMenu,\n  ContextMenuTrigger,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuCheckboxItem,\n  ContextMenuRadioItem,\n  ContextMenuLabel,\n  ContextMenuSeparator,\n  ContextMenuShortcut,\n  ContextMenuGroup,\n  ContextMenuPortal,\n  ContextMenuSub,\n  ContextMenuSubContent,\n  ContextMenuSubTrigger,\n  ContextMenuRadioGroup,\n}\n"
  },
  {
    "path": "frontend/components/ui/dialog.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { X } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Dialog = DialogPrimitive.Root\n\nconst DialogTrigger = DialogPrimitive.Trigger\n\nconst DialogPortal = DialogPrimitive.Portal\n\nconst DialogClose = DialogPrimitive.Close\n\nconst DialogOverlay = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Overlay\n    ref={ref}\n    className={cn(\n      \"fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName\n\nconst DialogContent = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <DialogPortal>\n    <DialogOverlay />\n    <DialogPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n      <DialogPrimitive.Close className=\"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground\">\n        <X className=\"h-4 w-4\" />\n        <span className=\"sr-only\">Close</span>\n      </DialogPrimitive.Close>\n    </DialogPrimitive.Content>\n  </DialogPortal>\n))\nDialogContent.displayName = DialogPrimitive.Content.displayName\n\nconst DialogHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-1.5 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogHeader.displayName = \"DialogHeader\"\n\nconst DialogFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogFooter.displayName = \"DialogFooter\"\n\nconst DialogTitle = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Title\n    ref={ref}\n    className={cn(\n      \"text-lg font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogTitle.displayName = DialogPrimitive.Title.displayName\n\nconst DialogDescription = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nDialogDescription.displayName = DialogPrimitive.Description.displayName\n\nexport {\n  Dialog,\n  DialogPortal,\n  DialogOverlay,\n  DialogClose,\n  DialogTrigger,\n  DialogContent,\n  DialogHeader,\n  DialogFooter,\n  DialogTitle,\n  DialogDescription,\n}\n"
  },
  {
    "path": "frontend/components/ui/document-preview.tsx",
    "content": "import { XCircleIcon } from \"lucide-react\";\nimport Image from \"next/image\";\nimport DocxIcon from \"../ui/icons/docx.svg\";\nimport PdfIcon from \"../ui/icons/pdf.svg\";\nimport SheetIcon from \"../ui/icons/sheet.svg\";\nimport TxtIcon from \"../ui/icons/txt.svg\";\nimport { Button } from \"./button\";\nimport { DocumentFile, DocumentFileType } from \"./chat\";\nimport {\n  Drawer,\n  DrawerClose,\n  DrawerContent,\n  DrawerDescription,\n  DrawerHeader,\n  DrawerTitle,\n  DrawerTrigger,\n} from \"./drawer\";\nimport { cn } from \"../../lib/utils\";\n\nexport interface DocumentPreviewProps {\n  file: DocumentFile;\n  onRemove?: () => void;\n}\n\nexport function DocumentPreview(props: DocumentPreviewProps) {\n  const { filename, filesize, content, filetype } = props.file;\n\n  if (content.type === \"ref\") {\n    return (\n      <div title={`Document IDs: ${(content.value as string[]).join(\", \")}`}>\n        <PreviewCard {...props} />\n      </div>\n    );\n  }\n\n  return (\n    <Drawer direction=\"left\">\n      <DrawerTrigger asChild>\n        <div>\n          <PreviewCard {...props} />\n        </div>\n      </DrawerTrigger>\n      <DrawerContent className=\"w-3/5 mt-24 h-full max-h-[96%] \">\n        <DrawerHeader className=\"flex justify-between\">\n          <div className=\"space-y-2\">\n            <DrawerTitle>{filetype.toUpperCase()} Raw Content</DrawerTitle>\n            <DrawerDescription>\n              {filename} ({inKB(filesize)} KB)\n            </DrawerDescription>\n          </div>\n          <DrawerClose asChild>\n            <Button variant=\"outline\">Close</Button>\n          </DrawerClose>\n        </DrawerHeader>\n        <div className=\"m-4 max-h-[80%] overflow-auto\">\n          {content.type === \"text\" && (\n            <pre className=\"bg-secondary rounded-md p-4 block text-sm\">\n              {content.value as string}\n            </pre>\n          )}\n        </div>\n      </DrawerContent>\n    </Drawer>\n  );\n}\n\nconst FileIcon: Record<DocumentFileType, string> = {\n  csv: SheetIcon,\n  pdf: PdfIcon,\n  docx: DocxIcon,\n  txt: TxtIcon,\n};\n\nfunction PreviewCard(props: DocumentPreviewProps) {\n  const { onRemove, file } = props;\n  return (\n    <div\n      className={cn(\n        \"p-2 w-60 max-w-60 bg-secondary rounded-lg text-sm relative\",\n        file.content.type === \"ref\" ? \"\" : \"cursor-pointer\"\n      )}\n    >\n      <div className=\"flex flex-row items-center gap-2\">\n        <div className=\"relative h-8 w-8 shrink-0 overflow-hidden rounded-md\">\n          <Image\n            className=\"h-full w-auto\"\n            priority\n            src={FileIcon[file.filetype]}\n            alt=\"Icon\"\n          />\n        </div>\n        <div className=\"overflow-hidden\">\n          <div className=\"truncate font-semibold\">\n            {file.filename} ({inKB(file.filesize)} KB)\n          </div>\n          <div className=\"truncate text-token-text-tertiary flex items-center gap-2\">\n            <span>{file.filetype.toUpperCase()} File</span>\n          </div>\n        </div>\n      </div>\n      {onRemove && (\n        <div\n          className={cn(\n            \"absolute -top-2 -right-2 w-6 h-6 z-10 bg-gray-500 text-white rounded-full\"\n          )}\n        >\n          <XCircleIcon\n            className=\"w-6 h-6 bg-gray-500 text-white rounded-full\"\n            onClick={onRemove}\n          />\n        </div>\n      )}\n    </div>\n  );\n}\n\nfunction inKB(size: number) {\n  return Math.round((size / 1024) * 10) / 10;\n}\n"
  },
  {
    "path": "frontend/components/ui/drawer.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Drawer as DrawerPrimitive } from \"vaul\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Drawer = ({\n  shouldScaleBackground = true,\n  ...props\n}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (\n  <DrawerPrimitive.Root\n    shouldScaleBackground={shouldScaleBackground}\n    {...props}\n  />\n)\nDrawer.displayName = \"Drawer\"\n\nconst DrawerTrigger = DrawerPrimitive.Trigger\n\nconst DrawerPortal = DrawerPrimitive.Portal\n\nconst DrawerClose = DrawerPrimitive.Close\n\nconst DrawerOverlay = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Overlay\n    ref={ref}\n    className={cn(\"fixed inset-0 z-50 bg-black/80\", className)}\n    {...props}\n  />\n))\nDrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName\n\nconst DrawerContent = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <DrawerPortal>\n    <DrawerOverlay />\n    <DrawerPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background\",\n        className\n      )}\n      {...props}\n    >\n      <div className=\"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted\" />\n      {children}\n    </DrawerPrimitive.Content>\n  </DrawerPortal>\n))\nDrawerContent.displayName = \"DrawerContent\"\n\nconst DrawerHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\"grid gap-1.5 p-4 text-center sm:text-left\", className)}\n    {...props}\n  />\n)\nDrawerHeader.displayName = \"DrawerHeader\"\n\nconst DrawerFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\"mt-auto flex flex-col gap-2 p-4\", className)}\n    {...props}\n  />\n)\nDrawerFooter.displayName = \"DrawerFooter\"\n\nconst DrawerTitle = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Title\n    ref={ref}\n    className={cn(\n      \"text-lg font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nDrawerTitle.displayName = DrawerPrimitive.Title.displayName\n\nconst DrawerDescription = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nDrawerDescription.displayName = DrawerPrimitive.Description.displayName\n\nexport {\n  Drawer,\n  DrawerPortal,\n  DrawerOverlay,\n  DrawerTrigger,\n  DrawerClose,\n  DrawerContent,\n  DrawerHeader,\n  DrawerFooter,\n  DrawerTitle,\n  DrawerDescription,\n}\n"
  },
  {
    "path": "frontend/components/ui/dropdown-menu.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as DropdownMenuPrimitive from \"@radix-ui/react-dropdown-menu\"\nimport { Check, ChevronRight, Circle } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst DropdownMenu = DropdownMenuPrimitive.Root\n\nconst DropdownMenuTrigger = DropdownMenuPrimitive.Trigger\n\nconst DropdownMenuGroup = DropdownMenuPrimitive.Group\n\nconst DropdownMenuPortal = DropdownMenuPrimitive.Portal\n\nconst DropdownMenuSub = DropdownMenuPrimitive.Sub\n\nconst DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup\n\nconst DropdownMenuSubTrigger = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {\n    inset?: boolean\n  }\n>(({ className, inset, children, ...props }, ref) => (\n  <DropdownMenuPrimitive.SubTrigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <ChevronRight className=\"ml-auto h-4 w-4\" />\n  </DropdownMenuPrimitive.SubTrigger>\n))\nDropdownMenuSubTrigger.displayName =\n  DropdownMenuPrimitive.SubTrigger.displayName\n\nconst DropdownMenuSubContent = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>\n>(({ className, ...props }, ref) => (\n  <DropdownMenuPrimitive.SubContent\n    ref={ref}\n    className={cn(\n      \"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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))\nDropdownMenuSubContent.displayName =\n  DropdownMenuPrimitive.SubContent.displayName\n\nconst DropdownMenuContent = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n  <DropdownMenuPrimitive.Portal>\n    <DropdownMenuPrimitive.Content\n      ref={ref}\n      sideOffset={sideOffset}\n      className={cn(\n        \"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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  </DropdownMenuPrimitive.Portal>\n))\nDropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName\n\nconst DropdownMenuItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <DropdownMenuPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nDropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName\n\nconst DropdownMenuCheckboxItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>\n>(({ className, children, checked, ...props }, ref) => (\n  <DropdownMenuPrimitive.CheckboxItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    checked={checked}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <DropdownMenuPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </DropdownMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </DropdownMenuPrimitive.CheckboxItem>\n))\nDropdownMenuCheckboxItem.displayName =\n  DropdownMenuPrimitive.CheckboxItem.displayName\n\nconst DropdownMenuRadioItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>\n>(({ className, children, ...props }, ref) => (\n  <DropdownMenuPrimitive.RadioItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <DropdownMenuPrimitive.ItemIndicator>\n        <Circle className=\"h-2 w-2 fill-current\" />\n      </DropdownMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </DropdownMenuPrimitive.RadioItem>\n))\nDropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName\n\nconst DropdownMenuLabel = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <DropdownMenuPrimitive.Label\n    ref={ref}\n    className={cn(\n      \"px-2 py-1.5 text-sm font-semibold\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nDropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName\n\nconst DropdownMenuSeparator = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <DropdownMenuPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-muted\", className)}\n    {...props}\n  />\n))\nDropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName\n\nconst DropdownMenuShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\"ml-auto text-xs tracking-widest opacity-60\", className)}\n      {...props}\n    />\n  )\n}\nDropdownMenuShortcut.displayName = \"DropdownMenuShortcut\"\n\nexport {\n  DropdownMenu,\n  DropdownMenuTrigger,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuCheckboxItem,\n  DropdownMenuRadioItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuShortcut,\n  DropdownMenuGroup,\n  DropdownMenuPortal,\n  DropdownMenuSub,\n  DropdownMenuSubContent,\n  DropdownMenuSubTrigger,\n  DropdownMenuRadioGroup,\n}\n"
  },
  {
    "path": "frontend/components/ui/file-upload.tsx",
    "content": "import React, { useRef, useState } from 'react';\nimport { motion } from 'framer-motion';\nimport { useDropzone } from 'react-dropzone';\nimport { UploadIcon, X } from 'lucide-react';\nimport { cn } from '@/lib/utils';\n\nconst mainVariant = {\n  initial: { x: 0, y: 0 },\n  animate: { x: 10, y: -10, opacity: 0.9 },\n};\n\nconst secondaryVariant = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n};\n\nconst allowedFileTypes = '.pdf,.doc,.docx,.txt,.md';\n\nexport const FileUpload = ({\n  onChange,\n}: {\n  onChange?: (files: File[]) => void;\n}) => {\n  const [file, setFile] = useState<File | null>(null);\n  const fileInputRef = useRef<HTMLInputElement>(null);\n\n  const handleFileChange = (newFiles: File[]) => {\n    const validFiles = newFiles.filter((file) => {\n      const fileExtension = file.name.split('.').pop()?.toLowerCase();\n      return ['pdf', 'doc', 'docx', 'txt', 'md'].includes(fileExtension || '');\n    });\n\n    if (validFiles.length > 0) {\n      setFile(validFiles[0]);\n      onChange && onChange(validFiles);\n    }\n  };\n\n  const handleClick = () => {\n    fileInputRef.current?.click();\n  };\n\n  const removeFile = () => {\n    setFile(null);\n    onChange && onChange([]);\n  };\n\n  const { getRootProps, isDragActive } = useDropzone({\n    multiple: false,\n    noClick: true,\n    onDrop: handleFileChange,\n    accept: {\n      'application/pdf': ['.pdf'],\n      'application/msword': ['.doc'],\n      'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n        ['.docx'],\n      'text/plain': ['.txt'],\n      'text/markdown': ['.md'],\n    },\n    onDropRejected: (error) => {\n      console.log(error);\n    },\n  });\n\n  return (\n    <div className=\"w-full\" {...getRootProps()}>\n      <motion.div\n        onClick={handleClick}\n        whileHover=\"animate\"\n        className=\"p-10 group/file block rounded-lg cursor-pointer w-full relative overflow-hidden\"\n      >\n        <input\n          ref={fileInputRef}\n          id=\"file-upload-handle\"\n          type=\"file\"\n          accept={allowedFileTypes}\n          onChange={(e) => handleFileChange(Array.from(e.target.files || []))}\n          className=\"hidden\"\n        />\n        <div className=\"absolute inset-0 [mask-image:radial-gradient(ellipse_at_center,white,transparent)]\">\n          <GridPattern />\n        </div>\n        <div className=\"flex flex-col items-center justify-center\">\n          <p className=\"relative z-20 font-sans font-bold text-neutral-700 dark:text-neutral-300 text-base\">\n            Upload file\n          </p>\n          <p className=\"relative z-20 font-sans font-normal text-neutral-400 dark:text-neutral-400 text-base mt-2\">\n            Drag or drop your file here or click to upload\n          </p>\n          <p className=\"relative z-20 font-sans font-normal text-neutral-400 dark:text-neutral-400 text-base mt-2\">\n            Allowed File type: {allowedFileTypes}\n          </p>\n\n          <div className=\"relative w-full mt-10 mx-auto\">\n            {file ? (\n              <motion.div\n                layoutId=\"file-upload\"\n                className={cn(\n                  'relative overflow-hidden z-40 bg-white dark:bg-neutral-900 flex flex-col items-start justify-start md:h-24 p-4 mt-4 w-full mx-auto rounded-md',\n                  'shadow-sm'\n                )}\n              >\n                <div className=\"flex justify-between w-full items-center gap-4\">\n                  <motion.p\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 1 }}\n                    layout\n                    className=\"text-base text-neutral-700 dark:text-neutral-300 truncate max-w-xs\"\n                  >\n                    {file.name}\n                  </motion.p>\n                  <motion.p\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 1 }}\n                    layout\n                    className=\"rounded-lg px-2 py-1 w-fit flex-shrink-0 text-sm text-neutral-600 dark:bg-neutral-800 dark:text-white shadow-input\"\n                  >\n                    {(file.size / (1024 * 1024)).toFixed(2)} MB\n                  </motion.p>\n                </div>\n\n                <div className=\"flex text-sm md:flex-row flex-col items-start md:items-center w-full mt-2 justify-between text-neutral-600 dark:text-neutral-400\">\n                  <motion.p\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 1 }}\n                    layout\n                    className=\"px-1 py-0.5 rounded-md bg-gray-100 dark:bg-neutral-800 \"\n                  >\n                    {file.type}\n                  </motion.p>\n\n                  <motion.p\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 1 }}\n                    layout\n                  >\n                    modified {new Date(file.lastModified).toLocaleDateString()}\n                  </motion.p>\n                </div>\n\n                <button\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    removeFile();\n                  }}\n                  className=\"absolute top-2 right-2 text-neutral-500 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-200\"\n                >\n                  <X size={18} />\n                </button>\n              </motion.div>\n            ) : (\n              <>\n                <motion.div\n                  layoutId=\"file-upload\"\n                  variants={mainVariant}\n                  transition={{\n                    type: 'spring',\n                    stiffness: 300,\n                    damping: 20,\n                  }}\n                  className={cn(\n                    'relative group-hover/file:shadow-2xl z-40 bg-white dark:bg-neutral-900 flex items-center justify-center h-32 mt-4 w-full max-w-[8rem] mx-auto rounded-md',\n                    'shadow-[0px_10px_50px_rgba(0,0,0,0.1)]'\n                  )}\n                >\n                  {isDragActive ? (\n                    <motion.p\n                      initial={{ opacity: 0 }}\n                      animate={{ opacity: 1 }}\n                      className=\"text-neutral-600 flex flex-col items-center\"\n                    >\n                      Drop it\n                      <UploadIcon className=\"h-4 w-4 text-neutral-600 dark:text-neutral-400\" />\n                    </motion.p>\n                  ) : (\n                    <UploadIcon className=\"h-4 w-4 text-neutral-600 dark:text-neutral-300\" />\n                  )}\n                </motion.div>\n\n                <motion.div\n                  variants={secondaryVariant}\n                  className=\"absolute opacity-0 border border-dashed border-sky-400 inset-0 z-30 bg-transparent flex items-center justify-center h-32 mt-4 w-full max-w-[8rem] mx-auto rounded-md\"\n                ></motion.div>\n              </>\n            )}\n          </div>\n        </div>\n      </motion.div>\n    </div>\n  );\n};\nexport function GridPattern() {\n  const columns = 41;\n  const rows = 11;\n  return (\n    <div className=\"flex bg-gray-100 dark:bg-neutral-900 flex-shrink-0 flex-wrap justify-center items-center gap-x-px gap-y-px  scale-105\">\n      {Array.from({ length: rows }).map((_, row) =>\n        Array.from({ length: columns }).map((_, col) => {\n          const index = row * columns + col;\n          return (\n            <div\n              key={`${col}-${row}`}\n              className={`w-10 h-10 flex flex-shrink-0 rounded-[2px] ${\n                index % 2 === 0\n                  ? 'bg-gray-50 dark:bg-neutral-950'\n                  : 'bg-gray-50 dark:bg-neutral-950 shadow-[0px_0px_1px_3px_rgba(255,255,255,1)_inset] dark:shadow-[0px_0px_1px_3px_rgba(0,0,0,1)_inset]'\n              }`}\n            />\n          );\n        })\n      )}\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/file-uploader.tsx",
    "content": "\"use client\";\n\nimport { Loader2, Paperclip } from \"lucide-react\";\nimport { ChangeEvent, useState } from \"react\";\nimport { buttonVariants } from \"./button\";\nimport { cn } from \"../../lib/utils\";\n\nexport interface FileUploaderProps {\n  config?: {\n    inputId?: string;\n    fileSizeLimit?: number;\n    allowedExtensions?: string[];\n    checkExtension?: (extension: string) => string | null;\n    disabled: boolean;\n  };\n  onFileUpload: (file: File) => Promise<void>;\n  onFileError?: (errMsg: string) => void;\n}\n\nconst DEFAULT_INPUT_ID = \"fileInput\";\nconst DEFAULT_FILE_SIZE_LIMIT = 1024 * 1024 * 50; // 50 MB\n\nexport default function FileUploader({\n  config,\n  onFileUpload,\n  onFileError,\n}: FileUploaderProps) {\n  const [uploading, setUploading] = useState(false);\n\n  const inputId = config?.inputId || DEFAULT_INPUT_ID;\n  const fileSizeLimit = config?.fileSizeLimit || DEFAULT_FILE_SIZE_LIMIT;\n  const allowedExtensions = config?.allowedExtensions;\n  const defaultCheckExtension = (extension: string) => {\n    if (allowedExtensions && !allowedExtensions.includes(extension)) {\n      return `Invalid file type. Please select a file with one of these formats: ${allowedExtensions!.join(\n        \",\"\n      )}`;\n    }\n    return null;\n  };\n  const checkExtension = config?.checkExtension ?? defaultCheckExtension;\n\n  const isFileSizeExceeded = (file: File) => {\n    return file.size > fileSizeLimit;\n  };\n\n  const resetInput = () => {\n    const fileInput = document.getElementById(inputId) as HTMLInputElement;\n    fileInput.value = \"\";\n  };\n\n  const onFileChange = async (e: ChangeEvent<HTMLInputElement>) => {\n    const file = e.target.files?.[0];\n    if (!file) return;\n\n    setUploading(true);\n    await handleUpload(file);\n    resetInput();\n    setUploading(false);\n  };\n\n  const handleUpload = async (file: File) => {\n    const onFileUploadError = onFileError || window.alert;\n    const fileExtension = file.name.split(\".\").pop() || \"\";\n    const extensionFileError = checkExtension(fileExtension);\n    if (extensionFileError) {\n      return onFileUploadError(extensionFileError);\n    }\n\n    if (isFileSizeExceeded(file)) {\n      return onFileUploadError(\n        `File size exceeded. Limit is ${fileSizeLimit / 1024 / 1024} MB`\n      );\n    }\n\n    await onFileUpload(file);\n  };\n\n  return (\n    <div className=\"self-stretch\">\n      <input\n        type=\"file\"\n        id={inputId}\n        style={{ display: \"none\" }}\n        onChange={onFileChange}\n        accept={allowedExtensions?.join(\",\")}\n        disabled={config?.disabled || uploading}\n      />\n      <label\n        htmlFor={inputId}\n        className={cn(\n          buttonVariants({ variant: \"secondary\", size: \"icon\" }),\n          \"cursor-pointer\",\n          uploading && \"opacity-50\"\n        )}\n      >\n        {uploading ? (\n          <Loader2 className=\"h-4 w-4 animate-spin\" />\n        ) : (\n          <Paperclip className=\"-rotate-45 w-4 h-4\" />\n        )}\n      </label>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/form.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport {\n  Controller,\n  ControllerProps,\n  FieldPath,\n  FieldValues,\n  FormProvider,\n  useFormContext,\n} from \"react-hook-form\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Label } from \"@/components/ui/label\"\n\nconst Form = FormProvider\n\ntype FormFieldContextValue<\n  TFieldValues extends FieldValues = FieldValues,\n  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>\n> = {\n  name: TName\n}\n\nconst FormFieldContext = React.createContext<FormFieldContextValue>(\n  {} as FormFieldContextValue\n)\n\nconst FormField = <\n  TFieldValues extends FieldValues = FieldValues,\n  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>\n>({\n  ...props\n}: ControllerProps<TFieldValues, TName>) => {\n  return (\n    <FormFieldContext.Provider value={{ name: props.name }}>\n      <Controller {...props} />\n    </FormFieldContext.Provider>\n  )\n}\n\nconst useFormField = () => {\n  const fieldContext = React.useContext(FormFieldContext)\n  const itemContext = React.useContext(FormItemContext)\n  const { getFieldState, formState } = useFormContext()\n\n  const fieldState = getFieldState(fieldContext.name, formState)\n\n  if (!fieldContext) {\n    throw new Error(\"useFormField should be used within <FormField>\")\n  }\n\n  const { id } = itemContext\n\n  return {\n    id,\n    name: fieldContext.name,\n    formItemId: `${id}-form-item`,\n    formDescriptionId: `${id}-form-item-description`,\n    formMessageId: `${id}-form-item-message`,\n    ...fieldState,\n  }\n}\n\ntype FormItemContextValue = {\n  id: string\n}\n\nconst FormItemContext = React.createContext<FormItemContextValue>(\n  {} as FormItemContextValue\n)\n\nconst FormItem = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => {\n  const id = React.useId()\n\n  return (\n    <FormItemContext.Provider value={{ id }}>\n      <div ref={ref} className={cn(\"space-y-2\", className)} {...props} />\n    </FormItemContext.Provider>\n  )\n})\nFormItem.displayName = \"FormItem\"\n\nconst FormLabel = React.forwardRef<\n  React.ElementRef<typeof LabelPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>\n>(({ className, ...props }, ref) => {\n  const { error, formItemId } = useFormField()\n\n  return (\n    <Label\n      ref={ref}\n      className={cn(error && \"text-destructive\", className)}\n      htmlFor={formItemId}\n      {...props}\n    />\n  )\n})\nFormLabel.displayName = \"FormLabel\"\n\nconst FormControl = React.forwardRef<\n  React.ElementRef<typeof Slot>,\n  React.ComponentPropsWithoutRef<typeof Slot>\n>(({ ...props }, ref) => {\n  const { error, formItemId, formDescriptionId, formMessageId } = useFormField()\n\n  return (\n    <Slot\n      ref={ref}\n      id={formItemId}\n      aria-describedby={\n        !error\n          ? `${formDescriptionId}`\n          : `${formDescriptionId} ${formMessageId}`\n      }\n      aria-invalid={!!error}\n      {...props}\n    />\n  )\n})\nFormControl.displayName = \"FormControl\"\n\nconst FormDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => {\n  const { formDescriptionId } = useFormField()\n\n  return (\n    <p\n      ref={ref}\n      id={formDescriptionId}\n      className={cn(\"text-sm text-muted-foreground\", className)}\n      {...props}\n    />\n  )\n})\nFormDescription.displayName = \"FormDescription\"\n\nconst FormMessage = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, children, ...props }, ref) => {\n  const { error, formMessageId } = useFormField()\n  const body = error ? String(error?.message) : children\n\n  if (!body) {\n    return null\n  }\n\n  return (\n    <p\n      ref={ref}\n      id={formMessageId}\n      className={cn(\"text-sm font-medium text-destructive\", className)}\n      {...props}\n    >\n      {body}\n    </p>\n  )\n})\nFormMessage.displayName = \"FormMessage\"\n\nexport {\n  useFormField,\n  Form,\n  FormItem,\n  FormLabel,\n  FormControl,\n  FormDescription,\n  FormMessage,\n  FormField,\n}\n"
  },
  {
    "path": "frontend/components/ui/hover-card.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as HoverCardPrimitive from \"@radix-ui/react-hover-card\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst HoverCard = HoverCardPrimitive.Root\n\nconst HoverCardTrigger = HoverCardPrimitive.Trigger\n\nconst HoverCardContent = React.forwardRef<\n  React.ElementRef<typeof HoverCardPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n  <HoverCardPrimitive.Content\n    ref={ref}\n    align={align}\n    sideOffset={sideOffset}\n    className={cn(\n      \"z-50 w-64 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))\nHoverCardContent.displayName = HoverCardPrimitive.Content.displayName\n\nexport { HoverCard, HoverCardTrigger, HoverCardContent }\n"
  },
  {
    "path": "frontend/components/ui/input-otp.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { OTPInput, OTPInputContext } from \"input-otp\"\nimport { Dot } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst InputOTP = React.forwardRef<\n  React.ElementRef<typeof OTPInput>,\n  React.ComponentPropsWithoutRef<typeof OTPInput>\n>(({ className, containerClassName, ...props }, ref) => (\n  <OTPInput\n    ref={ref}\n    containerClassName={cn(\n      \"flex items-center gap-2 has-[:disabled]:opacity-50\",\n      containerClassName\n    )}\n    className={cn(\"disabled:cursor-not-allowed\", className)}\n    {...props}\n  />\n))\nInputOTP.displayName = \"InputOTP\"\n\nconst InputOTPGroup = React.forwardRef<\n  React.ElementRef<\"div\">,\n  React.ComponentPropsWithoutRef<\"div\">\n>(({ className, ...props }, ref) => (\n  <div ref={ref} className={cn(\"flex items-center\", className)} {...props} />\n))\nInputOTPGroup.displayName = \"InputOTPGroup\"\n\nconst InputOTPSlot = React.forwardRef<\n  React.ElementRef<\"div\">,\n  React.ComponentPropsWithoutRef<\"div\"> & { index: number }\n>(({ index, className, ...props }, ref) => {\n  const inputOTPContext = React.useContext(OTPInputContext)\n  const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]\n\n  return (\n    <div\n      ref={ref}\n      className={cn(\n        \"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md\",\n        isActive && \"z-10 ring-2 ring-ring ring-offset-background\",\n        className\n      )}\n      {...props}\n    >\n      {char}\n      {hasFakeCaret && (\n        <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center\">\n          <div className=\"h-4 w-px animate-caret-blink bg-foreground duration-1000\" />\n        </div>\n      )}\n    </div>\n  )\n})\nInputOTPSlot.displayName = \"InputOTPSlot\"\n\nconst InputOTPSeparator = React.forwardRef<\n  React.ElementRef<\"div\">,\n  React.ComponentPropsWithoutRef<\"div\">\n>(({ ...props }, ref) => (\n  <div ref={ref} role=\"separator\" {...props}>\n    <Dot />\n  </div>\n))\nInputOTPSeparator.displayName = \"InputOTPSeparator\"\n\nexport { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }\n"
  },
  {
    "path": "frontend/components/ui/input.tsx",
    "content": "import * as React from 'react';\n\nimport { cn } from '@/lib/utils';\n\nexport interface InputProps\n  extends React.InputHTMLAttributes<HTMLInputElement> {}\n\nconst Input = React.forwardRef<HTMLInputElement, InputProps>(\n  ({ className, type, ...props }, ref) => {\n    return (\n      <input\n        type={type}\n        className={cn(\n          'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',\n          className\n        )}\n        ref={ref}\n        {...props}\n      />\n    );\n  }\n);\nInput.displayName = 'Input';\n\nexport { Input };\n"
  },
  {
    "path": "frontend/components/ui/label.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst labelVariants = cva(\n  \"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\"\n)\n\nconst Label = React.forwardRef<\n  React.ElementRef<typeof LabelPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &\n    VariantProps<typeof labelVariants>\n>(({ className, ...props }, ref) => (\n  <LabelPrimitive.Root\n    ref={ref}\n    className={cn(labelVariants(), className)}\n    {...props}\n  />\n))\nLabel.displayName = LabelPrimitive.Root.displayName\n\nexport { Label }\n"
  },
  {
    "path": "frontend/components/ui/menubar.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as MenubarPrimitive from \"@radix-ui/react-menubar\"\nimport { Check, ChevronRight, Circle } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst MenubarMenu = MenubarPrimitive.Menu\n\nconst MenubarGroup = MenubarPrimitive.Group\n\nconst MenubarPortal = MenubarPrimitive.Portal\n\nconst MenubarSub = MenubarPrimitive.Sub\n\nconst MenubarRadioGroup = MenubarPrimitive.RadioGroup\n\nconst Menubar = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"flex h-10 items-center space-x-1 rounded-md border bg-background p-1\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubar.displayName = MenubarPrimitive.Root.displayName\n\nconst MenubarTrigger = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName\n\nconst MenubarSubTrigger = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.SubTrigger>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {\n    inset?: boolean\n  }\n>(({ className, inset, children, ...props }, ref) => (\n  <MenubarPrimitive.SubTrigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <ChevronRight className=\"ml-auto h-4 w-4\" />\n  </MenubarPrimitive.SubTrigger>\n))\nMenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName\n\nconst MenubarSubContent = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.SubContent>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.SubContent\n    ref={ref}\n    className={cn(\n      \"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground 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))\nMenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName\n\nconst MenubarContent = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>\n>(\n  (\n    { className, align = \"start\", alignOffset = -4, sideOffset = 8, ...props },\n    ref\n  ) => (\n    <MenubarPrimitive.Portal>\n      <MenubarPrimitive.Content\n        ref={ref}\n        align={align}\n        alignOffset={alignOffset}\n        sideOffset={sideOffset}\n        className={cn(\n          \"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in 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    </MenubarPrimitive.Portal>\n  )\n)\nMenubarContent.displayName = MenubarPrimitive.Content.displayName\n\nconst MenubarItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <MenubarPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarItem.displayName = MenubarPrimitive.Item.displayName\n\nconst MenubarCheckboxItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>\n>(({ className, children, checked, ...props }, ref) => (\n  <MenubarPrimitive.CheckboxItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    checked={checked}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <MenubarPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </MenubarPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </MenubarPrimitive.CheckboxItem>\n))\nMenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName\n\nconst MenubarRadioItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.RadioItem>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>\n>(({ className, children, ...props }, ref) => (\n  <MenubarPrimitive.RadioItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <MenubarPrimitive.ItemIndicator>\n        <Circle className=\"h-2 w-2 fill-current\" />\n      </MenubarPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </MenubarPrimitive.RadioItem>\n))\nMenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName\n\nconst MenubarLabel = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <MenubarPrimitive.Label\n    ref={ref}\n    className={cn(\n      \"px-2 py-1.5 text-sm font-semibold\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarLabel.displayName = MenubarPrimitive.Label.displayName\n\nconst MenubarSeparator = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-muted\", className)}\n    {...props}\n  />\n))\nMenubarSeparator.displayName = MenubarPrimitive.Separator.displayName\n\nconst MenubarShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\n        \"ml-auto text-xs tracking-widest text-muted-foreground\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\nMenubarShortcut.displayname = \"MenubarShortcut\"\n\nexport {\n  Menubar,\n  MenubarMenu,\n  MenubarTrigger,\n  MenubarContent,\n  MenubarItem,\n  MenubarSeparator,\n  MenubarLabel,\n  MenubarCheckboxItem,\n  MenubarRadioGroup,\n  MenubarRadioItem,\n  MenubarPortal,\n  MenubarSubContent,\n  MenubarSubTrigger,\n  MenubarGroup,\n  MenubarSub,\n  MenubarShortcut,\n}\n"
  },
  {
    "path": "frontend/components/ui/navigation-menu.tsx",
    "content": "import * as React from \"react\"\nimport * as NavigationMenuPrimitive from \"@radix-ui/react-navigation-menu\"\nimport { cva } from \"class-variance-authority\"\nimport { ChevronDown } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst NavigationMenu = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>\n>(({ className, children, ...props }, ref) => (\n  <NavigationMenuPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative z-10 flex max-w-max flex-1 items-center justify-center\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <NavigationMenuViewport />\n  </NavigationMenuPrimitive.Root>\n))\nNavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName\n\nconst NavigationMenuList = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.List\n    ref={ref}\n    className={cn(\n      \"group flex flex-1 list-none items-center justify-center space-x-1\",\n      className\n    )}\n    {...props}\n  />\n))\nNavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName\n\nconst NavigationMenuItem = NavigationMenuPrimitive.Item\n\nconst navigationMenuTriggerStyle = cva(\n  \"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50\"\n)\n\nconst NavigationMenuTrigger = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <NavigationMenuPrimitive.Trigger\n    ref={ref}\n    className={cn(navigationMenuTriggerStyle(), \"group\", className)}\n    {...props}\n  >\n    {children}{\" \"}\n    <ChevronDown\n      className=\"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180\"\n      aria-hidden=\"true\"\n    />\n  </NavigationMenuPrimitive.Trigger>\n))\nNavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName\n\nconst NavigationMenuContent = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.Content\n    ref={ref}\n    className={cn(\n      \"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto \",\n      className\n    )}\n    {...props}\n  />\n))\nNavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName\n\nconst NavigationMenuLink = NavigationMenuPrimitive.Link\n\nconst NavigationMenuViewport = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>\n>(({ className, ...props }, ref) => (\n  <div className={cn(\"absolute left-0 top-full flex justify-center\")}>\n    <NavigationMenuPrimitive.Viewport\n      className={cn(\n        \"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]\",\n        className\n      )}\n      ref={ref}\n      {...props}\n    />\n  </div>\n))\nNavigationMenuViewport.displayName =\n  NavigationMenuPrimitive.Viewport.displayName\n\nconst NavigationMenuIndicator = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.Indicator\n    ref={ref}\n    className={cn(\n      \"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in\",\n      className\n    )}\n    {...props}\n  >\n    <div className=\"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md\" />\n  </NavigationMenuPrimitive.Indicator>\n))\nNavigationMenuIndicator.displayName =\n  NavigationMenuPrimitive.Indicator.displayName\n\nexport {\n  navigationMenuTriggerStyle,\n  NavigationMenu,\n  NavigationMenuList,\n  NavigationMenuItem,\n  NavigationMenuContent,\n  NavigationMenuTrigger,\n  NavigationMenuLink,\n  NavigationMenuIndicator,\n  NavigationMenuViewport,\n}\n"
  },
  {
    "path": "frontend/components/ui/pagination.tsx",
    "content": "import * as React from \"react\"\nimport { ChevronLeft, ChevronRight, MoreHorizontal } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { ButtonProps, buttonVariants } from \"@/components/ui/button\"\n\nconst Pagination = ({ className, ...props }: React.ComponentProps<\"nav\">) => (\n  <nav\n    role=\"navigation\"\n    aria-label=\"pagination\"\n    className={cn(\"mx-auto flex w-full justify-center\", className)}\n    {...props}\n  />\n)\nPagination.displayName = \"Pagination\"\n\nconst PaginationContent = React.forwardRef<\n  HTMLUListElement,\n  React.ComponentProps<\"ul\">\n>(({ className, ...props }, ref) => (\n  <ul\n    ref={ref}\n    className={cn(\"flex flex-row items-center gap-1\", className)}\n    {...props}\n  />\n))\nPaginationContent.displayName = \"PaginationContent\"\n\nconst PaginationItem = React.forwardRef<\n  HTMLLIElement,\n  React.ComponentProps<\"li\">\n>(({ className, ...props }, ref) => (\n  <li ref={ref} className={cn(\"\", className)} {...props} />\n))\nPaginationItem.displayName = \"PaginationItem\"\n\ntype PaginationLinkProps = {\n  isActive?: boolean\n} & Pick<ButtonProps, \"size\"> &\n  React.ComponentProps<\"a\">\n\nconst PaginationLink = ({\n  className,\n  isActive,\n  size = \"icon\",\n  ...props\n}: PaginationLinkProps) => (\n  <a\n    aria-current={isActive ? \"page\" : undefined}\n    className={cn(\n      buttonVariants({\n        variant: isActive ? \"outline\" : \"ghost\",\n        size,\n      }),\n      className\n    )}\n    {...props}\n  />\n)\nPaginationLink.displayName = \"PaginationLink\"\n\nconst PaginationPrevious = ({\n  className,\n  ...props\n}: React.ComponentProps<typeof PaginationLink>) => (\n  <PaginationLink\n    aria-label=\"Go to previous page\"\n    size=\"default\"\n    className={cn(\"gap-1 pl-2.5\", className)}\n    {...props}\n  >\n    <ChevronLeft className=\"h-4 w-4\" />\n    <span>Previous</span>\n  </PaginationLink>\n)\nPaginationPrevious.displayName = \"PaginationPrevious\"\n\nconst PaginationNext = ({\n  className,\n  ...props\n}: React.ComponentProps<typeof PaginationLink>) => (\n  <PaginationLink\n    aria-label=\"Go to next page\"\n    size=\"default\"\n    className={cn(\"gap-1 pr-2.5\", className)}\n    {...props}\n  >\n    <span>Next</span>\n    <ChevronRight className=\"h-4 w-4\" />\n  </PaginationLink>\n)\nPaginationNext.displayName = \"PaginationNext\"\n\nconst PaginationEllipsis = ({\n  className,\n  ...props\n}: React.ComponentProps<\"span\">) => (\n  <span\n    aria-hidden\n    className={cn(\"flex h-9 w-9 items-center justify-center\", className)}\n    {...props}\n  >\n    <MoreHorizontal className=\"h-4 w-4\" />\n    <span className=\"sr-only\">More pages</span>\n  </span>\n)\nPaginationEllipsis.displayName = \"PaginationEllipsis\"\n\nexport {\n  Pagination,\n  PaginationContent,\n  PaginationEllipsis,\n  PaginationItem,\n  PaginationLink,\n  PaginationNext,\n  PaginationPrevious,\n}\n"
  },
  {
    "path": "frontend/components/ui/placeholders-and-vanish-input.tsx",
    "content": "'use client';\n\nimport { AnimatePresence, motion } from 'framer-motion';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { cn } from '@/lib/utils';\n\nexport function PlaceholdersAndVanishInput({\n  placeholders,\n  onChange,\n  onSubmit,\n  value,\n  setValue,\n}: {\n  placeholders: string[];\n  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n  onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;\n  value: string;\n  setValue: (value: string) => void;\n}) {\n  const [currentPlaceholder, setCurrentPlaceholder] = useState(0);\n\n  const intervalRef = useRef<NodeJS.Timeout | null>(null);\n  const startAnimation = () => {\n    intervalRef.current = setInterval(() => {\n      setCurrentPlaceholder((prev) => (prev + 1) % placeholders.length);\n    }, 3000);\n  };\n  const handleVisibilityChange = () => {\n    if (document.visibilityState !== 'visible' && intervalRef.current) {\n      clearInterval(intervalRef.current); // Clear the interval when the tab is not visible\n      intervalRef.current = null;\n    } else if (document.visibilityState === 'visible') {\n      startAnimation(); // Restart the interval when the tab becomes visible\n    }\n  };\n\n  useEffect(() => {\n    startAnimation();\n    document.addEventListener('visibilitychange', handleVisibilityChange);\n\n    return () => {\n      if (intervalRef.current) {\n        clearInterval(intervalRef.current);\n      }\n      document.removeEventListener('visibilitychange', handleVisibilityChange);\n    };\n  }, [placeholders]);\n\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const newDataRef = useRef<any[]>([]);\n  const inputRef = useRef<HTMLInputElement>(null);\n  // const [value, setValue] = useState('');\n  const [animating, setAnimating] = useState(false);\n\n  const draw = useCallback(() => {\n    if (!inputRef.current) return;\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext('2d');\n    if (!ctx) return;\n\n    canvas.width = 800;\n    canvas.height = 800;\n    ctx.clearRect(0, 0, 800, 800);\n    const computedStyles = getComputedStyle(inputRef.current);\n\n    const fontSize = parseFloat(computedStyles.getPropertyValue('font-size'));\n    ctx.font = `${fontSize * 2}px ${computedStyles.fontFamily}`;\n    ctx.fillStyle = '#FFF';\n    ctx.fillText(value, 16, 40);\n\n    const imageData = ctx.getImageData(0, 0, 800, 800);\n    const pixelData = imageData.data;\n    const newData: any[] = [];\n\n    for (let t = 0; t < 800; t++) {\n      let i = 4 * t * 800;\n      for (let n = 0; n < 800; n++) {\n        let e = i + 4 * n;\n        if (\n          pixelData[e] !== 0 &&\n          pixelData[e + 1] !== 0 &&\n          pixelData[e + 2] !== 0\n        ) {\n          newData.push({\n            x: n,\n            y: t,\n            color: [\n              pixelData[e],\n              pixelData[e + 1],\n              pixelData[e + 2],\n              pixelData[e + 3],\n            ],\n          });\n        }\n      }\n    }\n\n    newDataRef.current = newData.map(({ x, y, color }) => ({\n      x,\n      y,\n      r: 1,\n      color: `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${color[3]})`,\n    }));\n  }, [value]);\n\n  useEffect(() => {\n    draw();\n  }, [value, draw]);\n\n  const animate = (start: number) => {\n    const animateFrame = (pos: number = 0) => {\n      requestAnimationFrame(() => {\n        const newArr = [];\n        for (let i = 0; i < newDataRef.current.length; i++) {\n          const current = newDataRef.current[i];\n          if (current.x < pos) {\n            newArr.push(current);\n          } else {\n            if (current.r <= 0) {\n              current.r = 0;\n              continue;\n            }\n            current.x += Math.random() > 0.5 ? 1 : -1;\n            current.y += Math.random() > 0.5 ? 1 : -1;\n            current.r -= 0.05 * Math.random();\n            newArr.push(current);\n          }\n        }\n        newDataRef.current = newArr;\n        const ctx = canvasRef.current?.getContext('2d');\n        if (ctx) {\n          ctx.clearRect(pos, 0, 800, 800);\n          newDataRef.current.forEach((t) => {\n            const { x: n, y: i, r: s, color: color } = t;\n            if (n > pos) {\n              ctx.beginPath();\n              ctx.rect(n, i, s, s);\n              ctx.fillStyle = color;\n              ctx.strokeStyle = color;\n              ctx.stroke();\n            }\n          });\n        }\n        if (newDataRef.current.length > 0) {\n          animateFrame(pos - 8);\n        } else {\n          setValue('');\n          setAnimating(false);\n        }\n      });\n    };\n    animateFrame(start);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === 'Enter' && !animating) {\n      vanishAndSubmit();\n    }\n  };\n\n  const vanishAndSubmit = () => {\n    setAnimating(true);\n    draw();\n\n    const value = inputRef.current?.value || '';\n    if (value && inputRef.current) {\n      const maxX = newDataRef.current.reduce(\n        (prev, current) => (current.x > prev ? current.x : prev),\n        0\n      );\n      animate(maxX);\n    }\n  };\n\n  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    vanishAndSubmit();\n    onSubmit && onSubmit(e);\n  };\n  return (\n    <form\n      className={cn(\n        'relative w-full md:max-w-[60%] mx-auto bg-muted dark:bg-background h-14 rounded-full overflow-hidden shadow-[0px_2px_3px_-1px_rgba(0,0,0,0.1),_0px_1px_0px_0px_rgba(25,28,33,0.02),_0px_0px_0px_1px_rgba(25,28,33,0.08)] transition duration-200 border-2',\n        value && 'bg-gray-50'\n      )}\n      onSubmit={handleSubmit}\n    >\n      <canvas\n        className={cn(\n          'absolute pointer-events-none  text-base transform scale-50 top-[20%] left-2 sm:left-8 origin-top-left filter invert dark:invert-0 pr-20',\n          !animating ? 'opacity-0' : 'opacity-100'\n        )}\n        ref={canvasRef}\n      />\n      <input\n        onChange={(e) => {\n          if (!animating) {\n            setValue(e.target.value);\n            onChange && onChange(e);\n          }\n        }}\n        onKeyDown={handleKeyDown}\n        ref={inputRef}\n        value={value}\n        type=\"text\"\n        className={cn(\n          'w-full relative text-sm sm:text-base z-20 border-none dark:text-white bg-transparent text-black h-full rounded-full focus:outline-none focus:ring-0 pl-6 sm:pl-6 pr-20',\n          animating && 'text-transparent dark:text-transparent'\n        )}\n      />\n\n      <button\n        disabled={!value}\n        type=\"submit\"\n        className=\"absolute right-2 top-1/2 z-30 -translate-y-1/2 h-8 w-8 rounded-full disabled:bg-gray-100 bg-black dark:bg-zinc-900 dark:disabled:bg-zinc-800 transition duration-200 flex items-center justify-center\"\n      >\n        <motion.svg\n          xmlns=\"http://www.w3.org/2000/svg\"\n          width=\"24\"\n          height=\"24\"\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth=\"2\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          className=\"text-gray-300 h-4 w-4\"\n        >\n          <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill=\"none\" />\n          <motion.path\n            d=\"M5 12l14 0\"\n            initial={{\n              strokeDasharray: '50%',\n              strokeDashoffset: '50%',\n            }}\n            animate={{\n              strokeDashoffset: value ? 0 : '50%',\n            }}\n            transition={{\n              duration: 0.3,\n              ease: 'linear',\n            }}\n          />\n          <path d=\"M13 18l6 -6\" />\n          <path d=\"M13 6l6 6\" />\n        </motion.svg>\n      </button>\n\n      <div className=\"absolute inset-0 flex items-center rounded-full pointer-events-none\">\n        <AnimatePresence mode=\"wait\">\n          {!value && (\n            <motion.p\n              initial={{\n                y: 5,\n                opacity: 0,\n              }}\n              key={`current-placeholder-${currentPlaceholder}`}\n              animate={{\n                y: 0,\n                opacity: 1,\n              }}\n              exit={{\n                y: -15,\n                opacity: 0,\n              }}\n              transition={{\n                duration: 0.3,\n                ease: 'linear',\n              }}\n              className=\"dark:text-zinc-500 text-sm sm:text-base font-normal text-neutral-500 pl-6 sm:pl-6 text-left w-[calc(100%-2rem)] truncate\"\n            >\n              {placeholders[currentPlaceholder]}\n            </motion.p>\n          )}\n        </AnimatePresence>\n      </div>\n    </form>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/popover.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\"\n\nimport { cn } from \"@/lib/utils\"\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": "frontend/components/ui/progress.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as ProgressPrimitive from \"@radix-ui/react-progress\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Progress = React.forwardRef<\n  React.ElementRef<typeof ProgressPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>\n>(({ className, value, ...props }, ref) => (\n  <ProgressPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative h-4 w-full overflow-hidden rounded-full bg-secondary\",\n      className\n    )}\n    {...props}\n  >\n    <ProgressPrimitive.Indicator\n      className=\"h-full w-full flex-1 bg-primary transition-all\"\n      style={{ transform: `translateX(-${100 - (value || 0)}%)` }}\n    />\n  </ProgressPrimitive.Root>\n))\nProgress.displayName = ProgressPrimitive.Root.displayName\n\nexport { Progress }\n"
  },
  {
    "path": "frontend/components/ui/radio-group.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as RadioGroupPrimitive from \"@radix-ui/react-radio-group\"\nimport { Circle } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst RadioGroup = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>\n>(({ className, ...props }, ref) => {\n  return (\n    <RadioGroupPrimitive.Root\n      className={cn(\"grid gap-2\", className)}\n      {...props}\n      ref={ref}\n    />\n  )\n})\nRadioGroup.displayName = RadioGroupPrimitive.Root.displayName\n\nconst RadioGroupItem = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>\n>(({ className, ...props }, ref) => {\n  return (\n    <RadioGroupPrimitive.Item\n      ref={ref}\n      className={cn(\n        \"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50\",\n        className\n      )}\n      {...props}\n    >\n      <RadioGroupPrimitive.Indicator className=\"flex items-center justify-center\">\n        <Circle className=\"h-2.5 w-2.5 fill-current text-current\" />\n      </RadioGroupPrimitive.Indicator>\n    </RadioGroupPrimitive.Item>\n  )\n})\nRadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName\n\nexport { RadioGroup, RadioGroupItem }\n"
  },
  {
    "path": "frontend/components/ui/resizable.tsx",
    "content": "\"use client\"\n\nimport { GripVertical } from \"lucide-react\"\nimport * as ResizablePrimitive from \"react-resizable-panels\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst ResizablePanelGroup = ({\n  className,\n  ...props\n}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (\n  <ResizablePrimitive.PanelGroup\n    className={cn(\n      \"flex h-full w-full data-[panel-group-direction=vertical]:flex-col\",\n      className\n    )}\n    {...props}\n  />\n)\n\nconst ResizablePanel = ResizablePrimitive.Panel\n\nconst ResizableHandle = ({\n  withHandle,\n  className,\n  ...props\n}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {\n  withHandle?: boolean\n}) => (\n  <ResizablePrimitive.PanelResizeHandle\n    className={cn(\n      \"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90\",\n      className\n    )}\n    {...props}\n  >\n    {withHandle && (\n      <div className=\"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border\">\n        <GripVertical className=\"h-2.5 w-2.5\" />\n      </div>\n    )}\n  </ResizablePrimitive.PanelResizeHandle>\n)\n\nexport { ResizablePanelGroup, ResizablePanel, ResizableHandle }\n"
  },
  {
    "path": "frontend/components/ui/scroll-area.tsx",
    "content": "'use client';\n\nimport * as React from 'react';\nimport * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';\n\nimport { cn } from '@/lib/utils';\n\nconst ScrollArea = React.forwardRef<\n  React.ElementRef<typeof ScrollAreaPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>\n>(({ className, children, ...props }, ref) => (\n  <ScrollAreaPrimitive.Root\n    ref={ref}\n    className={cn('relative overflow-hidden', className)}\n    {...props}\n  >\n    <ScrollAreaPrimitive.Viewport className=\"h-full w-full rounded-[inherit]\">\n      {children}\n    </ScrollAreaPrimitive.Viewport>\n    <ScrollBar />\n    <ScrollAreaPrimitive.Corner />\n  </ScrollAreaPrimitive.Root>\n));\nScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;\n\nconst ScrollBar = React.forwardRef<\n  React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,\n  React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>\n>(({ className, orientation = 'vertical', ...props }, ref) => (\n  <ScrollAreaPrimitive.ScrollAreaScrollbar\n    ref={ref}\n    orientation={orientation}\n    className={cn(\n      'flex touch-none select-none transition-colors',\n      orientation === 'vertical' &&\n        'h-full w-2.5 border-l border-l-transparent p-[1px]',\n      orientation === 'horizontal' &&\n        'h-2.5 flex-col border-t border-t-transparent p-[1px]',\n      className\n    )}\n    {...props}\n  >\n    <ScrollAreaPrimitive.ScrollAreaThumb className=\"relative flex-1 rounded-full bg-border\" />\n  </ScrollAreaPrimitive.ScrollAreaScrollbar>\n));\nScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;\n\nexport { ScrollArea, ScrollBar };\n"
  },
  {
    "path": "frontend/components/ui/select.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { Check, ChevronDown, ChevronUp } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Select = SelectPrimitive.Root\n\nconst SelectGroup = SelectPrimitive.Group\n\nconst SelectValue = SelectPrimitive.Value\n\nconst SelectTrigger = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <SelectPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <SelectPrimitive.Icon asChild>\n      <ChevronDown className=\"h-4 w-4 opacity-50\" />\n    </SelectPrimitive.Icon>\n  </SelectPrimitive.Trigger>\n))\nSelectTrigger.displayName = SelectPrimitive.Trigger.displayName\n\nconst SelectScrollUpButton = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.ScrollUpButton\n    ref={ref}\n    className={cn(\n      \"flex cursor-default items-center justify-center py-1\",\n      className\n    )}\n    {...props}\n  >\n    <ChevronUp className=\"h-4 w-4\" />\n  </SelectPrimitive.ScrollUpButton>\n))\nSelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName\n\nconst SelectScrollDownButton = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.ScrollDownButton\n    ref={ref}\n    className={cn(\n      \"flex cursor-default items-center justify-center py-1\",\n      className\n    )}\n    {...props}\n  >\n    <ChevronDown className=\"h-4 w-4\" />\n  </SelectPrimitive.ScrollDownButton>\n))\nSelectScrollDownButton.displayName =\n  SelectPrimitive.ScrollDownButton.displayName\n\nconst SelectContent = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>\n>(({ className, children, position = \"popper\", ...props }, ref) => (\n  <SelectPrimitive.Portal>\n    <SelectPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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        position === \"popper\" &&\n          \"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1\",\n        className\n      )}\n      position={position}\n      {...props}\n    >\n      <SelectScrollUpButton />\n      <SelectPrimitive.Viewport\n        className={cn(\n          \"p-1\",\n          position === \"popper\" &&\n            \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]\"\n        )}\n      >\n        {children}\n      </SelectPrimitive.Viewport>\n      <SelectScrollDownButton />\n    </SelectPrimitive.Content>\n  </SelectPrimitive.Portal>\n))\nSelectContent.displayName = SelectPrimitive.Content.displayName\n\nconst SelectLabel = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.Label\n    ref={ref}\n    className={cn(\"py-1.5 pl-8 pr-2 text-sm font-semibold\", className)}\n    {...props}\n  />\n))\nSelectLabel.displayName = SelectPrimitive.Label.displayName\n\nconst SelectItem = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>\n>(({ className, children, ...props }, ref) => (\n  <SelectPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <SelectPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </SelectPrimitive.ItemIndicator>\n    </span>\n\n    <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n  </SelectPrimitive.Item>\n))\nSelectItem.displayName = SelectPrimitive.Item.displayName\n\nconst SelectSeparator = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-muted\", className)}\n    {...props}\n  />\n))\nSelectSeparator.displayName = SelectPrimitive.Separator.displayName\n\nexport {\n  Select,\n  SelectGroup,\n  SelectValue,\n  SelectTrigger,\n  SelectContent,\n  SelectLabel,\n  SelectItem,\n  SelectSeparator,\n  SelectScrollUpButton,\n  SelectScrollDownButton,\n}\n"
  },
  {
    "path": "frontend/components/ui/separator.tsx",
    "content": "'use client';\n\nimport * as React from 'react';\nimport * as SeparatorPrimitive from '@radix-ui/react-separator';\n\nimport { cn } from '@/lib/utils';\n\nconst Separator = React.forwardRef<\n  React.ElementRef<typeof SeparatorPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>\n>(\n  (\n    { className, orientation = 'horizontal', decorative = true, ...props },\n    ref\n  ) => (\n    <SeparatorPrimitive.Root\n      ref={ref}\n      decorative={decorative}\n      orientation={orientation}\n      className={cn(\n        'shrink-0 bg-accent-foreground',\n        orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',\n        className\n      )}\n      {...props}\n    />\n  )\n);\nSeparator.displayName = SeparatorPrimitive.Root.displayName;\n\nexport { Separator };\n"
  },
  {
    "path": "frontend/components/ui/sheet.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as SheetPrimitive from \"@radix-ui/react-dialog\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { X } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Sheet = SheetPrimitive.Root\n\nconst SheetTrigger = SheetPrimitive.Trigger\n\nconst SheetClose = SheetPrimitive.Close\n\nconst SheetPortal = SheetPrimitive.Portal\n\nconst SheetOverlay = React.forwardRef<\n  React.ElementRef<typeof SheetPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <SheetPrimitive.Overlay\n    className={cn(\n      \"fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0\",\n      className\n    )}\n    {...props}\n    ref={ref}\n  />\n))\nSheetOverlay.displayName = SheetPrimitive.Overlay.displayName\n\nconst sheetVariants = cva(\n  \"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500\",\n  {\n    variants: {\n      side: {\n        top: \"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top\",\n        bottom:\n          \"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom\",\n        left: \"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm\",\n        right:\n          \"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm\",\n      },\n    },\n    defaultVariants: {\n      side: \"right\",\n    },\n  }\n)\n\ninterface SheetContentProps\n  extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,\n    VariantProps<typeof sheetVariants> {}\n\nconst SheetContent = React.forwardRef<\n  React.ElementRef<typeof SheetPrimitive.Content>,\n  SheetContentProps\n>(({ side = \"right\", className, children, ...props }, ref) => (\n  <SheetPortal>\n    <SheetOverlay />\n    <SheetPrimitive.Content\n      ref={ref}\n      className={cn(sheetVariants({ side }), className)}\n      {...props}\n    >\n      {children}\n      <SheetPrimitive.Close className=\"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary\">\n        <X className=\"h-4 w-4\" />\n        <span className=\"sr-only\">Close</span>\n      </SheetPrimitive.Close>\n    </SheetPrimitive.Content>\n  </SheetPortal>\n))\nSheetContent.displayName = SheetPrimitive.Content.displayName\n\nconst SheetHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-2 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nSheetHeader.displayName = \"SheetHeader\"\n\nconst SheetFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nSheetFooter.displayName = \"SheetFooter\"\n\nconst SheetTitle = React.forwardRef<\n  React.ElementRef<typeof SheetPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <SheetPrimitive.Title\n    ref={ref}\n    className={cn(\"text-lg font-semibold text-foreground\", className)}\n    {...props}\n  />\n))\nSheetTitle.displayName = SheetPrimitive.Title.displayName\n\nconst SheetDescription = React.forwardRef<\n  React.ElementRef<typeof SheetPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <SheetPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nSheetDescription.displayName = SheetPrimitive.Description.displayName\n\nexport {\n  Sheet,\n  SheetPortal,\n  SheetOverlay,\n  SheetTrigger,\n  SheetClose,\n  SheetContent,\n  SheetHeader,\n  SheetFooter,\n  SheetTitle,\n  SheetDescription,\n}\n"
  },
  {
    "path": "frontend/components/ui/skeleton.tsx",
    "content": "import { cn } from \"@/lib/utils\"\n\nfunction Skeleton({\n  className,\n  ...props\n}: React.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": "frontend/components/ui/slider.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as SliderPrimitive from \"@radix-ui/react-slider\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Slider = React.forwardRef<\n  React.ElementRef<typeof SliderPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <SliderPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative flex w-full touch-none select-none items-center\",\n      className\n    )}\n    {...props}\n  >\n    <SliderPrimitive.Track className=\"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary\">\n      <SliderPrimitive.Range className=\"absolute h-full bg-primary\" />\n    </SliderPrimitive.Track>\n    <SliderPrimitive.Thumb className=\"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\" />\n  </SliderPrimitive.Root>\n))\nSlider.displayName = SliderPrimitive.Root.displayName\n\nexport { Slider }\n"
  },
  {
    "path": "frontend/components/ui/sonner.tsx",
    "content": "\"use client\"\n\nimport { useTheme } from \"next-themes\"\nimport { Toaster as Sonner } from \"sonner\"\n\ntype ToasterProps = React.ComponentProps<typeof Sonner>\n\nconst Toaster = ({ ...props }: ToasterProps) => {\n  const { theme = \"system\" } = useTheme()\n\n  return (\n    <Sonner\n      theme={theme as ToasterProps[\"theme\"]}\n      className=\"toaster group\"\n      toastOptions={{\n        classNames: {\n          toast:\n            \"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg\",\n          description: \"group-[.toast]:text-muted-foreground\",\n          actionButton:\n            \"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground\",\n          cancelButton:\n            \"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground\",\n        },\n      }}\n      {...props}\n    />\n  )\n}\n\nexport { Toaster }\n"
  },
  {
    "path": "frontend/components/ui/switch.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as SwitchPrimitives from \"@radix-ui/react-switch\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Switch = React.forwardRef<\n  React.ElementRef<typeof SwitchPrimitives.Root>,\n  React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>\n>(({ className, ...props }, ref) => (\n  <SwitchPrimitives.Root\n    className={cn(\n      \"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input\",\n      className\n    )}\n    {...props}\n    ref={ref}\n  >\n    <SwitchPrimitives.Thumb\n      className={cn(\n        \"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0\"\n      )}\n    />\n  </SwitchPrimitives.Root>\n))\nSwitch.displayName = SwitchPrimitives.Root.displayName\n\nexport { Switch }\n"
  },
  {
    "path": "frontend/components/ui/table.tsx",
    "content": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Table = React.forwardRef<\n  HTMLTableElement,\n  React.HTMLAttributes<HTMLTableElement>\n>(({ className, ...props }, ref) => (\n  <div className=\"relative w-full overflow-auto\">\n    <table\n      ref={ref}\n      className={cn(\"w-full caption-bottom text-sm\", className)}\n      {...props}\n    />\n  </div>\n))\nTable.displayName = \"Table\"\n\nconst TableHeader = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <thead ref={ref} className={cn(\"[&_tr]:border-b\", className)} {...props} />\n))\nTableHeader.displayName = \"TableHeader\"\n\nconst TableBody = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tbody\n    ref={ref}\n    className={cn(\"[&_tr:last-child]:border-0\", className)}\n    {...props}\n  />\n))\nTableBody.displayName = \"TableBody\"\n\nconst TableFooter = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tfoot\n    ref={ref}\n    className={cn(\n      \"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0\",\n      className\n    )}\n    {...props}\n  />\n))\nTableFooter.displayName = \"TableFooter\"\n\nconst TableRow = React.forwardRef<\n  HTMLTableRowElement,\n  React.HTMLAttributes<HTMLTableRowElement>\n>(({ className, ...props }, ref) => (\n  <tr\n    ref={ref}\n    className={cn(\n      \"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted\",\n      className\n    )}\n    {...props}\n  />\n))\nTableRow.displayName = \"TableRow\"\n\nconst TableHead = React.forwardRef<\n  HTMLTableCellElement,\n  React.ThHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <th\n    ref={ref}\n    className={cn(\n      \"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0\",\n      className\n    )}\n    {...props}\n  />\n))\nTableHead.displayName = \"TableHead\"\n\nconst TableCell = React.forwardRef<\n  HTMLTableCellElement,\n  React.TdHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <td\n    ref={ref}\n    className={cn(\"p-4 align-middle [&:has([role=checkbox])]:pr-0\", className)}\n    {...props}\n  />\n))\nTableCell.displayName = \"TableCell\"\n\nconst TableCaption = React.forwardRef<\n  HTMLTableCaptionElement,\n  React.HTMLAttributes<HTMLTableCaptionElement>\n>(({ className, ...props }, ref) => (\n  <caption\n    ref={ref}\n    className={cn(\"mt-4 text-sm text-muted-foreground\", className)}\n    {...props}\n  />\n))\nTableCaption.displayName = \"TableCaption\"\n\nexport {\n  Table,\n  TableHeader,\n  TableBody,\n  TableFooter,\n  TableHead,\n  TableRow,\n  TableCell,\n  TableCaption,\n}\n"
  },
  {
    "path": "frontend/components/ui/tabs.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Tabs = TabsPrimitive.Root\n\nconst TabsList = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.List\n    ref={ref}\n    className={cn(\n      \"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsList.displayName = TabsPrimitive.List.displayName\n\nconst TabsTrigger = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsTrigger.displayName = TabsPrimitive.Trigger.displayName\n\nconst TabsContent = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.Content\n    ref={ref}\n    className={cn(\n      \"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsContent.displayName = TabsPrimitive.Content.displayName\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent }\n"
  },
  {
    "path": "frontend/components/ui/textarea.tsx",
    "content": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface TextareaProps\n  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}\n\nconst Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(\n  ({ className, ...props }, ref) => {\n    return (\n      <textarea\n        className={cn(\n          \"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50\",\n          className\n        )}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nTextarea.displayName = \"Textarea\"\n\nexport { Textarea }\n"
  },
  {
    "path": "frontend/components/ui/toast.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as ToastPrimitives from \"@radix-ui/react-toast\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { X } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst ToastProvider = ToastPrimitives.Provider\n\nconst ToastViewport = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Viewport>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Viewport\n    ref={ref}\n    className={cn(\n      \"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]\",\n      className\n    )}\n    {...props}\n  />\n))\nToastViewport.displayName = ToastPrimitives.Viewport.displayName\n\nconst toastVariants = cva(\n  \"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full\",\n  {\n    variants: {\n      variant: {\n        default: \"border bg-background text-foreground\",\n        destructive:\n          \"destructive group border-destructive bg-destructive text-destructive-foreground\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nconst Toast = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Root>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &\n    VariantProps<typeof toastVariants>\n>(({ className, variant, ...props }, ref) => {\n  return (\n    <ToastPrimitives.Root\n      ref={ref}\n      className={cn(toastVariants({ variant }), className)}\n      {...props}\n    />\n  )\n})\nToast.displayName = ToastPrimitives.Root.displayName\n\nconst ToastAction = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Action>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Action\n    ref={ref}\n    className={cn(\n      \"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive\",\n      className\n    )}\n    {...props}\n  />\n))\nToastAction.displayName = ToastPrimitives.Action.displayName\n\nconst ToastClose = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Close>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Close\n    ref={ref}\n    className={cn(\n      \"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600\",\n      className\n    )}\n    toast-close=\"\"\n    {...props}\n  >\n    <X className=\"h-4 w-4\" />\n  </ToastPrimitives.Close>\n))\nToastClose.displayName = ToastPrimitives.Close.displayName\n\nconst ToastTitle = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Title>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Title\n    ref={ref}\n    className={cn(\"text-sm font-semibold\", className)}\n    {...props}\n  />\n))\nToastTitle.displayName = ToastPrimitives.Title.displayName\n\nconst ToastDescription = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Description>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Description\n    ref={ref}\n    className={cn(\"text-sm opacity-90\", className)}\n    {...props}\n  />\n))\nToastDescription.displayName = ToastPrimitives.Description.displayName\n\ntype ToastProps = React.ComponentPropsWithoutRef<typeof Toast>\n\ntype ToastActionElement = React.ReactElement<typeof ToastAction>\n\nexport {\n  type ToastProps,\n  type ToastActionElement,\n  ToastProvider,\n  ToastViewport,\n  Toast,\n  ToastTitle,\n  ToastDescription,\n  ToastClose,\n  ToastAction,\n}\n"
  },
  {
    "path": "frontend/components/ui/toaster.tsx",
    "content": "\"use client\"\n\nimport {\n  Toast,\n  ToastClose,\n  ToastDescription,\n  ToastProvider,\n  ToastTitle,\n  ToastViewport,\n} from \"@/components/ui/toast\"\nimport { useToast } from \"@/components/ui/use-toast\"\n\nexport function Toaster() {\n  const { toasts } = useToast()\n\n  return (\n    <ToastProvider>\n      {toasts.map(function ({ id, title, description, action, ...props }) {\n        return (\n          <Toast key={id} {...props}>\n            <div className=\"grid gap-1\">\n              {title && <ToastTitle>{title}</ToastTitle>}\n              {description && (\n                <ToastDescription>{description}</ToastDescription>\n              )}\n            </div>\n            {action}\n            <ToastClose />\n          </Toast>\n        )\n      })}\n      <ToastViewport />\n    </ToastProvider>\n  )\n}\n"
  },
  {
    "path": "frontend/components/ui/toggle-group.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as ToggleGroupPrimitive from \"@radix-ui/react-toggle-group\"\nimport { type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\nimport { toggleVariants } from \"@/components/ui/toggle\"\n\nconst ToggleGroupContext = React.createContext<\n  VariantProps<typeof toggleVariants>\n>({\n  size: \"default\",\n  variant: \"default\",\n})\n\nconst ToggleGroup = React.forwardRef<\n  React.ElementRef<typeof ToggleGroupPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &\n    VariantProps<typeof toggleVariants>\n>(({ className, variant, size, children, ...props }, ref) => (\n  <ToggleGroupPrimitive.Root\n    ref={ref}\n    className={cn(\"flex items-center justify-center gap-1\", className)}\n    {...props}\n  >\n    <ToggleGroupContext.Provider value={{ variant, size }}>\n      {children}\n    </ToggleGroupContext.Provider>\n  </ToggleGroupPrimitive.Root>\n))\n\nToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName\n\nconst ToggleGroupItem = React.forwardRef<\n  React.ElementRef<typeof ToggleGroupPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &\n    VariantProps<typeof toggleVariants>\n>(({ className, children, variant, size, ...props }, ref) => {\n  const context = React.useContext(ToggleGroupContext)\n\n  return (\n    <ToggleGroupPrimitive.Item\n      ref={ref}\n      className={cn(\n        toggleVariants({\n          variant: context.variant || variant,\n          size: context.size || size,\n        }),\n        className\n      )}\n      {...props}\n    >\n      {children}\n    </ToggleGroupPrimitive.Item>\n  )\n})\n\nToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName\n\nexport { ToggleGroup, ToggleGroupItem }\n"
  },
  {
    "path": "frontend/components/ui/toggle.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as TogglePrimitive from \"@radix-ui/react-toggle\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst toggleVariants = cva(\n  \"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-transparent\",\n        outline:\n          \"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground\",\n      },\n      size: {\n        default: \"h-10 px-3\",\n        sm: \"h-9 px-2.5\",\n        lg: \"h-11 px-5\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n      size: \"default\",\n    },\n  }\n)\n\nconst Toggle = React.forwardRef<\n  React.ElementRef<typeof TogglePrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &\n    VariantProps<typeof toggleVariants>\n>(({ className, variant, size, ...props }, ref) => (\n  <TogglePrimitive.Root\n    ref={ref}\n    className={cn(toggleVariants({ variant, size, className }))}\n    {...props}\n  />\n))\n\nToggle.displayName = TogglePrimitive.Root.displayName\n\nexport { Toggle, toggleVariants }\n"
  },
  {
    "path": "frontend/components/ui/tooltip.tsx",
    "content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst TooltipProvider = TooltipPrimitive.Provider\n\nconst Tooltip = TooltipPrimitive.Root\n\nconst TooltipTrigger = TooltipPrimitive.Trigger\n\nconst TooltipContent = React.forwardRef<\n  React.ElementRef<typeof TooltipPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n  <TooltipPrimitive.Content\n    ref={ref}\n    sideOffset={sideOffset}\n    className={cn(\n      \"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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))\nTooltipContent.displayName = TooltipPrimitive.Content.displayName\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }\n"
  },
  {
    "path": "frontend/components/ui/upload-image-preview.tsx",
    "content": "import { XCircleIcon } from \"lucide-react\";\nimport Image from \"next/image\";\nimport { cn } from \"../../lib/utils\";\n\nexport default function UploadImagePreview({\n  url,\n  onRemove,\n}: {\n  url: string;\n  onRemove: () => void;\n}) {\n  return (\n    <div className=\"relative w-20 h-20 group\">\n      <Image\n        src={url}\n        alt=\"Uploaded image\"\n        fill\n        className=\"object-cover w-full h-full rounded-xl hover:brightness-75\"\n      />\n      <div\n        className={cn(\n          \"absolute -top-2 -right-2 w-6 h-6 z-10 bg-gray-500 text-white rounded-full hidden group-hover:block\"\n        )}\n      >\n        <XCircleIcon\n          className=\"w-6 h-6 bg-gray-500 text-white rounded-full\"\n          onClick={onRemove}\n        />\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "frontend/components/ui/use-toast.ts",
    "content": "\"use client\"\n\n// Inspired by react-hot-toast library\nimport * as React from \"react\"\n\nimport type {\n  ToastActionElement,\n  ToastProps,\n} from \"@/components/ui/toast\"\n\nconst TOAST_LIMIT = 1\nconst TOAST_REMOVE_DELAY = 1000000\n\ntype ToasterToast = ToastProps & {\n  id: string\n  title?: React.ReactNode\n  description?: React.ReactNode\n  action?: ToastActionElement\n}\n\nconst actionTypes = {\n  ADD_TOAST: \"ADD_TOAST\",\n  UPDATE_TOAST: \"UPDATE_TOAST\",\n  DISMISS_TOAST: \"DISMISS_TOAST\",\n  REMOVE_TOAST: \"REMOVE_TOAST\",\n} as const\n\nlet count = 0\n\nfunction genId() {\n  count = (count + 1) % Number.MAX_SAFE_INTEGER\n  return count.toString()\n}\n\ntype ActionType = typeof actionTypes\n\ntype Action =\n  | {\n      type: ActionType[\"ADD_TOAST\"]\n      toast: ToasterToast\n    }\n  | {\n      type: ActionType[\"UPDATE_TOAST\"]\n      toast: Partial<ToasterToast>\n    }\n  | {\n      type: ActionType[\"DISMISS_TOAST\"]\n      toastId?: ToasterToast[\"id\"]\n    }\n  | {\n      type: ActionType[\"REMOVE_TOAST\"]\n      toastId?: ToasterToast[\"id\"]\n    }\n\ninterface State {\n  toasts: ToasterToast[]\n}\n\nconst toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()\n\nconst addToRemoveQueue = (toastId: string) => {\n  if (toastTimeouts.has(toastId)) {\n    return\n  }\n\n  const timeout = setTimeout(() => {\n    toastTimeouts.delete(toastId)\n    dispatch({\n      type: \"REMOVE_TOAST\",\n      toastId: toastId,\n    })\n  }, TOAST_REMOVE_DELAY)\n\n  toastTimeouts.set(toastId, timeout)\n}\n\nexport const reducer = (state: State, action: Action): State => {\n  switch (action.type) {\n    case \"ADD_TOAST\":\n      return {\n        ...state,\n        toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),\n      }\n\n    case \"UPDATE_TOAST\":\n      return {\n        ...state,\n        toasts: state.toasts.map((t) =>\n          t.id === action.toast.id ? { ...t, ...action.toast } : t\n        ),\n      }\n\n    case \"DISMISS_TOAST\": {\n      const { toastId } = action\n\n      // ! Side effects ! - This could be extracted into a dismissToast() action,\n      // but I'll keep it here for simplicity\n      if (toastId) {\n        addToRemoveQueue(toastId)\n      } else {\n        state.toasts.forEach((toast) => {\n          addToRemoveQueue(toast.id)\n        })\n      }\n\n      return {\n        ...state,\n        toasts: state.toasts.map((t) =>\n          t.id === toastId || toastId === undefined\n            ? {\n                ...t,\n                open: false,\n              }\n            : t\n        ),\n      }\n    }\n    case \"REMOVE_TOAST\":\n      if (action.toastId === undefined) {\n        return {\n          ...state,\n          toasts: [],\n        }\n      }\n      return {\n        ...state,\n        toasts: state.toasts.filter((t) => t.id !== action.toastId),\n      }\n  }\n}\n\nconst listeners: Array<(state: State) => void> = []\n\nlet memoryState: State = { toasts: [] }\n\nfunction dispatch(action: Action) {\n  memoryState = reducer(memoryState, action)\n  listeners.forEach((listener) => {\n    listener(memoryState)\n  })\n}\n\ntype Toast = Omit<ToasterToast, \"id\">\n\nfunction toast({ ...props }: Toast) {\n  const id = genId()\n\n  const update = (props: ToasterToast) =>\n    dispatch({\n      type: \"UPDATE_TOAST\",\n      toast: { ...props, id },\n    })\n  const dismiss = () => dispatch({ type: \"DISMISS_TOAST\", toastId: id })\n\n  dispatch({\n    type: \"ADD_TOAST\",\n    toast: {\n      ...props,\n      id,\n      open: true,\n      onOpenChange: (open) => {\n        if (!open) dismiss()\n      },\n    },\n  })\n\n  return {\n    id: id,\n    dismiss,\n    update,\n  }\n}\n\nfunction useToast() {\n  const [state, setState] = React.useState<State>(memoryState)\n\n  React.useEffect(() => {\n    listeners.push(setState)\n    return () => {\n      const index = listeners.indexOf(setState)\n      if (index > -1) {\n        listeners.splice(index, 1)\n      }\n    }\n  }, [state])\n\n  return {\n    ...state,\n    toast,\n    dismiss: (toastId?: string) => dispatch({ type: \"DISMISS_TOAST\", toastId }),\n  }\n}\n\nexport { useToast, toast }\n"
  },
  {
    "path": "frontend/components.json",
    "content": "{\n  \"$schema\": \"https://ui.shadcn.com/schema.json\",\n  \"style\": \"default\",\n  \"rsc\": true,\n  \"tsx\": true,\n  \"tailwind\": {\n    \"config\": \"tailwind.config.ts\",\n    \"css\": \"app/globals.css\",\n    \"baseColor\": \"neutral\",\n    \"cssVariables\": true,\n    \"prefix\": \"\"\n  },\n  \"aliases\": {\n    \"components\": \"@/components\",\n    \"utils\": \"@/lib/utils\"\n  }\n}\n"
  },
  {
    "path": "frontend/config/features.ts",
    "content": "export const Features = [\n  {\n    title: 'Basic Authentication',\n    description:\n      'Secure your RAG-based application with built-in authentication. Protect sensitive data and ensure only authorized users can access your system.',\n    link: '/features/authentication',\n  },\n  {\n    title: 'Chat History Tracking',\n    description:\n      'Keep track of user interactions and chat histories. Analyze conversations to improve your RAG model and provide better user experiences over time.',\n    link: '/features/chat-history',\n  },\n  {\n    title: 'Multiple RAG Variations',\n    description:\n      'Choose from multiple RAG configurations, including Basic RAG and two additional setups. Tailor your retrieval-augmented generation to suit your specific use case.',\n    link: '/features/rag-variations',\n  },\n  {\n    title: 'Admin Dashboard',\n    description:\n      'Manage your RAG-SaaS application with ease using the comprehensive admin dashboard. Control data ingestion, monitor system performance, and switch between RAG configurations.',\n    link: '/features/admin-dashboard',\n  },\n  {\n    title: 'Data Ingestion',\n    description:\n      'Easily ingest new data into your RAG system. Keep your knowledge base up-to-date and relevant with simple data upload and processing tools.',\n    link: '/features/data-ingestion',\n  },\n  {\n    title: 'System Monitoring',\n    description:\n      'Keep an eye on your RAG-SaaS applications performance. Monitor key metrics and ensure optimal functioning of your retrieval and generation processes.',\n    link: '/features/monitoring',\n  },\n  {\n    title: 'S3 Integration',\n    description:\n      'Seamlessly integrate with Amazon S3 for PDF uploads. Store and retrieve documents efficiently, enhancing your RAG systems knowledge base.',\n    link: '/features/s3-integration',\n  },\n  {\n    title: 'Docker Deployment',\n    description:\n      'Deploy your RAG-SaaS application quickly and consistently using Docker. Ensure your system runs smoothly across different environments with containerization.',\n    link: '/features/docker-deployment',\n  },\n  {\n    title: 'Customizable Tech Stack',\n    description:\n      'Built on a robust tech stack including LlamaIndex, MongoDB, FastAPI, and Next.js. Customize and extend your RAG-SaaS application to meet your specific needs.',\n    link: '/features/tech-stack',\n  },\n];\n"
  },
  {
    "path": "frontend/config/site.ts",
    "content": "import { SiteConfig } from '@/types';\n\nexport const siteConfig: SiteConfig = {\n  name: 'RAG SAAS',\n  description: 'RAG-SaaS: Ship RAG Solutions Quickly',\n  url: 'https://rag.cognitivelab.in/',\n  ogImage: 'https://rag.cognitivelab.in/og.jpg',\n  links: {\n    twitter: 'https://x.com/adithya_s_k',\n    github: 'https://github.com/adithya-s-k/RAG-SaaS',\n  },\n};\n"
  },
  {
    "path": "frontend/config/tools.json",
    "content": "{\n  \"local\": {\n    \"duckduckgo\": {}\n  },\n  \"llamahub\": {}\n}"
  },
  {
    "path": "frontend/hooks/useGitHubStars.tsx",
    "content": "'use client';\n\nimport { useState, useEffect } from 'react';\n\nconst useGitHubStars = (repoName: string) => {\n  const [stars, setStars] = useState(300); // Default value\n\n  useEffect(() => {\n    const fetchStars = async () => {\n      try {\n        const response = await fetch(\n          `https://api.github.com/repos/${repoName}`,\n          {\n            headers: process.env.NEXT_PUBLIC_GITHUB_OAUTH_TOKEN\n              ? {\n                  Authorization: `Bearer ${process.env.NEXT_PUBLIC_GITHUB_OAUTH_TOKEN}`,\n                  'Content-Type': 'application/json',\n                }\n              : {},\n            next: {\n              revalidate: 3600,\n            },\n          }\n        );\n\n        if (response.ok) {\n          const data = await response.json();\n          setStars(data.stargazers_count || stars);\n        }\n      } catch (error) {\n        console.error('Error fetching GitHub stars:', error);\n      }\n    };\n\n    fetchStars();\n  }, [repoName]);\n\n  return stars;\n};\n\nexport default useGitHubStars;\n"
  },
  {
    "path": "frontend/lib/utils.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": "frontend/next.config.mjs",
    "content": "/** @type {import('next').NextConfig} */\nconst nextConfig = {\n  output: \"standalone\",\n};\n\nexport default nextConfig;"
  },
  {
    "path": "frontend/package.json",
    "content": "{\n  \"name\": \"frontend\",\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    \"@llamaindex/pdf-viewer\": \"^1.1.3\",\n    \"@radix-ui/react-accordion\": \"^1.2.0\",\n    \"@radix-ui/react-alert-dialog\": \"^1.1.1\",\n    \"@radix-ui/react-aspect-ratio\": \"^1.1.0\",\n    \"@radix-ui/react-avatar\": \"^1.1.0\",\n    \"@radix-ui/react-checkbox\": \"^1.1.1\",\n    \"@radix-ui/react-collapsible\": \"^1.1.0\",\n    \"@radix-ui/react-context-menu\": \"^2.2.1\",\n    \"@radix-ui/react-dialog\": \"^1.1.1\",\n    \"@radix-ui/react-dropdown-menu\": \"^2.1.1\",\n    \"@radix-ui/react-hover-card\": \"^1.1.1\",\n    \"@radix-ui/react-label\": \"^2.1.0\",\n    \"@radix-ui/react-menubar\": \"^1.1.1\",\n    \"@radix-ui/react-navigation-menu\": \"^1.2.0\",\n    \"@radix-ui/react-popover\": \"^1.1.1\",\n    \"@radix-ui/react-progress\": \"^1.1.0\",\n    \"@radix-ui/react-radio-group\": \"^1.2.0\",\n    \"@radix-ui/react-scroll-area\": \"^1.1.0\",\n    \"@radix-ui/react-select\": \"^2.1.1\",\n    \"@radix-ui/react-separator\": \"^1.1.0\",\n    \"@radix-ui/react-slider\": \"^1.2.0\",\n    \"@radix-ui/react-slot\": \"^1.1.0\",\n    \"@radix-ui/react-switch\": \"^1.1.0\",\n    \"@radix-ui/react-tabs\": \"^1.1.0\",\n    \"@radix-ui/react-toast\": \"^1.2.1\",\n    \"@radix-ui/react-toggle\": \"^1.1.0\",\n    \"@radix-ui/react-toggle-group\": \"^1.1.0\",\n    \"@radix-ui/react-tooltip\": \"^1.1.2\",\n    \"@types/mdast\": \"^4.0.4\",\n    \"@vercel/analytics\": \"^1.3.1\",\n    \"ai\": \"^3.3.16\",\n    \"axios\": \"^1.7.5\",\n    \"class-variance-authority\": \"^0.7.0\",\n    \"clsx\": \"^2.1.1\",\n    \"cmdk\": \"^1.0.0\",\n    \"framer-motion\": \"^11.3.30\",\n    \"input-otp\": \"^1.2.4\",\n    \"js-cookie\": \"^3.0.5\",\n    \"jwt-decode\": \"^4.0.0\",\n    \"llamaindex\": \"^0.5.19\",\n    \"lucide-react\": \"^0.435.0\",\n    \"next\": \"14.2.6\",\n    \"next-themes\": \"^0.3.0\",\n    \"react\": \"^18\",\n    \"react-dom\": \"^18\",\n    \"react-dropzone\": \"^14.2.3\",\n    \"react-hook-form\": \"^7.52.2\",\n    \"react-markdown\": \"^9.0.1\",\n    \"react-resizable-panels\": \"^2.1.1\",\n    \"rehype-katex\": \"7.0.0\",\n    \"remark\": \"^15.0.1\",\n    \"remark-code-import\": \"^1.2.0\",\n    \"remark-gfm\": \"^3.0.1\",\n    \"remark-math\": \"^6.0.0\",\n    \"sonner\": \"^1.5.0\",\n    \"tailwind-merge\": \"^2.5.2\",\n    \"tailwindcss-animate\": \"^1.0.7\",\n    \"uuid\": \"^10.0.0\",\n    \"vaul\": \"^0.9.1\",\n    \"zod\": \"^3.23.8\"\n  },\n  \"devDependencies\": {\n    \"@hookform/resolvers\": \"^3.9.0\",\n    \"@types/js-cookie\": \"^3.0.6\",\n    \"@types/node\": \"^20\",\n    \"@types/react\": \"^18\",\n    \"@types/react-dom\": \"^18\",\n    \"@types/react-syntax-highlighter\": \"^15.5.13\",\n    \"@types/uuid\": \"^10.0.0\",\n    \"eslint\": \"^8\",\n    \"eslint-config-next\": \"14.2.6\",\n    \"postcss\": \"^8\",\n    \"react-syntax-highlighter\": \"^15.5.0\",\n    \"tailwindcss\": \"^3.4.1\",\n    \"typescript\": \"^5\"\n  }\n}\n"
  },
  {
    "path": "frontend/postcss.config.mjs",
    "content": "/** @type {import('postcss-load-config').Config} */\nconst config = {\n  plugins: {\n    tailwindcss: {},\n  },\n};\n\nexport default config;\n"
  },
  {
    "path": "frontend/public/site.webmanifest",
    "content": "{\n  \"name\": \"\",\n  \"short_name\": \"\",\n  \"icons\": [\n    {\n      \"src\": \"/android-chrome-192x192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    },\n    {\n      \"src\": \"/android-chrome-512x512.png\",\n      \"sizes\": \"512x512\",\n      \"type\": \"image/png\"\n    }\n  ],\n  \"theme_color\": \"#ffffff\",\n  \"background_color\": \"#ffffff\",\n  \"display\": \"standalone\"\n}\n"
  },
  {
    "path": "frontend/tailwind.config.ts",
    "content": "import type { Config } from 'tailwindcss';\n\nconst config = {\n  darkMode: ['class'],\n  content: [\n    './pages/**/*.{ts,tsx}',\n    './components/**/*.{ts,tsx}',\n    './app/**/*.{ts,tsx}',\n    './src/**/*.{ts,tsx}',\n  ],\n  prefix: '',\n  theme: {\n    container: {\n      center: true,\n      padding: '2rem',\n      screens: {\n        '2xl': '1400px',\n      },\n    },\n    extend: {\n      colors: {\n        border: 'hsl(var(--border))',\n        input: 'hsl(var(--input))',\n        ring: 'hsl(var(--ring))',\n        background: 'hsl(var(--background))',\n        foreground: 'hsl(var(--foreground))',\n        primary: {\n          DEFAULT: 'hsl(var(--primary))',\n          foreground: 'hsl(var(--primary-foreground))',\n        },\n        secondary: {\n          DEFAULT: 'hsl(var(--secondary))',\n          foreground: 'hsl(var(--secondary-foreground))',\n        },\n        destructive: {\n          DEFAULT: 'hsl(var(--destructive))',\n          foreground: 'hsl(var(--destructive-foreground))',\n        },\n        muted: {\n          DEFAULT: 'hsl(var(--muted))',\n          foreground: 'hsl(var(--muted-foreground))',\n        },\n        accent: {\n          DEFAULT: 'hsl(var(--accent))',\n          foreground: 'hsl(var(--accent-foreground))',\n        },\n        popover: {\n          DEFAULT: 'hsl(var(--popover))',\n          foreground: 'hsl(var(--popover-foreground))',\n        },\n        card: {\n          DEFAULT: 'hsl(var(--card))',\n          foreground: 'hsl(var(--card-foreground))',\n        },\n      },\n      borderRadius: {\n        lg: 'var(--radius)',\n        md: 'calc(var(--radius) - 2px)',\n        sm: 'calc(var(--radius) - 4px)',\n      },\n      keyframes: {\n        'accordion-down': {\n          from: { height: '0' },\n          to: { height: 'var(--radix-accordion-content-height)' },\n        },\n        'accordion-up': {\n          from: { height: 'var(--radix-accordion-content-height)' },\n          to: { height: '0' },\n        },\n        ripple: {\n          '0%, 100%': {\n            transform: 'translate(-50%, -50%) scale(1)',\n          },\n          '50%': {\n            transform: 'translate(-50%, -50%) scale(0.9)',\n          },\n        },\n        gradient: {\n          to: {\n            backgroundPosition: 'var(--bg-size) 0',\n          },\n        },\n      },\n      animation: {\n        'accordion-down': 'accordion-down 0.2s ease-out',\n        'accordion-up': 'accordion-up 0.2s ease-out',\n        ripple: 'ripple var(--duration,2s) ease calc(var(--i, 0)*.2s) infinite',\n        gradient: 'gradient 8s linear infinite',\n      },\n    },\n  },\n  plugins: [require('tailwindcss-animate')],\n} satisfies Config;\n\nexport default config;\n"
  },
  {
    "path": "frontend/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\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    }\n  },\n  \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\", \".next/types/**/*.ts\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "frontend/types/index.d.ts",
    "content": "export type SiteConfig = {\n  name: string;\n  description: string;\n  url: string;\n  ogImage: string;\n  links: {\n    twitter: string;\n    github: string;\n  };\n};\n"
  }
]