Repository: adithya-s-k/RAG-SaaS Branch: main Commit: 751ab3a4ad79 Files: 191 Total size: 505.7 KB Directory structure: gitextract_kge9g_mh/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ └── PULL_REQUEST_TEMPLATE/ │ └── pull_request_template.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSING.md ├── README.md ├── backend/ │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── app/ │ │ ├── __init__.py │ │ ├── api/ │ │ │ ├── __init__.py │ │ │ ├── admin/ │ │ │ │ ├── __init__.py │ │ │ │ └── route.py │ │ │ ├── auth/ │ │ │ │ ├── __init__.py │ │ │ │ └── route.py │ │ │ ├── chat/ │ │ │ │ ├── __init__.py │ │ │ │ ├── chat_config.py │ │ │ │ ├── engine/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── engine.py │ │ │ │ │ ├── generate.py │ │ │ │ │ ├── index.py │ │ │ │ │ ├── loaders/ │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── db.py │ │ │ │ │ │ ├── file.py │ │ │ │ │ │ └── web.py │ │ │ │ │ ├── node_postprocessors.py │ │ │ │ │ ├── query_filter.py │ │ │ │ │ └── vectordb.py │ │ │ │ ├── events.py │ │ │ │ ├── models.py │ │ │ │ ├── route.py │ │ │ │ ├── services/ │ │ │ │ │ ├── file.py │ │ │ │ │ └── suggestion.py │ │ │ │ ├── summary.py │ │ │ │ ├── upload.py │ │ │ │ └── vercel_response.py │ │ │ └── conversation/ │ │ │ ├── __init__.py │ │ │ └── route.py │ │ ├── config.py │ │ ├── core/ │ │ │ ├── config.py │ │ │ ├── security.py │ │ │ └── user.py │ │ ├── db.py │ │ ├── llmhub.py │ │ ├── models/ │ │ │ └── user_model.py │ │ ├── observability.py │ │ ├── schemas/ │ │ │ ├── admin_schema.py │ │ │ ├── auth_schema.py │ │ │ └── user_schema.py │ │ ├── services/ │ │ │ ├── __init__.py │ │ │ ├── admin_service.py │ │ │ ├── config_service.py │ │ │ ├── conversation_service.py │ │ │ └── user_service.py │ │ └── settings.py │ ├── config/ │ │ ├── loaders.yaml │ │ └── tools.yaml │ ├── main.py │ ├── pyproject.toml │ └── tests/ │ └── __init__.py ├── docker-compose.yaml └── frontend/ ├── .eslintrc.json ├── .gitignore ├── Dockerfile ├── README.md ├── app/ │ ├── (auth)/ │ │ ├── signin/ │ │ │ └── page.tsx │ │ └── signup/ │ │ └── page.tsx │ ├── ConversationContext.tsx │ ├── admin/ │ │ ├── AdminAuthProvider.tsx │ │ ├── DataIngestion.tsx │ │ ├── RAGConfiguration.tsx │ │ ├── UsersManagement.tsx │ │ ├── layout.tsx │ │ └── page.tsx │ ├── authProvider.tsx │ ├── chat/ │ │ └── page.tsx │ ├── features/ │ │ └── page.tsx │ ├── globals.css │ ├── layout.tsx │ ├── markdown.css │ ├── page.tsx │ └── share/ │ └── page.tsx ├── components/ │ ├── analytics.tsx │ ├── banner-card.tsx │ ├── header.tsx │ ├── history.tsx │ ├── loading.tsx │ ├── magicui/ │ │ ├── animated-gradient-text.tsx │ │ ├── border-beam.tsx │ │ ├── box-reveal.tsx │ │ ├── gradual-spacing.tsx │ │ ├── hyper-text.tsx │ │ ├── meteors.tsx │ │ ├── neon-gradient-card.tsx │ │ ├── number-ticker.tsx │ │ ├── ripple.tsx │ │ ├── shimmer-button.tsx │ │ ├── shine-border.tsx │ │ ├── shiny-button.tsx │ │ ├── sparkles-text.tsx │ │ └── typing-animation.tsx │ ├── sidebar.tsx │ ├── theme-provider.tsx │ ├── theme-toggle.tsx │ └── ui/ │ ├── accordion.tsx │ ├── alert-dialog.tsx │ ├── alert.tsx │ ├── aspect-ratio.tsx │ ├── avatar.tsx │ ├── badge.tsx │ ├── breadcrumb.tsx │ ├── button.tsx │ ├── card-hover-effect.tsx │ ├── card.tsx │ ├── chat/ │ │ ├── chat-actions.tsx │ │ ├── chat-input.tsx │ │ ├── chat-message/ │ │ │ ├── chat-avatar.tsx │ │ │ ├── chat-events.tsx │ │ │ ├── chat-files.tsx │ │ │ ├── chat-image.tsx │ │ │ ├── chat-sources.tsx │ │ │ ├── chat-suggestedQuestions.tsx │ │ │ ├── chat-tools.tsx │ │ │ ├── codeblock.tsx │ │ │ ├── index.tsx │ │ │ └── markdown.tsx │ │ ├── chat-messages.tsx │ │ ├── chat.interface.ts │ │ ├── hooks/ │ │ │ ├── use-config.ts │ │ │ ├── use-copy-to-clipboard.tsx │ │ │ └── use-file.ts │ │ ├── index.ts │ │ └── widgets/ │ │ ├── PdfDialog.tsx │ │ └── WeatherCard.tsx │ ├── checkbox.tsx │ ├── collapsible.tsx │ ├── command.tsx │ ├── context-menu.tsx │ ├── dialog.tsx │ ├── document-preview.tsx │ ├── drawer.tsx │ ├── dropdown-menu.tsx │ ├── file-upload.tsx │ ├── file-uploader.tsx │ ├── form.tsx │ ├── hover-card.tsx │ ├── input-otp.tsx │ ├── input.tsx │ ├── label.tsx │ ├── menubar.tsx │ ├── navigation-menu.tsx │ ├── pagination.tsx │ ├── placeholders-and-vanish-input.tsx │ ├── popover.tsx │ ├── progress.tsx │ ├── radio-group.tsx │ ├── resizable.tsx │ ├── scroll-area.tsx │ ├── select.tsx │ ├── separator.tsx │ ├── sheet.tsx │ ├── skeleton.tsx │ ├── slider.tsx │ ├── sonner.tsx │ ├── switch.tsx │ ├── table.tsx │ ├── tabs.tsx │ ├── textarea.tsx │ ├── toast.tsx │ ├── toaster.tsx │ ├── toggle-group.tsx │ ├── toggle.tsx │ ├── tooltip.tsx │ ├── upload-image-preview.tsx │ └── use-toast.ts ├── components.json ├── config/ │ ├── features.ts │ ├── site.ts │ └── tools.json ├── hooks/ │ └── useGitHubStars.tsx ├── lib/ │ └── utils.ts ├── next.config.mjs ├── package.json ├── postcss.config.mjs ├── public/ │ └── site.webmanifest ├── tailwind.config.ts ├── tsconfig.json └── types/ └── index.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/PULL_REQUEST_TEMPLATE/pull_request_template.md ================================================ # Pull Request Template ## Description Please 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. Fixes # (issue) ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ## How Has This Been Tested? Please 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 - [ ] Test A - [ ] Test B ## Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] Any dependent changes have been merged and published in downstream modules ## Additional context Add any other context or screenshots about the pull request here. ================================================ FILE: .gitignore ================================================ /rag-venv /ragsaas-venvs backend/poetry.lock backend/rag_config.json backend/data/** ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to RAG-SaaS First 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. ## Table of Contents 1. [Code of Conduct](#code-of-conduct) 2. [Getting Started](#getting-started) 3. [How Can I Contribute?](#how-can-i-contribute) - [Reporting Bugs](#reporting-bugs) - [Suggesting Enhancements](#suggesting-enhancements) - [Your First Code Contribution](#your-first-code-contribution) - [Pull Requests](#pull-requests) 4. [Style Guidelines](#style-guidelines) - [Git Commit Messages](#git-commit-messages) - [Python Style Guide](#python-style-guide) - [JavaScript Style Guide](#javascript-style-guide) 5. [Additional Notes](#additional-notes) ## Code of Conduct This 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). ## Getting Started 1. Fork the repository on GitHub 2. Clone your fork locally 3. Set up your environment (see README.md for details) 4. Create a branch for your changes 5. Make your changes 6. Run tests and ensure they pass 7. Commit your changes 8. Push your changes to your fork 9. Open a pull request ## How Can I Contribute? ### Reporting Bugs - Before submitting a bug report, please check the existing issues to see if someone has already reported the problem. - 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. ### Suggesting Enhancements - Before creating enhancement suggestions, please check the existing issues to see if the enhancement has already been suggested. - 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. ### Your First Code Contribution Unsure where to begin contributing to RAG-SaaS? You can start by looking through these `beginner` and `help-wanted` issues: - [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. - [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. ### Pull Requests - Fill in the required template - Do not include issue numbers in the PR title - Include screenshots and animated GIFs in your pull request whenever possible - Follow the [Python](#python-style-guide) and [JavaScript](#javascript-style-guide) style guides - Document new code based on the Documentation Style Guide - End all files with a newline ## Style Guidelines ### Git Commit Messages - Use the present tense ("Add feature" not "Added feature") - Use the imperative mood ("Move cursor to..." not "Moves cursor to...") - Limit the first line to 72 characters or less - Reference issues and pull requests liberally after the first line ### Python Style Guide - Follow [PEP 8](https://www.python.org/dev/peps/pep-0008/) - Use 4 spaces for indentation (not tabs) - Use docstrings for functions and classes - Use type hints where possible ### JavaScript Style Guide - Use 2 spaces for indentation (not tabs) - Use semicolons at the end of each statement - Use single quotes for strings - Use camelCase for variable and function names - Use PascalCase for class names ## Additional Notes ### Issue and Pull Request Labels This section lists the labels we use to help us track and manage issues and pull requests. - `bug` - Issues for bugs in the code - `enhancement` - Issues for new features or improvements - `documentation` - Issues related to documentation - `good first issue` - Good for newcomers - `help wanted` - Extra attention is needed - `question` - Further information is requested Thank you for contributing to RAG-SaaS! ================================================ FILE: LICENSE ================================================ RAG-SaaS Dual License This project is licensed under two licenses: 1. Apache License, Version 2.0 (for students, developers, and individuals) 2. GNU General Public License v3.0 (for companies and commercial use) The full text of both licenses is included below. Please see LICENSING.md for details on which license applies to your use case. --- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2024] [Adithya S Kolavi] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 2024 Adithya S Kolavi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) 2024 Adithya S Kolavi This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: LICENSING.md ================================================ # Licensing for RAG-SaaS RAG-SaaS is released under a dual licensing model designed to accommodate both open-source and commercial use. ## For Students, Developers, Individuals, and Educational Institutions If 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**. The Apache License 2.0 allows you to: - Use the software for any purpose, including commercial purposes - Modify the software and distribute your modifications - Distribute the software, in source or binary forms - Sublicense the software For the full terms of the Apache License 2.0, please see the [LICENSE](LICENSE) file in this repository. ## For Companies and Commercial Use (Non-Educational) If 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)**. The GPL-3.0 requires that: - Any modifications to the software must also be released under the GPL-3.0 - If you distribute the software, you must make the source code available - Any software that incorporates GPL-3.0 licensed code must also be released under the GPL-3.0 For the full terms of the GNU General Public License v3.0, please see the [LICENSE](LICENSE) file in this repository. ## Choosing the Appropriate License 1. 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. 2. 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. ## Additional Notes - 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. - If you are unsure which license applies to your use case, please contact us for clarification. - Contributions to this project will be accepted under the terms of both licenses. ## Contact If you have any questions about licensing, please open an issue in the GitHub repository or contact the project maintainers at [your contact email]. By using this software, you agree to abide by the terms of the applicable license. ================================================ FILE: README.md ================================================

RAG SaaS

Ship RAG solutions quickly⚡

RAG-SaaS Logo

A end to end SaaS Solution for Retrieval-Augmented Generation (RAG)
and Agentic based applications.

Features · Tech Stack · Getting Started · Deployment · Roadmap

GitHub Stars GitHub Forks GitHub Issues GitHub Pull Requests

Features Demo Video
  • 🔐 Basic Authentication
  • 💬 Chat History Tracking
  • 🧠 Multiple RAG Variations
    • Basic RAG
    • Two additional configurations
  • 👨‍💼 Admin Dashboard
    • 📥 Data Ingestion
    • 📊 Monitoring
    • 👁️ Observability
    • 🔄 RAG Configuration Switching
  • 🗄️ S3 Integration for PDF uploads
  • 🐳 Easy Deployment with Docker / Docker Compose
![f937cd54-217f-4106-81b6-56636a17306f (1)](https://github.com/user-attachments/assets/2f2c75fa-a3f0-4311-9a43-554d8cb3e04e)
## Tech Stack - 🦙 LlamaIndex: For building and orchestrating RAG pipelines - 📦 MongoDB: Used as both a normal database and a vector database - ⚡ FastAPI: Backend API framework - ⚛️ Next.js: Frontend framework - 🔍 Qdrant: Vector database for efficient similarity search - 👁️ Arize Phoenix: Observability Platform to monitor/evaluate your RAG system ## 🌟 Why RAG-SaaS? Setting 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. ## 🚀 Getting Started 1. Clone the repository: ```bash git clone https://github.com/adithya-s-k/RAG-SaaS.git cd RAG-SaaS ``` ## 🐳 Docker Compose Deployment ### Environment Variables
🔑 How to Set up .env ### Environment Variables To 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: #### Frontend Environment (./frontend/.env.local) - `NEXT_PUBLIC_SERVER_URL`: (Compulsory) The endpoint URL of your FastAPI server. - `NEXT_PUBLIC_CHAT_API`: (Compulsory) Derived from NEXT_SERVER_URL, typically set to `${NEXT_PUBLIC_SERVER_URL}/api/chat`. #### Backend Environment (./backend/.env) 1. Model Configuration: - `MODEL_PROVIDER`: (Compulsory) The AI model provider (e.g., 'openai'). - `MODEL`: (Compulsory) The name of the LLM model to use. - `EMBEDDING_MODEL`: (Compulsory) The name of the embedding model. - `EMBEDDING_DIM`: (Compulsory) The dimensionality of the embedding model. 2. OpenAI Configuration: - `OPENAI_API_KEY`: (Compulsory) Your OpenAI API key. 3. Application Settings: - `CONVERSATION_STARTERS`: (Compulsory) A list of starter questions for users. - `SYSTEM_PROMPT`: (Compulsory) The system prompt for the AI model. - `SYSTEM_CITATION_PROMPT`: (Optional) Additional prompt for citation. - `APP_HOST`: (Compulsory) The host address for the backend (default: '0.0.0.0'). - `APP_PORT`: (Compulsory) The port for the backend (default: 8000). 4. Database Configuration: - `MONGODB_URI`: (Compulsory) The MongoDB connection URI. - `MONGODB_NAME`: (Compulsory) The MongoDB database name (default: 'RAGSAAS'). - `QDRANT_URL`: (Compulsory) The URL for the Qdrant server. - `QDRANT_COLLECTION`: (Compulsory) The Qdrant collection name. - `QDRANT_API_KEY`: (Optional) API key for Qdrant authentication. 5. Authentication: - `JWT_SECRET_KEY`: (Compulsory) Secret key for signing JWT tokens. - `JWT_REFRESH_SECRET_KEY`: (Compulsory) Secret key for signing JWT refresh tokens. - `ADMIN_EMAIL`: (Compulsory) Administrator email for application login. - `ADMIN_PASSWORD`: (Compulsory) Administrator password for application login. 6. AWS S3 Configuration (Optional): - `AWS_ACCESS_KEY_ID`: AWS Access Key ID. - `AWS_SECRET_ACCESS_KEY`: AWS Secret Access Key. - `AWS_REGION`: AWS Region for your services. - `BUCKET_NAME`: The name of the S3 bucket to use. 7. Observability: - `ARIZE_PHOENIX_ENDPOINT`: (Optional) Endpoint for Arize Phoenix observability. #### S3 Integration To enable S3 integration for PDF uploads/Ingestion: 1. Set the following environment variables in your `.env` file: ``` AWS_ACCESS_KEY_ID=your_access_key AWS_SECRET_ACCESS_KEY=your_secret_key AWS_REGION=bucket_region BUCKET_NAME=your_bucket_name ``` ### Docker Compose Env (./env) ``` backend: build: context: ./backend dockerfile: Dockerfile image: ragsaas/backend:latest container_name: backend ports: - '8000:8000' environment: # MongoDB Configuration MONGODB_NAME: RAGSAAS MONGODB_URI: mongodb://admin:password@mongodb:27017/ # Qdrant Configuration QDRANT_COLLECTION: default QDRANT_URL: http://qdrant:6333 # QDRANT_API_KEY: # OPENAI_API_KEY is compulsory OPENAI_API_KEY: # Backend Application Configuration MODEL_PROVIDER: openai MODEL: gpt-4o-mini EMBEDDING_MODEL: text-embedding-3-small EMBEDDING_DIM: 1536 FILESERVER_URL_PREFIX: http://backend:8000/api/files SYSTEM_PROMPT: 'You are a helpful assistant who helps users with their questions.' APP_HOST: 0.0.0.0 APP_PORT: 8000 JWT_SECRET_KEY: JWT_REFRESH_SECRET_KEY: ARIZE_PHOENIX_ENDPOINT: http://arizephoenix:4317 ```
For Docker Compose deployment, use: ```bash docker compose up -d ``` Pull down the containers ```bash docker compose down ``` ### Development Mode To run the project in development mode, follow these steps: 1. **Start the Next.js Frontend:** Navigate to the `frontend` directory and install the required dependencies. Then, run the development server: ```bash cd frontend npm install npm run dev ``` 2. **Set Up the Vector Database (Qdrant), Database (MongoDB), and Observability Platform (Arize Phoenix):** You can either self-host these services using Docker or use hosted solutions. **Self-Hosted Options:** - Qdrant: ```bash docker pull qdrant/qdrant ``` - MongoDB: ```bash docker pull mongo ``` - Arize Phoenix: ```bash docker pull arizephoenix/phoenix ``` **Hosted Options:** - Qdrant Cloud: [Qdrant Cloud](https://cloud.qdrant.io/) - MongoDB Atlas: [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) - Arize Phoenix: [Arize Phoenix](https://app.phoenix.arize.com/) 3. **Start the FastAPI Server:** Navigate to the `backend` directory and set up the Python environment. You can use either Conda or Python's built-in `venv`: ```bash cd backend ``` **Using Conda:** ```bash conda create -n ragsaas-venv python=3.11 conda activate ragsaas-venv ``` **Using Python's `venv`:** ```bash python -m venv ragsaas-venv \ragsaas-venv\Scripts\activate # On Windows source ragsaas-venv/bin/activate # On macOS/Linux ``` Install the required dependencies and run the server: ```bash pip install -e . python main.py ``` --- ## Roadmap - [x] add support to store ingested data in AWS S3 - [x] Add Docker compose for each set up - [x] Implement Observability - [ ] Improve authentication system - [ ] Integrate OmniParse API for efficient Data ingestion - [ ] Provide more control to Admin over RAG configuration - [ ] Implement Advanced and Agentic RAG ## 👥 Contributing We welcome contributions to RAG-SaaS! Please see our [CONTRIBUTING.md](CONTRIBUTING.md) for more details on how to get started. ## 📄 Licensing This project is available under a dual license: - Apache License 2.0 for students, developers, and individuals - GNU General Public License v3.0 for companies and commercial use See the [LICENSING.md](LICENSING.md) file for more details. ## 🙏 Acknowledgements This project is built on the following frameworks, technologies and tools: - [LlamaIndex](https://www.llamaindex.ai/) for the create-llama tool and RAG orchestration - [FastAPI](https://fastapi.tiangolo.com/) - [Next.js](https://nextjs.org/) - [MongoDB](https://www.mongodb.com/) - [Qdrant](https://qdrant.tech/) - [Arize Phoenix](https://docs.arize.com/phoenix) ## Contact & Support ### Bug Reports If 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. ### Commercial Use & Custom Solutions For inquiries regarding: - Commercial licensing - Custom modifications - Managed deployment - Specialized integrations Please contact: adithyaskolavi@gmail.com We're here to help tailor RAG-SaaS to your specific needs and ensure you get the most out of our solution. ## Star History

Star History Chart

================================================ FILE: backend/.gitignore ================================================ __pycache__ storage .env output ================================================ FILE: backend/Dockerfile ================================================ FROM python:3.11 as build WORKDIR /app ENV PYTHONPATH=/app # Install Poetry RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \ cd /usr/local/bin && \ ln -s /opt/poetry/bin/poetry && \ poetry config virtualenvs.create false # Install Chromium for web loader # Can disable this if you don't use the web loader to reduce the image size RUN apt update && apt install -y chromium chromium-driver # Install dependencies COPY ./pyproject.toml ./poetry.lock* /app/ RUN poetry install --no-root --no-cache --only main # ==================================== FROM build as release COPY . . CMD ["python", "main.py"] ================================================ FILE: backend/README.md ================================================ 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). ## Getting Started First, setup the environment with poetry: > **_Note:_** This step is not needed if you are using the dev-container. ``` poetry install poetry shell ``` Then 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). If you are using any tools or data sources, you can update their config files in the `config` folder. Second, generate the embeddings of the documents in the `./data` directory (if this folder exists - otherwise, skip this step): ``` poetry run generate ``` Third, run the development server: ``` python main.py ``` The example provides two different API endpoints: 1. `/api/chat` - a streaming chat endpoint 2. `/api/chat/request` - a non-streaming chat endpoint You can test the streaming endpoint with the following curl request: ``` curl --location 'localhost:8000/api/chat' \ --header 'Content-Type: application/json' \ --data '{ "messages": [{ "role": "user", "content": "Hello" }] }' ``` And for the non-streaming endpoint run: ``` curl --location 'localhost:8000/api/chat/request' \ --header 'Content-Type: application/json' \ --data '{ "messages": [{ "role": "user", "content": "Hello" }] }' ``` You 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. Open [http://localhost:8000/docs](http://localhost:8000/docs) with your browser to see the Swagger UI of the API. The API allows CORS for all origins to simplify development. You can change this behavior by setting the `ENVIRONMENT` environment variable to `prod`: ``` ENVIRONMENT=prod python main.py ``` ## Using Docker 1. Build an image for the FastAPI app: ``` docker build -t . ``` 2. Generate embeddings: Parse the data and generate the vector embeddings if the `./data` folder exists - otherwise, skip this step: ``` docker run \ --rm \ -v $(pwd)/.env:/app/.env \ # Use ENV variables and configuration from your file-system -v $(pwd)/config:/app/config \ -v $(pwd)/data:/app/data \ # Use your local folder to read the data -v $(pwd)/storage:/app/storage \ # Use your file system to store the vector database \ poetry run generate ``` 3. Start the API: ``` docker run \ -v $(pwd)/.env:/app/.env \ # Use ENV variables and configuration from your file-system -v $(pwd)/config:/app/config \ -v $(pwd)/storage:/app/storage \ # Use your file system to store gea vector database -p 8000:8000 \ ``` ## Learn More To learn more about LlamaIndex, take a look at the following resources: - [LlamaIndex Documentation](https://docs.llamaindex.ai) - learn about LlamaIndex. You can check out [the LlamaIndex GitHub repository](https://github.com/run-llama/llama_index) - your feedback and contributions are welcome! ================================================ FILE: backend/app/__init__.py ================================================ ================================================ FILE: backend/app/api/__init__.py ================================================ ================================================ FILE: backend/app/api/admin/__init__.py ================================================ from .route import admin_router __all__ = ["admin_router"] ================================================ FILE: backend/app/api/admin/route.py ================================================ import os from grpc import Status import boto3 import tempfile import shutil from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile, Depends, HTTPException, status from fastapi.responses import JSONResponse from typing import List, Dict, Any, Optional from pydantic import BaseModel, EmailStr, Field from app.core.user import get_current_user from app.models.user_model import User from app.services.admin_service import admin_service from app.schemas.admin_schema import UserOut, UsersOut, MessageOut, ErrorOut from app.services.config_service import config_service from llama_index.core.ingestion import IngestionPipeline from llama_index.core.node_parser import SentenceSplitter from llama_index.core.settings import Settings from app.api.chat.engine.vectordb import get_vector_store from llama_index.core import SimpleDirectoryReader from llama_index.core.schema import Document from phoenix.trace import using_project admin_router = APIRouter() load_dotenv() # AWS configuration AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_REGION = os.getenv("AWS_REGION") AWS_S3_BUCKET_NAME = os.getenv("AWS_S3_BUCKET_NAME") # Local storage configuration DATA_DIR = os.getenv("DATA_DIR", "data") PRIVATE_STORE_PATH = os.path.join(DATA_DIR) def get_documents( directory: str, recursive: bool = True, filename_as_id: bool = True ) -> List[Document]: """ Load documents from a specified directory using SimpleDirectoryReader. Args: directory (str): The path to the directory containing the documents. recursive (bool, optional): Whether to recursively search for documents in subdirectories. Defaults to True. filename_as_id (bool, optional): Whether to use the filename as the document ID. Defaults to True. Returns: List[Document]: A list of loaded documents. """ reader = SimpleDirectoryReader( directory, recursive=recursive, filename_as_id=filename_as_id ) documents = reader.load_data(show_progress=True) return documents class UserUpdate(BaseModel): first_name: Optional[str] = None last_name: Optional[str] = None email: Optional[EmailStr] = None role: Optional[str] = None disabled: Optional[bool] = None def verify_admin(current_user: User = Depends(get_current_user)): if current_user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to access this resource", ) return current_user @admin_router.get( "/users", response_model=UsersOut, responses={403: {"model": ErrorOut}} ) async def get_all_users(admin: User = Depends(verify_admin)) -> UsersOut: users = await admin_service.get_all_users() return UsersOut(users=[UserOut(**user) for user in users]) @admin_router.get( "/users/{user_id}", response_model=UserOut, responses={403: {"model": ErrorOut}, 404: {"model": ErrorOut}}, ) async def get_user(user_id: str, admin: User = Depends(verify_admin)) -> UserOut: user = await admin_service.get_user_by_id(user_id) if not user: raise HTTPException(status_code=404, detail="User not found") return UserOut(**user) @admin_router.put( "/users/{user_id}", response_model=MessageOut, responses={403: {"model": ErrorOut}, 404: {"model": ErrorOut}}, ) async def edit_user( user_id: str, user_update: UserUpdate, admin: User = Depends(verify_admin) ) -> MessageOut: success = await admin_service.edit_user( user_id, user_update.model_dump(exclude_unset=True) ) if not success: raise HTTPException(status_code=404, detail="User not found") return MessageOut(message="User updated successfully") @admin_router.delete( "/users/{user_id}", response_model=MessageOut, responses={ 403: {"model": ErrorOut}, 404: {"model": ErrorOut}, 400: {"model": ErrorOut}, }, ) async def delete_user(user_id: str, admin: User = Depends(verify_admin)) -> MessageOut: user = await admin_service.get_user_by_id(user_id) if not user: raise HTTPException(status_code=404, detail="User not found") if user["role"] == "admin": raise HTTPException(status_code=400, detail="Cannot delete an admin user") success = await admin_service.delete_user(user_id) if not success: raise HTTPException(status_code=500, detail="Failed to delete user") return MessageOut(message="User deleted successfully") @admin_router.get("/system-prompt") async def get_system_prompt(admin: User = Depends(verify_admin)): system_prompt = await config_service.get_system_prompt() return {"system_prompt": system_prompt} class SystemPromptUpdate(BaseModel): new_prompt: str @admin_router.put("/system-prompt") async def update_system_prompt( prompt_update: SystemPromptUpdate, admin: User = Depends(verify_admin) ): success = await config_service.update_system_prompt(prompt_update.new_prompt) if not success: raise HTTPException(status_code=500, detail="Failed to update system prompt") return {"message": "System prompt updated successfully"} class ConversationStartersUpdate(BaseModel): new_starters: List[str] = Field( ..., description="A list of new conversation starter questions", min_items=1, example=[ "What is RAG?", "How does chunking work?", "Explain vector embeddings", ], ) @admin_router.put( "/conversation-starters", response_model=MessageOut, responses={ 200: { "model": MessageOut, "description": "Conversation starters updated successfully", }, 500: { "model": ErrorOut, "description": "Failed to update conversation starters", }, }, summary="Update conversation starters", description="Update the list of conversation starter questions for the chat interface", ) async def update_conversation_starters( starters_update: ConversationStartersUpdate, admin: User = Depends(verify_admin) ): success = await config_service.update_conversation_starters( starters_update.new_starters ) if not success: raise HTTPException( status_code=500, detail="Failed to update conversation starters" ) return MessageOut(message="Conversation starters updated successfully") @admin_router.post("/upload_data") async def upload_and_ingest_data( file: UploadFile = File(...), admin: User = Depends(verify_admin) ): with using_project("RAGSAAS-Data-Ingest"): try: # Check if AWS credentials are available use_aws = all( [ AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_S3_BUCKET_NAME, ] ) with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(file.file, tmp_file) tmp_file_path = tmp_file.name if use_aws: # Initialize S3 client s3_client = boto3.client( "s3", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION, ) # Upload file to S3 folder_name = "admin_uploads/" file_key = f"{folder_name}{file.filename}" s3_client.upload_file(tmp_file_path, AWS_S3_BUCKET_NAME, file_key) # Generate the file URL file_url = f"https://{AWS_S3_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/{file_key}" else: # Store file locally os.makedirs(PRIVATE_STORE_PATH, exist_ok=True) local_file_path = os.path.join(PRIVATE_STORE_PATH, file.filename) shutil.move(tmp_file_path, local_file_path) file_url = f"/api/files/data/{file.filename}" # Ingest file into vector database with tempfile.TemporaryDirectory() as temp_dir: file_path = os.path.join(temp_dir, file.filename) shutil.copy( local_file_path if not use_aws else tmp_file_path, file_path ) documents = get_documents(temp_dir) # Set metadata for all documents for doc in documents: doc.metadata["private"] = "false" doc.metadata["file_id"] = file_key if use_aws else file.filename doc.metadata["user_id"] = "admin" doc.metadata["url"] = file_url doc.metadata["file_path"] = file_url doc.metadata["document_id"] = file_url doc.metadata["document_id"] = file_url vector_store = get_vector_store() pipeline = IngestionPipeline( transformations=[ SentenceSplitter( chunk_size=Settings.chunk_size, chunk_overlap=Settings.chunk_overlap, ), Settings.embed_model, ], vector_store=vector_store, ) nodes = pipeline.run(documents=documents, show_progress=True) return JSONResponse( status_code=200, content={ "file_url": file_url, "message": f"Ingestion complete. {len(nodes)} nodes inserted.", "storage": "S3" if use_aws else "Local", }, ) except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)}) ================================================ FILE: backend/app/api/auth/__init__.py ================================================ from .route import auth_router __all__ = ["auth_router"] ================================================ FILE: backend/app/api/auth/route.py ================================================ from fastapi import APIRouter, Depends, HTTPException, Response, status, Body from fastapi.security import OAuth2PasswordRequestForm from typing import Any from app.services import user_service from app.core.security import create_access_token, create_refresh_token from app.schemas.auth_schema import TokenSchema from app.schemas.user_schema import UserOut from app.models.user_model import User from app.core.user import get_current_user from app.core.config import settings from app.schemas.auth_schema import TokenPayload, AuthErrorOut, RefreshTokenRequest from app.schemas.user_schema import UserAuth, UserUpdate from pydantic import ValidationError from jose import JWTError, jwt import pymongo auth_router = APIRouter() @auth_router.post("/signup", summary="Create new user", response_model=dict) async def create_user(data: UserAuth): try: user = await user_service.create_user(data) return { "status": "success", "user": UserOut( # user_id=user.user_id, email=user.email, first_name=user.first_name, last_name=user.last_name, role=user.role, ), } except ValueError as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) except pymongo.errors.DuplicateKeyError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="User with this email already exists", ) @auth_router.post( "/login", summary="Create access and refresh tokens for user", response_model=TokenSchema, ) @auth_router.post( "/login", summary="Create access and refresh tokens for user", response_model=TokenSchema, ) async def login(form_data: OAuth2PasswordRequestForm = Depends()) -> Any: user = await user_service.authenticate( email=form_data.username, password=form_data.password ) if not user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect email or password", ) if user.disabled: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled", ) return { "access_token": create_access_token(user.user_id), "refresh_token": create_refresh_token(user.user_id), } # @auth_router.post("/refresh", summary="Refresh token", response_model=TokenSchema) # async def refresh_token(refresh_token: str = Body(...)): # try: # payload = jwt.decode( # refresh_token, # settings.JWT_REFRESH_SECRET_KEY, # algorithms=[settings.ALGORITHM], # ) # token_data = TokenPayload(**payload) # except (jwt.JWTError, ValidationError): # raise HTTPException( # status_code=status.HTTP_403_FORBIDDEN, # detail="Invalid token", # headers={"WWW-Authenticate": "Bearer"}, # ) # user = await user_service.get_user_by_id(token_data.sub) # if not user: # raise HTTPException( # status_code=status.HTTP_404_NOT_FOUND, # detail="Invalid token for user", # ) # return { # "access_token": create_access_token(user.user_id), # "refresh_token": create_refresh_token(user.user_id), # } @auth_router.post( "/refresh", response_model=TokenSchema, summary="Refresh token", responses={403: {"model": AuthErrorOut}, 404: {"model": AuthErrorOut}}, ) async def refresh_token(response: Response, refresh_request: RefreshTokenRequest): try: payload = jwt.decode( refresh_request.refresh_token, settings.JWT_REFRESH_SECRET_KEY, algorithms=[settings.ALGORITHM], ) token_data = TokenPayload(**payload) except (JWTError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid token", headers={"WWW-Authenticate": "Bearer"}, ) user = await user_service.get_user_by_id(token_data.sub) if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Invalid token for user", ) if user.disabled: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User account is disabled", ) new_access_token = create_access_token(user.user_id) new_refresh_token = create_refresh_token(user.user_id) # Set cookies response.set_cookie( key="accessToken", value=new_access_token, httponly=True, max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60, expires=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60, samesite="lax", secure=settings.COOKIE_SECURE, # True in production ) response.set_cookie( key="refreshToken", value=new_refresh_token, httponly=True, max_age=settings.REFRESH_TOKEN_EXPIRE_MINUTES * 60, expires=settings.REFRESH_TOKEN_EXPIRE_MINUTES * 60, samesite="lax", secure=settings.COOKIE_SECURE, # True in production ) return { "access_token": new_access_token, "refresh_token": new_refresh_token, } @auth_router.get( "/me", summary="Get details of currently logged in user", response_model=UserOut ) async def get_me(user: User = Depends(get_current_user)): return user @auth_router.get("/verify-admin", response_model=dict) async def verify_admin(current_user: User = Depends(get_current_user)): if not current_user.role or current_user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User is not an admin", ) return {"isAdmin": True} @auth_router.post("/update", summary="Update User", response_model=UserOut) async def update_user(data: UserUpdate, user: User = Depends(get_current_user)): try: return await user_service.update_user(user.user_id, data) except pymongo.errors.OperationFailure: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="User does not exist" ) @auth_router.post( "/test-token", summary="Test if the access token is valid", response_model=UserOut ) async def test_token(user: User = Depends(get_current_user)): return user ================================================ FILE: backend/app/api/chat/__init__.py ================================================ from .route import chat_router from .chat_config import config_router from .upload import file_upload_router __all__ = ["chat_router", "config_router", "file_upload_router"] ================================================ FILE: backend/app/api/chat/chat_config.py ================================================ import logging import os from fastapi import APIRouter from app.api.chat.models import ChatConfig from app.services.config_service import config_service config_router = r = APIRouter() logger = logging.getLogger("uvicorn") @r.get("") async def chat_config() -> ChatConfig: return await config_service.get_chat_config() ================================================ FILE: backend/app/api/chat/engine/__init__.py ================================================ from .engine import get_chat_engine as get_chat_engine ================================================ FILE: backend/app/api/chat/engine/engine.py ================================================ import os from app.api.chat.engine.index import get_index from app.api.chat.engine.node_postprocessors import NodeCitationProcessor from fastapi import HTTPException from llama_index.core.chat_engine import CondensePlusContextChatEngine from app.db import sync_mongodb from motor.motor_asyncio import AsyncIOMotorClient def get_system_prompt_from_db(): config_collection = sync_mongodb.db.config config = config_collection.find_one({"_id": "app_config"}) if config and "SYSTEM_PROMPT" in config: return config["SYSTEM_PROMPT"] return None def get_chat_engine(filters=None, params=None): system_prompt = get_system_prompt_from_db() if system_prompt is None: system_prompt = os.getenv("SYSTEM_PROMPT", "") citation_prompt = os.getenv("SYSTEM_CITATION_PROMPT", None) top_k = int(os.getenv("TOP_K", 0)) # node_postprocessors = [] # if citation_prompt: # node_postprocessors = [NodeCitationProcessor()] # system_prompt = f"{system_prompt}\n{citation_prompt}" index = get_index(params) if index is None: raise HTTPException( status_code=500, detail=str( "StorageContext is empty - call 'poetry run generate' to generate the storage first" ), ) retriever = index.as_retriever( filters=filters, **({"similarity_top_k": top_k} if top_k != 0 else {}) ) return CondensePlusContextChatEngine.from_defaults( system_prompt=system_prompt, retriever=retriever, # node_postprocessors=node_postprocessors, ) ================================================ FILE: backend/app/api/chat/engine/generate.py ================================================ # flake8: noqa: E402 from dotenv import load_dotenv load_dotenv() import logging import os from app.api.chat.engine.loaders import get_documents from app.api.chat.engine.vectordb import get_vector_store from app.settings import init_settings from llama_index.core.ingestion import IngestionPipeline from llama_index.core.node_parser import SentenceSplitter from llama_index.core.settings import Settings from llama_index.core.storage import StorageContext from llama_index.core.storage.docstore import SimpleDocumentStore logging.basicConfig(level=logging.INFO) logger = logging.getLogger() STORAGE_DIR = os.getenv("STORAGE_DIR", "storage") def get_doc_store(): # If the storage directory is there, load the document store from it. # If not, set up an in-memory document store since we can't load from a directory that doesn't exist. if os.path.exists(STORAGE_DIR): return SimpleDocumentStore.from_persist_dir(STORAGE_DIR) else: return SimpleDocumentStore() def run_pipeline(docstore, vector_store, documents): pipeline = IngestionPipeline( transformations=[ SentenceSplitter( chunk_size=Settings.chunk_size, chunk_overlap=Settings.chunk_overlap, ), Settings.embed_model, ], docstore=docstore, docstore_strategy="upserts_and_delete", vector_store=vector_store, ) # Run the ingestion pipeline and store the results nodes = pipeline.run(show_progress=True, documents=documents) return nodes def persist_storage(docstore, vector_store): storage_context = StorageContext.from_defaults( docstore=docstore, vector_store=vector_store, ) storage_context.persist(STORAGE_DIR) def generate_datasource(): init_settings() logger.info("Generate index for the provided data") # Get the stores and documents or create new ones documents = get_documents() # Set private=false to mark the document as public (required for filtering) for doc in documents: doc.metadata["private"] = "false" docstore = get_doc_store() vector_store = get_vector_store() # Run the ingestion pipeline _ = run_pipeline(docstore, vector_store, documents) # Build the index and persist storage persist_storage(docstore, vector_store) logger.info("Finished generating the index") if __name__ == "__main__": generate_datasource() ================================================ FILE: backend/app/api/chat/engine/index.py ================================================ import logging from llama_index.core.indices import VectorStoreIndex from app.api.chat.engine.vectordb import get_vector_store logger = logging.getLogger("uvicorn") def get_index(params=None): logger.info("Connecting vector store...") store = get_vector_store() # Load the index from the vector store # If you are using a vector store that doesn't store text, # you must load the index from both the vector store and the document store index = VectorStoreIndex.from_vector_store(store) logger.info("Finished load index from vector store.") return index ================================================ FILE: backend/app/api/chat/engine/loaders/__init__.py ================================================ import logging import yaml from app.api.chat.engine.loaders.db import DBLoaderConfig, get_db_documents from app.api.chat.engine.loaders.file import FileLoaderConfig, get_file_documents from app.api.chat.engine.loaders.web import WebLoaderConfig, get_web_documents logger = logging.getLogger(__name__) def load_configs(): with open("config/loaders.yaml") as f: configs = yaml.safe_load(f) return configs def get_documents(): documents = [] config = load_configs() for loader_type, loader_config in config.items(): logger.info( f"Loading documents from loader: {loader_type}, config: {loader_config}" ) match loader_type: case "file": document = get_file_documents(FileLoaderConfig(**loader_config)) case "web": document = get_web_documents(WebLoaderConfig(**loader_config)) case "db": document = get_db_documents( configs=[DBLoaderConfig(**cfg) for cfg in loader_config] ) case _: raise ValueError(f"Invalid loader type: {loader_type}") documents.extend(document) return documents ================================================ FILE: backend/app/api/chat/engine/loaders/db.py ================================================ import logging from typing import List from pydantic import BaseModel logger = logging.getLogger(__name__) class DBLoaderConfig(BaseModel): uri: str queries: List[str] def get_db_documents(configs: list[DBLoaderConfig]): from llama_index.readers.database import DatabaseReader docs = [] for entry in configs: loader = DatabaseReader(uri=entry.uri) for query in entry.queries: logger.info(f"Loading data from database with query: {query}") documents = loader.load_data(query=query) docs.extend(documents) return documents ================================================ FILE: backend/app/api/chat/engine/loaders/file.py ================================================ import os import logging from typing import Dict from llama_parse import LlamaParse from pydantic import BaseModel from app.config import DATA_DIR logger = logging.getLogger(__name__) class FileLoaderConfig(BaseModel): use_llama_parse: bool = False def llama_parse_parser(): if os.getenv("LLAMA_CLOUD_API_KEY") is None: raise ValueError( "LLAMA_CLOUD_API_KEY environment variable is not set. " "Please set it in .env file or in your shell environment then run again!" ) parser = LlamaParse( result_type="markdown", verbose=True, language="en", ignore_errors=False, ) return parser def llama_parse_extractor() -> Dict[str, LlamaParse]: from llama_parse.utils import SUPPORTED_FILE_TYPES parser = llama_parse_parser() return {file_type: parser for file_type in SUPPORTED_FILE_TYPES} def get_file_documents(config: FileLoaderConfig): from llama_index.core.readers import SimpleDirectoryReader try: file_extractor = None if config.use_llama_parse: # LlamaParse is async first, # so we need to use nest_asyncio to run it in sync mode import nest_asyncio nest_asyncio.apply() file_extractor = llama_parse_extractor() reader = SimpleDirectoryReader( DATA_DIR, recursive=True, filename_as_id=True, raise_on_error=True, file_extractor=file_extractor, ) return reader.load_data() except Exception as e: import sys import traceback # Catch the error if the data dir is empty # and return as empty document list _, _, exc_traceback = sys.exc_info() function_name = traceback.extract_tb(exc_traceback)[-1].name if function_name == "_add_files": logger.warning( f"Failed to load file documents, error message: {e} . Return as empty document list." ) return [] else: # Raise the error if it is not the case of empty data dir raise e ================================================ FILE: backend/app/api/chat/engine/loaders/web.py ================================================ from pydantic import BaseModel, Field class CrawlUrl(BaseModel): base_url: str prefix: str max_depth: int = Field(default=1, ge=0) class WebLoaderConfig(BaseModel): driver_arguments: list[str] = Field(default=None) urls: list[CrawlUrl] def get_web_documents(config: WebLoaderConfig): from llama_index.readers.web import WholeSiteReader from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() driver_arguments = config.driver_arguments or [] for arg in driver_arguments: options.add_argument(arg) docs = [] for url in config.urls: scraper = WholeSiteReader( prefix=url.prefix, max_depth=url.max_depth, driver=webdriver.Chrome(options=options), ) docs.extend(scraper.load_data(url.base_url)) return docs ================================================ FILE: backend/app/api/chat/engine/node_postprocessors.py ================================================ from typing import List, Optional from llama_index.core import QueryBundle from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.schema import NodeWithScore class NodeCitationProcessor(BaseNodePostprocessor): """ Append node_id into metadata for citation purpose. Config SYSTEM_CITATION_PROMPT in your runtime environment variable to enable this feature. """ def _postprocess_nodes( self, nodes: List[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> List[NodeWithScore]: for node_score in nodes: node_score.node.metadata["node_id"] = node_score.node.node_id return nodes ================================================ FILE: backend/app/api/chat/engine/query_filter.py ================================================ from llama_index.core.vector_stores.types import MetadataFilter, MetadataFilters def generate_filters(doc_ids): """ Generate public/private document filters based on the doc_ids and the vector store. """ public_doc_filter = MetadataFilter( key="private", value="true", operator="!=", # type: ignore ) selected_doc_filter = MetadataFilter( key="doc_id", value=doc_ids, operator="in", # type: ignore ) if len(doc_ids) > 0: # If doc_ids are provided, we will select both public and selected documents filters = MetadataFilters( filters=[ public_doc_filter, selected_doc_filter, ], condition="or", # type: ignore ) else: filters = MetadataFilters( filters=[ public_doc_filter, ] ) return filters ================================================ FILE: backend/app/api/chat/engine/vectordb.py ================================================ import os import qdrant_client from llama_index.vector_stores.qdrant import QdrantVectorStore def get_vector_store(): collection_name = os.getenv("QDRANT_COLLECTION", "ragsaas") QDRANT_URL = os.getenv("QDRANT_URL") QDRANT_API_KEY = os.getenv("QDRANT_API_KEY") if not collection_name or not QDRANT_URL: raise ValueError( "Please set QDRANT_COLLECTION, QDRANT_URL" " to your environment variables or config them in the .env file" ) if QDRANT_API_KEY: # creating a qdrant client instance client = qdrant_client.QdrantClient( url=QDRANT_URL, api_key=QDRANT_API_KEY, ) aclient = qdrant_client.AsyncQdrantClient( url=QDRANT_URL, api_key=QDRANT_API_KEY, ) store = QdrantVectorStore( client=client, aclient=aclient, collection_name=collection_name ) else: client = qdrant_client.QdrantClient( url=QDRANT_URL, ) aclient = qdrant_client.AsyncQdrantClient( url=QDRANT_URL, ) store = QdrantVectorStore( client=client, aclient=aclient, collection_name=collection_name ) return store ================================================ FILE: backend/app/api/chat/events.py ================================================ import json import asyncio import logging from typing import AsyncGenerator, Dict, Any, List, Optional from llama_index.core.callbacks.base import BaseCallbackHandler from llama_index.core.callbacks.schema import CBEventType from llama_index.core.tools.types import ToolOutput from pydantic import BaseModel logger = logging.getLogger(__name__) class CallbackEvent(BaseModel): event_type: CBEventType payload: Optional[Dict[str, Any]] = None event_id: str = "" def get_retrieval_message(self) -> dict | None: if self.payload: nodes = self.payload.get("nodes") if nodes: msg = f"Retrieved {len(nodes)} sources to use as context for the query" else: msg = f"Retrieving context for query: '{self.payload.get('query_str')}'" return { "type": "events", "data": {"title": msg}, } else: return None def get_tool_message(self) -> dict | None: func_call_args = self.payload.get("function_call") if func_call_args is not None and "tool" in self.payload: tool = self.payload.get("tool") return { "type": "events", "data": { "title": f"Calling tool: {tool.name} with inputs: {func_call_args}", }, } def _is_output_serializable(self, output: Any) -> bool: try: json.dumps(output) return True except TypeError: return False def get_agent_tool_response(self) -> dict | None: response = self.payload.get("response") if response is not None: sources = response.sources for source in sources: # Return the tool response here to include the toolCall information if isinstance(source, ToolOutput): if self._is_output_serializable(source.raw_output): output = source.raw_output else: output = source.content return { "type": "tools", "data": { "toolOutput": { "output": output, "isError": source.is_error, }, "toolCall": { "id": None, # There is no tool id in the ToolOutput "name": source.tool_name, "input": source.raw_input, }, }, } def to_response(self): try: match self.event_type: case "retrieve": return self.get_retrieval_message() case "function_call": return self.get_tool_message() case "agent_step": return self.get_agent_tool_response() case _: return None except Exception as e: logger.error(f"Error in converting event to response: {e}") return None class EventCallbackHandler(BaseCallbackHandler): _aqueue: asyncio.Queue is_done: bool = False def __init__( self, ): """Initialize the base callback handler.""" ignored_events = [ CBEventType.CHUNKING, CBEventType.NODE_PARSING, CBEventType.EMBEDDING, CBEventType.LLM, CBEventType.TEMPLATING, ] super().__init__(ignored_events, ignored_events) self._aqueue = asyncio.Queue() def on_event_start( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", **kwargs: Any, ) -> str: event = CallbackEvent(event_id=event_id, event_type=event_type, payload=payload) if event.to_response() is not None: self._aqueue.put_nowait(event) def on_event_end( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", **kwargs: Any, ) -> None: event = CallbackEvent(event_id=event_id, event_type=event_type, payload=payload) if event.to_response() is not None: self._aqueue.put_nowait(event) def start_trace(self, trace_id: Optional[str] = None) -> None: """No-op.""" def end_trace( self, trace_id: Optional[str] = None, trace_map: Optional[Dict[str, List[str]]] = None, ) -> None: """No-op.""" async def async_event_gen(self) -> AsyncGenerator[CallbackEvent, None]: while not self._aqueue.empty() or not self.is_done: try: yield await asyncio.wait_for(self._aqueue.get(), timeout=0.1) except asyncio.TimeoutError: pass ================================================ FILE: backend/app/api/chat/models.py ================================================ import logging import os from typing import Any, Dict, List, Literal, Optional from llama_index.core.llms import ChatMessage, MessageRole from llama_index.core.schema import NodeWithScore from pydantic import BaseModel, Field, validator from pydantic.alias_generators import to_camel from app.config import DATA_DIR logger = logging.getLogger("uvicorn") class FileContent(BaseModel): type: Literal["text", "ref"] # If the file is pure text then the value is be a string # otherwise, it's a list of document IDs value: str | List[str] class File(BaseModel): id: str content: FileContent filename: str filesize: int filetype: str class AnnotationFileData(BaseModel): files: List[File] = Field( default=[], description="List of files", ) class Config: json_schema_extra = { "example": { "csvFiles": [ { "content": "Name, Age\nAlice, 25\nBob, 30", "filename": "example.csv", "filesize": 123, "id": "123", "type": "text/csv", } ] } } alias_generator = to_camel class Annotation(BaseModel): type: str data: AnnotationFileData | List[str] def to_content(self) -> str | None: if self.type == "document_file": # We only support generating context content for CSV files for now csv_files = [file for file in self.data.files if file.filetype == "csv"] if len(csv_files) > 0: return "Use data from following CSV raw content\n" + "\n".join( [f"```csv\n{csv_file.content.value}\n```" for csv_file in csv_files] ) else: logger.warning( f"The annotation {self.type} is not supported for generating context content" ) return None class Message(BaseModel): role: MessageRole content: str annotations: List[Annotation] | None = None class ChatData(BaseModel): messages: List[Message] data: Any = None class Config: json_schema_extra = { "example": { "messages": [ { "role": "user", "content": "What standards for letters exist?", } ] } } @validator("messages") def messages_must_not_be_empty(cls, v): if len(v) == 0: raise ValueError("Messages must not be empty") return v def get_last_message_content(self) -> str: """ Get the content of the last message along with the data content if available. Fallback to use data content from previous messages """ if len(self.messages) == 0: raise ValueError("There is not any message in the chat") last_message = self.messages[-1] message_content = last_message.content for message in reversed(self.messages): if message.role == MessageRole.USER and message.annotations is not None: annotation_contents = filter( None, [annotation.to_content() for annotation in message.annotations], ) if not annotation_contents: continue annotation_text = "\n".join(annotation_contents) message_content = f"{message_content}\n{annotation_text}" break return message_content def get_history_messages(self) -> List[ChatMessage]: """ Get the history messages """ return [ ChatMessage(role=message.role, content=message.content) for message in self.messages[:-1] ] def is_last_message_from_user(self) -> bool: return self.messages[-1].role == MessageRole.USER def get_chat_document_ids(self) -> List[str]: """ Get the document IDs from the chat messages """ document_ids: List[str] = [] for message in self.messages: if message.role == MessageRole.USER and message.annotations is not None: for annotation in message.annotations: if ( annotation.type == "document_file" and annotation.data.files is not None ): for fi in annotation.data.files: if fi.content.type == "ref": document_ids += fi.content.value return list(set(document_ids)) class SourceNodes(BaseModel): id: str metadata: Dict[str, Any] score: Optional[float] text: str url: Optional[str] @classmethod def from_source_node(cls, source_node: NodeWithScore): metadata = source_node.node.metadata url = cls.get_url_from_metadata(metadata) return cls( id=source_node.node.node_id, metadata=metadata, score=source_node.score, text=source_node.node.text, # type: ignore url=url, ) @classmethod def get_url_from_metadata(cls, metadata: Dict[str, Any]) -> str: url_prefix = os.getenv("FILESERVER_URL_PREFIX") if not url_prefix: logger.warning( "Warning: FILESERVER_URL_PREFIX not set in environment variables. Can't use file server" ) file_name = metadata.get("file_name") if file_name and url_prefix: # file_name exists and file server is configured pipeline_id = metadata.get("pipeline_id") if pipeline_id: # file is from LlamaCloud file_name = f"{pipeline_id}${file_name}" return f"{url_prefix}/output/llamacloud/{file_name}" is_private = metadata.get("private", "false") == "true" if is_private: # file is a private upload return f"{url_prefix}/output/uploaded/{file_name}" # file is from calling the 'generate' script # Get the relative path of file_path to data_dir file_path = metadata.get("file_path") data_dir = os.path.abspath(DATA_DIR) if file_path and data_dir: relative_path = os.path.relpath(file_path, data_dir) return f"{url_prefix}/data/{relative_path}" # fallback to URL in metadata (e.g. for websites) return metadata.get("URL") @classmethod def from_source_nodes(cls, source_nodes: List[NodeWithScore]): return [cls.from_source_node(node) for node in source_nodes] class Result(BaseModel): result: Message nodes: List[SourceNodes] class ChatConfig(BaseModel): starter_questions: Optional[List[str]] = Field( default=None, description="List of starter questions", serialization_alias="starterQuestions", ) class Config: json_schema_extra = { "example": { "starterQuestions": [ "What standards for letters exist?", "What are the requirements for a letter to be considered a letter?", ], } } ================================================ FILE: backend/app/api/chat/route.py ================================================ import json import logging from typing import List, Dict, Any, Optional from fastapi import ( APIRouter, Depends, HTTPException, Request, status, Query, ) from llama_index.core.chat_engine.types import BaseChatEngine, NodeWithScore from llama_index.core.llms import MessageRole from app.api.chat.events import EventCallbackHandler from app.api.chat.models import ( ChatData, Message, Result, SourceNodes, ) from app.api.chat.vercel_response import VercelStreamResponse from app.api.chat.engine import get_chat_engine from app.api.chat.engine.query_filter import generate_filters from app.models.user_model import User from app.core.user import get_current_user from app.api.chat.summary import summary_generator from app.services import conversation_service from phoenix.trace import using_project chat_router = r = APIRouter() logger = logging.getLogger("uvicorn") # streaming endpoint - delete if not needed @r.post("") async def chat( request: Request, data: ChatData, conversation_id: Optional[str] = Query(None), current_user: User = Depends(get_current_user), ): with using_project("RAGSAAS-Chat"): if not conversation_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Conversation ID is required for authenticated requests.", ) try: USER_ID = current_user.email conversation = await conversation_service.get_or_create_conversation( conversation_id ) if conversation: stored_messages = conversation.get("messages", []) incoming_messages = data.messages if len(incoming_messages) < len(stored_messages): await conversation_service.truncate_conversation( conversation_id, len(incoming_messages), USER_ID ) if conversation.get("summary") == "New Chat": if len(data.messages) <= 2: summary = await summary_generator(data.messages) else: try: summary = conversation.get("summary") except Exception as e: summary = "New Chat" last_message_content = data.get_last_message_content() messages = data.get_history_messages() await conversation_service.update_conversation( conversation_id, {"role": MessageRole.USER, "content": last_message_content}, ) doc_ids = data.get_chat_document_ids() filters = generate_filters(doc_ids) params = data.data or {} logger.info( f"Creating chat engine with filters: {str(filters)}", ) chat_engine = get_chat_engine(filters=filters, params=params) event_handler = EventCallbackHandler() chat_engine.callback_manager.handlers.append(event_handler) # type: ignore response = await chat_engine.astream_chat(last_message_content, messages) # process_response_nodes(response.source_nodes, background_tasks) final_response = "" suggested_questions = [] source_nodes = [] event = [] tools = [] async def enhanced_content_generator(): nonlocal final_response, suggested_questions, source_nodes, event, tools async for chunk in VercelStreamResponse.content_generator( request, event_handler, response, data ): # print(chunk, end="", flush=True) # Print each chunk in the backend yield chunk if chunk.startswith(VercelStreamResponse.TEXT_PREFIX): final_response += json.loads(chunk[2:].strip()) elif chunk.startswith(VercelStreamResponse.DATA_PREFIX): data_chunk = json.loads(chunk[2:].strip())[0] if data_chunk["type"] == "suggested_questions": suggested_questions = data_chunk["data"] elif data_chunk["type"] == "sources": try: source_nodes = data_chunk[ "data" ] # might have chidlen key value pair except Exception: source_nodes = [] elif data_chunk["type"] == "events": try: event = data_chunk[ "data" ] # might have chidlen key value pair except Exception: event = [] # might have chidlen key value pair elif data_chunk["type"] == "tools": try: tools = data_chunk["data"] except Exception: tools = [] await conversation_service.update_conversation( conversation_id, { "role": MessageRole.ASSISTANT, "content": final_response, "annotations": [ {"type": "sources", "data": source_nodes}, { "type": "suggested_questions", "data": suggested_questions, }, {"type": "events", "data": event}, {"type": "tools", "data": tools}, ], }, summary=summary, user_id=USER_ID, ) return VercelStreamResponse( request, event_handler, response, data, content=enhanced_content_generator(), ) except Exception as e: logger.exception("Error in chat engine", exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error in chat engine: {e}", ) from e # non-streaming endpoint - delete if not needed # @r.post("/request") # async def chat_request( # data: ChatData, # chat_engine: BaseChatEngine = Depends(get_chat_engine), # ) -> Result: # last_message_content = data.get_last_message_content() # messages = data.get_history_messages() # response = await chat_engine.achat(last_message_content, messages) # return Result( # result=Message(role=MessageRole.ASSISTANT, content=response.response), # nodes=SourceNodes.from_source_nodes(response.source_nodes), # ) # def process_response_nodes( # nodes: List[NodeWithScore], # background_tasks: BackgroundTasks, # ): # try: # # Start background tasks to download documents from LlamaCloud if needed # from app.api.chat.engine.service import LLamaCloudFileService # LLamaCloudFileService.download_files_from_nodes(nodes, background_tasks) # except ImportError: # logger.debug("LlamaCloud is not configured. Skipping post processing of nodes") # pass ================================================ FILE: backend/app/api/chat/services/file.py ================================================ import base64 import mimetypes import os from io import BytesIO from pathlib import Path from typing import Any, List, Tuple from app.api.chat.engine.index import get_index from llama_index.core import VectorStoreIndex from llama_index.core.ingestion import IngestionPipeline from llama_index.core.readers.file.base import ( _try_loading_included_file_formats as get_file_loaders_map, ) from llama_index.core.schema import Document from llama_index.indices.managed.llama_cloud.base import LlamaCloudIndex from llama_index.readers.file import FlatReader def get_llamaparse_parser(): from app.api.chat.engine.loaders import load_configs from app.api.chat.engine.loaders.file import FileLoaderConfig, llama_parse_parser config = load_configs() file_loader_config = FileLoaderConfig(**config["file"]) if file_loader_config.use_llama_parse: return llama_parse_parser() else: return None def default_file_loaders_map(): default_loaders = get_file_loaders_map() default_loaders[".txt"] = FlatReader return default_loaders class PrivateFileService: PRIVATE_STORE_PATH = "output/uploaded" @staticmethod def preprocess_base64_file(base64_content: str) -> Tuple[bytes, str | None]: header, data = base64_content.split(",", 1) mime_type = header.split(";")[0].split(":", 1)[1] extension = mimetypes.guess_extension(mime_type) # File data as bytes return base64.b64decode(data), extension @staticmethod def store_and_parse_file(file_name, file_data, extension) -> List[Document]: # Store file to the private directory os.makedirs(PrivateFileService.PRIVATE_STORE_PATH, exist_ok=True) file_path = Path(os.path.join(PrivateFileService.PRIVATE_STORE_PATH, file_name)) # write file with open(file_path, "wb") as f: f.write(file_data) # Load file to documents # If LlamaParse is enabled, use it to parse the file # Otherwise, use the default file loaders reader = get_llamaparse_parser() if reader is None: reader_cls = default_file_loaders_map().get(extension) if reader_cls is None: raise ValueError(f"File extension {extension} is not supported") reader = reader_cls() documents = reader.load_data(file_path) # Add custom metadata for doc in documents: doc.metadata["file_name"] = file_name doc.metadata["private"] = "true" return documents @staticmethod def process_file(file_name: str, base64_content: str, params: Any) -> List[str]: file_data, extension = PrivateFileService.preprocess_base64_file(base64_content) # Add the nodes to the index and persist it current_index = get_index(params) # Insert the documents into the index if isinstance(current_index, LlamaCloudIndex): from app.api.chat.engine.service import LLamaCloudFileService project_id = current_index._get_project_id() pipeline_id = current_index._get_pipeline_id() # LlamaCloudIndex is a managed index so we can directly use the files upload_file = (file_name, BytesIO(file_data)) return [ LLamaCloudFileService.add_file_to_pipeline( project_id, pipeline_id, upload_file, custom_metadata={ # Set private=true to mark the document as private user docs (required for filtering) "private": "true", }, ) ] else: # First process documents into nodes documents = PrivateFileService.store_and_parse_file( file_name, file_data, extension ) pipeline = IngestionPipeline() nodes = pipeline.run(documents=documents) # Add the nodes to the index and persist it if current_index is None: current_index = VectorStoreIndex(nodes=nodes) else: current_index.insert_nodes(nodes=nodes) current_index.storage_context.persist( persist_dir=os.environ.get("STORAGE_DIR", "storage") ) # Return the document ids return [doc.doc_id for doc in documents] ================================================ FILE: backend/app/api/chat/services/suggestion.py ================================================ import logging from typing import List from app.api.chat.models import Message from llama_index.core.prompts import PromptTemplate from llama_index.core.settings import Settings from pydantic import BaseModel NEXT_QUESTIONS_SUGGESTION_PROMPT = PromptTemplate( "You're a helpful assistant! Your task is to suggest the next question that user might ask. " "\nHere is the conversation history" "\n---------------------\n{conversation}\n---------------------" "Given the conversation history, please give me {number_of_questions} questions that you might ask next!" ) N_QUESTION_TO_GENERATE = 3 logger = logging.getLogger("uvicorn") class NextQuestions(BaseModel): """A list of questions that user might ask next""" questions: List[str] class NextQuestionSuggestion: @staticmethod async def suggest_next_questions( messages: List[Message], number_of_questions: int = N_QUESTION_TO_GENERATE, ) -> List[str]: """ Suggest the next questions that user might ask based on the conversation history Return as empty list if there is an error """ try: # Reduce the cost by only using the last two messages last_user_message = None last_assistant_message = None for message in reversed(messages): if message.role == "user": last_user_message = f"User: {message.content}" elif message.role == "assistant": last_assistant_message = f"Assistant: {message.content}" if last_user_message and last_assistant_message: break conversation: str = f"{last_user_message}\n{last_assistant_message}" output: NextQuestions = await Settings.llm.astructured_predict( NextQuestions, prompt=NEXT_QUESTIONS_SUGGESTION_PROMPT, conversation=conversation, number_of_questions=number_of_questions, ) return output.questions except Exception as e: logger.error(f"Error when generating next question: {e}") return [] ================================================ FILE: backend/app/api/chat/summary.py ================================================ from typing import List from app.api.chat.models import Message from llama_index.core.settings import Settings async def summary_generator( messages: List[Message], ) -> str: # Reduce the cost by only using the last two messages last_user_message = None last_assistant_message = None for message in reversed(messages): if message.role == "user": last_user_message = f"User: {message.content}" elif message.role == "assistant": last_assistant_message = f"Assistant: {message.content}" if last_user_message and last_assistant_message: break conversation: str = f"{last_user_message}\n{last_assistant_message}" response = await Settings.llm.acomplete( prompt=f""" Here is the conversation history \n---------------------\n{messages}\n---------------------\n Given the a conversation between a user and an Medical AI assistant give me one line summary of the conversation so that is instantly recognizable make sure its really short don't mention user or assistant in the summary dont start with conversation , discussion , inquiry it should always start with a keyboard of the conversation the summary should be short less then 5 to 10 words, straight to the point and distinct """, formatted=False, ) # print(response) return str(response) ================================================ FILE: backend/app/api/chat/upload.py ================================================ import logging from typing import List, Any from fastapi import APIRouter, HTTPException from pydantic import BaseModel from app.api.chat.services.file import PrivateFileService file_upload_router = r = APIRouter() logger = logging.getLogger("uvicorn") class FileUploadRequest(BaseModel): base64: str filename: str params: Any = None # @r.post("") # def upload_file(request: FileUploadRequest) -> List[str]: # try: # logger.info("Processing file") # return PrivateFileService.process_file( # request.filename, request.base64, request.params # ) # except Exception as e: # logger.error(f"Error processing file: {e}", exc_info=True) # raise HTTPException(status_code=500, detail="Error processing file") ================================================ FILE: backend/app/api/chat/vercel_response.py ================================================ import json from aiostream import stream from fastapi import Request from fastapi.responses import StreamingResponse from llama_index.core.chat_engine.types import StreamingAgentChatResponse from app.api.chat.events import EventCallbackHandler from app.api.chat.models import ChatData, Message, SourceNodes from app.api.chat.services.suggestion import NextQuestionSuggestion class VercelStreamResponse(StreamingResponse): """ Class to convert the response from the chat engine to the streaming format expected by Vercel """ TEXT_PREFIX = "0:" DATA_PREFIX = "8:" @classmethod def convert_text(cls, token: str): # Escape newlines and double quotes to avoid breaking the stream token = json.dumps(token) return f"{cls.TEXT_PREFIX}{token}\n" @classmethod def convert_data(cls, data: dict): data_str = json.dumps(data) return f"{cls.DATA_PREFIX}[{data_str}]\n" def __init__( self, request: Request, event_handler: EventCallbackHandler, response: StreamingAgentChatResponse, chat_data: ChatData, content=None, ): if content is None: content = VercelStreamResponse.content_generator( request, event_handler, response, chat_data ) super().__init__(content=content) @classmethod async def content_generator( cls, request: Request, event_handler: EventCallbackHandler, response: StreamingAgentChatResponse, chat_data: ChatData, ): # Yield the text response async def _chat_response_generator(): final_response = "" async for token in response.async_response_gen(): final_response += token yield VercelStreamResponse.convert_text(token) # Generate questions that user might interested to conversation = chat_data.messages + [ Message(role="assistant", content=final_response) ] questions = await NextQuestionSuggestion.suggest_next_questions( conversation ) if len(questions) > 0: yield VercelStreamResponse.convert_data( { "type": "suggested_questions", "data": questions, } ) # the text_generator is the leading stream, once it's finished, also finish the event stream event_handler.is_done = True # Yield the source nodes yield cls.convert_data( { "type": "sources", "data": { "nodes": [ SourceNodes.from_source_node(node).model_dump() for node in response.source_nodes ] }, } ) # Yield the events from the event handler async def _event_generator(): async for event in event_handler.async_event_gen(): event_response = event.to_response() if event_response is not None: yield VercelStreamResponse.convert_data(event_response) combine = stream.merge(_chat_response_generator(), _event_generator()) is_stream_started = False async with combine.stream() as streamer: async for output in streamer: if not is_stream_started: is_stream_started = True # Stream a blank message to start the stream yield VercelStreamResponse.convert_text("") yield output if await request.is_disconnected(): break ================================================ FILE: backend/app/api/conversation/__init__.py ================================================ from .route import conversation_router __all__ = ["conversation_router"] ================================================ FILE: backend/app/api/conversation/route.py ================================================ import logging from pydantic import BaseModel from datetime import datetime, timedelta from typing import List, Dict, Any, Optional from bson import ObjectId from fastapi import APIRouter, HTTPException, status, Depends from fastapi.responses import JSONResponse from dotenv import load_dotenv from app.core.user import get_current_user from app.services import conversation_service from app.models.user_model import User conversation_router = APIRouter(tags=["Conversation"]) logger = logging.getLogger("uvicorn") load_dotenv() @conversation_router.get("/") async def get_new_conversation( current_user: User = Depends(get_current_user), ): try: new_conversation_id = ObjectId() # user_email = current_user.get("email") if current_user else None user_email = current_user.email await conversation_service.get_or_create_conversation( str(new_conversation_id), user_email ) return {"conversation_id": str(new_conversation_id)} except Exception as e: logger.exception("Error creating new conversation", exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error creating new conversation: {e}", ) from e @conversation_router.get("/list") async def get_conversation_history( current_user: Dict[str, Any] = Depends(get_current_user), ): try: conversations_by_date = ( await conversation_service.get_all_conversations_for_user( current_user.email ) ) return {"conversations": conversations_by_date} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @conversation_router.get("/{conversation_id}") async def get_conversation( conversation_id: str, current_user: Dict[str, Any] = Depends(get_current_user) ): conversation = await conversation_service.get_or_create_conversation( conversation_id, current_user.email ) conversation["_id"] = str(conversation["_id"]) return {"messages": conversation.get("messages", [])} @conversation_router.get("/sharable/{conversation_id}") async def get_sharable_conversation(conversation_id: str): conversation = await conversation_service.get_sharable_conversation( conversation_id, ) if conversation is None: raise HTTPException(status_code=404, detail="Sharable conversation not found") return {"messages": conversation.get("messages", [])} @conversation_router.delete("/{conversation_id}") async def delete_conversation( conversation_id: str, current_user: Dict[str, Any] = Depends(get_current_user) ): try: deleted_count = await conversation_service.delete_conversation( conversation_id, current_user.email ) if deleted_count == 1: return JSONResponse( status_code=status.HTTP_200_OK, content={ "message": f"Conversation {conversation_id} deleted successfully." }, ) else: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Conversation {conversation_id} not found for the current user.", ) except Exception as e: logger.exception("Error deleting conversation", exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error deleting conversation: {e}", ) from e class ConversationSummaryUpdate(BaseModel): summary: str @conversation_router.patch("/{conversation_id}/share") async def edit_conversation_sharable( conversation_id: str, current_user: User = Depends(get_current_user), ): try: success = await conversation_service.make_conversation_sharable( conversation_id, current_user.email ) if success: return JSONResponse( status_code=status.HTTP_200_OK, content={ "message": f"Conversation {conversation_id} is now shareable." }, ) else: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Conversation {conversation_id} not found for the current user.", ) except HTTPException as he: raise he except Exception as e: logger.exception("Error updating conversation shareable status", exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error updating conversation shareable status: {str(e)}", ) from e @conversation_router.patch("/{conversation_id}/summary") async def edit_conversation_summary( conversation_id: str, summary_update: ConversationSummaryUpdate, current_user: User = Depends(get_current_user), ): try: matched_count = await conversation_service.edit_conversation_summary( conversation_id, current_user.email, summary_update.summary ) if matched_count == 1: return JSONResponse( status_code=status.HTTP_200_OK, content={ "message": f"Summary for conversation {conversation_id} updated successfully." }, ) else: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Conversation {conversation_id} not found for the current user.", ) except Exception as e: logger.exception("Error updating conversation summary", exc_info=True) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error updating conversation summary: {e}", ) from e ================================================ FILE: backend/app/config.py ================================================ DATA_DIR = "data" ================================================ FILE: backend/app/core/config.py ================================================ from typing import List, ClassVar from decouple import config from pydantic import AnyHttpUrl from pydantic_settings import BaseSettings class Settings(BaseSettings): API_V1_STR: str = "/api" JWT_SECRET_KEY: str = config("JWT_SECRET_KEY", cast=str) JWT_REFRESH_SECRET_KEY: str = config("JWT_REFRESH_SECRET_KEY", cast=str) ALGORITHM: ClassVar[str] = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 REFRESH_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7 # 7 days BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = ["http://localhost:3000"] PROJECT_NAME: str = "RAGSAAS" COOKIE_SECURE: bool = False # Database MONGO_CONNECTION_STRING: str = config("MONGODB_URI", cast=str) class Config: case_sensitive = True settings = Settings() ================================================ FILE: backend/app/core/security.py ================================================ from datetime import datetime, timedelta from passlib.context import CryptContext from typing import Union, Any from app.core.config import settings from jose import jwt password_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def create_access_token(subject: Union[str, Any], expires_delta: int = None) -> str: if expires_delta is not None: expires_delta = datetime.utcnow() + expires_delta else: expires_delta = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = {"exp": expires_delta, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET_KEY, settings.ALGORITHM) return encoded_jwt def create_refresh_token(subject: Union[str, Any], expires_delta: int = None) -> str: if expires_delta is not None: expires_delta = datetime.utcnow() + expires_delta else: expires_delta = datetime.utcnow() + timedelta(minutes=settings.REFRESH_TOKEN_EXPIRE_MINUTES) to_encode = {"exp": expires_delta, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, settings.JWT_REFRESH_SECRET_KEY, settings.ALGORITHM) return encoded_jwt def get_password(password: str) -> str: return password_context.hash(password) def verify_password(password: str, hashed_pass: str) -> bool: return password_context.verify(password, hashed_pass) ================================================ FILE: backend/app/core/user.py ================================================ from datetime import datetime from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from app.core.config import settings from app.models.user_model import User from jose import jwt from pydantic import ValidationError from app.services.user_service import user_service from app.schemas.auth_schema import TokenPayload reuseable_oauth = OAuth2PasswordBearer( tokenUrl=f"{settings.API_V1_STR}/auth/login", scheme_name="JWT" ) async def get_current_user(token: str = Depends(reuseable_oauth)) -> User: try: payload = jwt.decode( token, settings.JWT_SECRET_KEY, algorithms=[settings.ALGORITHM] ) token_data = TokenPayload(**payload) if datetime.fromtimestamp(token_data.exp) < datetime.now(): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired", headers={"WWW-Authenticate": "Bearer"}, ) except (jwt.JWTError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) user = await user_service.get_user_by_id(token_data.sub) if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Could not find user", ) return user ================================================ FILE: backend/app/db.py ================================================ import asyncio import re import os import json import time from motor.motor_asyncio import AsyncIOMotorClient from pymongo import MongoClient from dotenv import load_dotenv from pymongo.errors import ServerSelectionTimeoutError from app.models.user_model import User from app.core.security import get_password load_dotenv() MONGODB_URI = os.getenv("MONGODB_URI") MONGODB_NAME = os.getenv("MONGODB_NAME", "RAGSAAS") ADMIN_EMAIL = os.getenv("ADMIN_EMAIL") ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD") ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin") CONFIG_FILE = "rag_config.json" MAX_RETRIES = 5 RETRY_DELAY = 5 class AsyncMongoDB: client: AsyncIOMotorClient = None db = None async def connect_to_database(self): for attempt in range(MAX_RETRIES): try: print( f"Attempting to connect to MongoDB (Async) - Attempt {attempt + 1}" ) self.client = AsyncIOMotorClient(MONGODB_URI) await ( self.client.server_info() ) # This will raise an exception if it can't connect self.db = self.client[MONGODB_NAME] print("Connected to MongoDB (Async)") return except ServerSelectionTimeoutError as e: print(f"Connection attempt {attempt + 1} failed: {str(e)}") if attempt < MAX_RETRIES - 1: print(f"Retrying in {RETRY_DELAY} seconds...") await asyncio.sleep(RETRY_DELAY) else: print("Max retries reached. Unable to connect to MongoDB.") raise async def close_database_connection(self): if self.client: self.client.close() print("Closed MongoDB connection (Async)") async def database_init(self): users_collection = self.db.users config_collection = self.db.config # Create admin user if not exists existing_user = await users_collection.find_one({"email": ADMIN_EMAIL}) if not existing_user: admin_user = User( first_name=ADMIN_USERNAME, last_name=ADMIN_USERNAME, email=ADMIN_EMAIL, hashed_password=get_password(ADMIN_PASSWORD), role="admin", ) await users_collection.insert_one(admin_user.to_mongo()) print(f"Admin user created with email: {ADMIN_EMAIL}") # Check if config already exists existing_config = await config_collection.find_one({"_id": "app_config"}) if existing_config: print("Configuration already exists. Skipping initialization.") return # Initialize system prompt and conversation starters system_prompt = os.getenv("SYSTEM_PROMPT", "") conversation_starters_raw = os.getenv("CONVERSATION_STARTERS", "") conversation_starters = re.split(r"[,\n]+", conversation_starters_raw) conversation_starters = [ starter.strip() for starter in conversation_starters if starter.strip() ] initial_config = { "SYSTEM_PROMPT": system_prompt, "CONVERSATION_STARTERS": conversation_starters, } await config_collection.insert_one({"_id": "app_config", **initial_config}) with open(CONFIG_FILE, "w") as f: json.dump(initial_config, f, indent=2) print("System prompt and conversation starters initialized") print(f"Conversation starters: {conversation_starters}") class SyncMongoDB: client: MongoClient = None db = None def connect_to_database(self): for attempt in range(MAX_RETRIES): try: print( f"Attempting to connect to MongoDB (Sync) - Attempt {attempt + 1}" ) self.client = MongoClient(MONGODB_URI) self.client.server_info() # This will raise an exception if it can't connect self.db = self.client[MONGODB_NAME] print("Connected to MongoDB (Sync)") return except ServerSelectionTimeoutError as e: print(f"Connection attempt {attempt + 1} failed: {str(e)}") if attempt < MAX_RETRIES - 1: print(f"Retrying in {RETRY_DELAY} seconds...") time.sleep(RETRY_DELAY) else: print("Max retries reached. Unable to connect to MongoDB.") raise def close_database_connection(self): if self.client: self.client.close() print("Closed MongoDB connection (Sync)") def database_init(self): users_collection = self.db.users config_collection = self.db.config # Create admin user if not exists existing_user = users_collection.find_one({"email": ADMIN_EMAIL}) if not existing_user: admin_user = User( first_name=ADMIN_USERNAME, last_name=ADMIN_USERNAME, email=ADMIN_EMAIL, hashed_password=get_password(ADMIN_PASSWORD), role="admin", ) users_collection.insert_one(admin_user.to_mongo()) print(f"Admin user created with email: {ADMIN_EMAIL}") # Check if config already exists existing_config = config_collection.find_one({"_id": "app_config"}) if existing_config: print("Configuration already exists. Skipping initialization.") return # Initialize system prompt and conversation starters system_prompt = os.getenv("SYSTEM_PROMPT", "") conversation_starters_raw = os.getenv("CONVERSATION_STARTERS", "") conversation_starters = re.split(r"[,\n]+", conversation_starters_raw) conversation_starters = [ starter.strip() for starter in conversation_starters if starter.strip() ] initial_config = { "SYSTEM_PROMPT": system_prompt, "CONVERSATION_STARTERS": conversation_starters, } config_collection.insert_one({"_id": "app_config", **initial_config}) with open(CONFIG_FILE, "w") as f: json.dump(initial_config, f, indent=2) print("System prompt and conversation starters initialized") print(f"Conversation starters: {conversation_starters}") async_mongodb = AsyncMongoDB() sync_mongodb = SyncMongoDB() ================================================ FILE: backend/app/llmhub.py ================================================ from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.settings import Settings from typing import Dict import os DEFAULT_MODEL = "gpt-3.5-turbo" DEFAULT_EMBEDDING_MODEL = "text-embedding-3-large" class TSIEmbedding(OpenAIEmbedding): def __init__(self, **kwargs): super().__init__(**kwargs) self._query_engine = self._text_engine = self.model_name def llm_config_from_env() -> Dict: from llama_index.core.constants import DEFAULT_TEMPERATURE model = os.getenv("MODEL", DEFAULT_MODEL) temperature = os.getenv("LLM_TEMPERATURE", DEFAULT_TEMPERATURE) max_tokens = os.getenv("LLM_MAX_TOKENS") api_key = os.getenv("T_SYSTEMS_LLMHUB_API_KEY") api_base = os.getenv("T_SYSTEMS_LLMHUB_BASE_URL") config = { "model": model, "api_key": api_key, "api_base": api_base, "temperature": float(temperature), "max_tokens": int(max_tokens) if max_tokens is not None else None, } return config def embedding_config_from_env() -> Dict: from llama_index.core.constants import DEFAULT_EMBEDDING_DIM model = os.getenv("EMBEDDING_MODEL", DEFAULT_EMBEDDING_MODEL) dimension = os.getenv("EMBEDDING_DIM", DEFAULT_EMBEDDING_DIM) api_key = os.getenv("T_SYSTEMS_LLMHUB_API_KEY") api_base = os.getenv("T_SYSTEMS_LLMHUB_BASE_URL") config = { "model_name": model, "dimension": int(dimension) if dimension is not None else None, "api_key": api_key, "api_base": api_base, } return config def init_llmhub(): from llama_index.llms.openai_like import OpenAILike llm_configs = llm_config_from_env() embedding_configs = embedding_config_from_env() Settings.embed_model = TSIEmbedding(**embedding_configs) Settings.llm = OpenAILike( **llm_configs, is_chat_model=True, is_function_calling_model=False, context_window=4096, ) ================================================ FILE: backend/app/models/user_model.py ================================================ from typing import Optional from datetime import datetime from uuid import UUID, uuid4 from pydantic import BaseModel, Field, EmailStr from bson import Binary class User(BaseModel): user_id: UUID = Field(default_factory=uuid4) email: EmailStr hashed_password: str first_name: Optional[str] = None last_name: Optional[str] = None disabled: Optional[bool] = None role: str = "user" created_at: datetime = Field(default_factory=datetime.utcnow) def __repr__(self) -> str: return f"" def __str__(self) -> str: return self.email def __hash__(self) -> int: return hash(self.email) def __eq__(self, other: object) -> bool: if isinstance(other, User): return self.email == other.email return False @property def create(self) -> datetime: return self.created_at class Config: allow_population_by_field_name = True arbitrary_types_allowed = True json_encoders = {UUID: str} def to_mongo(self): # Convert the model to a dictionary data = self.model_dump() # Convert UUID to Binary for MongoDB storage data["user_id"] = Binary.from_uuid(data["user_id"]) return data @classmethod def from_mongo(cls, data): # Convert Binary back to UUID if data.get("user_id"): data["user_id"] = data["user_id"].as_uuid() return cls(**data) ================================================ FILE: backend/app/observability.py ================================================ import os from openinference.instrumentation.llama_index import LlamaIndexInstrumentor from opentelemetry import trace as trace_api from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk import trace as trace_sdk from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace.export import SimpleSpanProcessor from dotenv import load_dotenv load_dotenv() def init_observability(): ARIZE_PHOENIX_ENDPOINT = os.getenv("ARIZE_PHOENIX_ENDPOINT") if ARIZE_PHOENIX_ENDPOINT: try: if ARIZE_PHOENIX_ENDPOINT and "/v1/traces" in ARIZE_PHOENIX_ENDPOINT: PHOENIX_ENDPOINT_TRACE_ENDPOINT = ARIZE_PHOENIX_ENDPOINT else: PHOENIX_ENDPOINT_TRACE_ENDPOINT = f"{ARIZE_PHOENIX_ENDPOINT}/v1/traces" resource = Resource(attributes={}) tracer_provider = trace_sdk.TracerProvider(resource=resource) span_exporter = OTLPSpanExporter(endpoint=PHOENIX_ENDPOINT_TRACE_ENDPOINT) span_processor = SimpleSpanProcessor(span_exporter=span_exporter) tracer_provider.add_span_processor(span_processor=span_processor) trace_api.set_tracer_provider(tracer_provider=tracer_provider) LlamaIndexInstrumentor().instrument() print("🔭 ARIZE PHOENIX - Set up complete") except Exception as e: print("Wasnt able to set up Arize Phoenix", e) else: print("Arize Phoenix API Endpoint Not provided") ================================================ FILE: backend/app/schemas/admin_schema.py ================================================ from pydantic import BaseModel, EmailStr from typing import List, Optional, Any from datetime import datetime from uuid import UUID class UserOut(BaseModel): user_id: UUID email: EmailStr first_name: Optional[str] = None last_name: Optional[str] = None role: str disabled: Optional[bool] = None created_at: datetime class UsersOut(BaseModel): users: List[UserOut] class MessageOut(BaseModel): message: str class ErrorOut(BaseModel): detail: str status_code: int class AuthErrorOut(ErrorOut): error_description: Optional[str] = None error_code: Optional[str] = None ================================================ FILE: backend/app/schemas/auth_schema.py ================================================ from uuid import UUID from pydantic import BaseModel from typing_extensions import Optional class TokenSchema(BaseModel): access_token: str refresh_token: str class TokenPayload(BaseModel): sub: UUID = None exp: int = None class ErrorOut(BaseModel): detail: str status_code: int class AuthErrorOut(ErrorOut): error_description: Optional[str] = None error_code: Optional[str] = None class RefreshTokenRequest(BaseModel): refresh_token: str ================================================ FILE: backend/app/schemas/user_schema.py ================================================ from typing import Optional from pydantic import BaseModel, EmailStr, Field class UserAuth(BaseModel): email: EmailStr = Field(..., description="user email") first_name: str = Field(..., description="first name") last_name: str = Field(..., description="last name") password: str = Field(..., min_length=5, max_length=24, description="user password") class UserOut(BaseModel): # user_id: UUID email: EmailStr first_name: Optional[str] last_name: Optional[str] role: Optional[str] class UserUpdate(BaseModel): first_name: Optional[str] = None last_name: Optional[str] = None ================================================ FILE: backend/app/services/__init__.py ================================================ from .user_service import user_service from .conversation_service import conversation_service from .admin_service import admin_service from .config_service import config_service __all__ = ["user_service", "conversation_service", "admin_service", "config_service"] ================================================ FILE: backend/app/services/admin_service.py ================================================ from typing import List, Dict, Any, Optional from bson import ObjectId, Binary from datetime import datetime from app.db import async_mongodb from app.models.user_model import User from uuid import UUID class AdminService: @property def user_collection(self): return async_mongodb.db.users async def get_all_users(self) -> List[Dict[str, Any]]: users = await self.user_collection.find().to_list(length=None) return [self._serialize_user(User.from_mongo(user)) for user in users] async def get_user_by_id(self, user_id: str) -> Optional[Dict[str, Any]]: user = await self.user_collection.find_one( {"user_id": Binary.from_uuid(UUID(user_id))} ) return self._serialize_user(User.from_mongo(user)) if user else None async def edit_user(self, user_id: str, updated_data: Dict[str, Any]) -> bool: result = await self.user_collection.update_one( {"user_id": Binary.from_uuid(UUID(user_id))}, {"$set": updated_data} ) return result.modified_count > 0 async def delete_user(self, user_id: str) -> bool: result = await self.user_collection.delete_one( {"user_id": Binary.from_uuid(UUID(user_id))} ) return result.deleted_count > 0 def _serialize_user(self, user: User) -> Dict[str, Any]: return { "user_id": str(user.user_id), "email": user.email, "first_name": user.first_name, "last_name": user.last_name, "role": user.role, "disabled": user.disabled, "created_at": user.created_at.isoformat() if user.created_at else None, } admin_service = AdminService() ================================================ FILE: backend/app/services/config_service.py ================================================ from typing import List, Dict, Any, Optional from app.db import async_mongodb from app.api.chat.models import ChatConfig class ConfigService: @property def config_collection(self): return async_mongodb.db.config async def get_chat_config(self) -> ChatConfig: config = await self.config_collection.find_one({"_id": "app_config"}) if config: return ChatConfig( system_prompt=config.get("SYSTEM_PROMPT", ""), starter_questions=config.get("CONVERSATION_STARTERS", []), ) return ChatConfig(system_prompt="", starter_questions=[]) async def update_chat_config(self, updated_data: Dict[str, Any]) -> bool: result = await self.config_collection.update_one( {"_id": "app_config"}, {"$set": updated_data}, upsert=True ) return result.modified_count > 0 or result.upserted_id is not None async def get_system_prompt(self) -> str: config = await self.config_collection.find_one({"_id": "app_config"}) return config.get("SYSTEM_PROMPT", "") if config else "" async def update_system_prompt(self, new_prompt: str) -> bool: return await self.update_chat_config({"SYSTEM_PROMPT": new_prompt}) async def update_conversation_starters(self, new_starters: List[str]) -> bool: return await self.update_chat_config({"CONVERSATION_STARTERS": new_starters}) config_service = ConfigService() ================================================ FILE: backend/app/services/conversation_service.py ================================================ import logging from pydantic import BaseModel from datetime import datetime, timedelta from typing import List, Dict, Any, Optional from bson import ObjectId from dotenv import load_dotenv from app.db import async_mongodb logger = logging.getLogger("uvicorn") load_dotenv() class ConversationService: @property def conversation_collection(self): return async_mongodb.db.conversation async def get_or_create_conversation( self, conversation_id: str, user_id: Optional[str] = None ) -> Dict[str, Any]: conversation = await self.conversation_collection.find_one( {"_id": ObjectId(conversation_id)} ) if not conversation: conversation = { "_id": ObjectId(conversation_id), "messages": [], "created_at": datetime.utcnow(), "updated_at": datetime.utcnow(), "summary": "New Chat", } if user_id: conversation["user_id"] = user_id await self.conversation_collection.insert_one(conversation) return conversation async def update_conversation( self, conversation_id: str, new_message: Dict[str, Any], summary: Optional[str] = None, user_id: Optional[str] = None, ) -> None: update_fields = { "$push": {"messages": new_message}, "$set": {"updated_at": datetime.utcnow()}, } if summary: update_fields["$set"] = update_fields.get("$set", {}) update_fields["$set"]["summary"] = summary if user_id: update_fields["$set"] = update_fields.get("$set", {}) update_fields["$set"]["user_id"] = user_id await self.conversation_collection.update_one( {"_id": ObjectId(conversation_id)}, update_fields ) async def truncate_conversation( self, conversation_id: str, index: int, user_id: str ) -> None: conversation = await self.get_or_create_conversation(conversation_id) if conversation and conversation.get("user_id") == user_id: stored_messages = conversation.get("messages", []) truncated_messages = stored_messages[: index - 1] await self.conversation_collection.update_one( {"_id": ObjectId(conversation_id)}, { "$set": { "messages": truncated_messages, "updated_at": datetime.utcnow(), } }, ) else: raise PermissionError("User ID does not match or conversation not found.") async def get_all_conversations_for_user(self, user_id: str): projection = {"summary": 1, "created_at": 1, "updated_at": 1} conversations_cursor = self.conversation_collection.find( {"user_id": user_id}, projection ).sort("updated_at", -1) conversations = await conversations_cursor.to_list(length=None) now = datetime.utcnow() today = now.replace(hour=0, minute=0, second=0, microsecond=0) yesterday = today - timedelta(days=1) last_week = today - timedelta(days=7) categorized_conversations = { "today": [], "yesterday": [], "last_7_days": [], "before_that": [], } for conversation in conversations: conversation["_id"] = str(conversation["_id"]) updated_at = conversation["updated_at"] if updated_at >= today: categorized_conversations["today"].append(conversation) elif updated_at >= yesterday: categorized_conversations["yesterday"].append(conversation) elif updated_at >= last_week: categorized_conversations["last_7_days"].append(conversation) else: categorized_conversations["before_that"].append(conversation) for category in categorized_conversations: categorized_conversations[category].sort( key=lambda x: x["updated_at"], reverse=True ) return categorized_conversations async def delete_conversation(self, conversation_id: str, user_id: str) -> int: result = await self.conversation_collection.delete_one( {"_id": ObjectId(conversation_id), "user_id": user_id} ) return result.deleted_count async def edit_conversation_summary( self, conversation_id: str, user_id: str, new_summary: str ) -> int: result = await self.conversation_collection.update_one( {"_id": ObjectId(conversation_id), "user_id": user_id}, { "$set": { "summary": new_summary, "updated_at": datetime.utcnow(), } }, ) return result.matched_count async def get_sharable_conversation( self, conversation_id: str, ) -> Dict[str, Any]: conversation = await self.conversation_collection.find_one( {"_id": ObjectId(conversation_id), "sharable": True} ) if conversation is None: return None conversation["_id"] = str(conversation["_id"]) return conversation async def make_conversation_sharable( self, conversation_id: str, user_id: str ) -> bool: conversation = await self.conversation_collection.find_one( {"_id": ObjectId(conversation_id), "user_id": user_id} ) if not conversation: return False if conversation.get("sharable", False): # Changed True to False here return True result = await self.conversation_collection.update_one( {"_id": ObjectId(conversation_id), "user_id": user_id}, { "$set": { "sharable": True, "updated_at": datetime.utcnow(), } }, ) return result.modified_count == 1 conversation_service = ConversationService() ================================================ FILE: backend/app/services/user_service.py ================================================ from typing import Optional from uuid import UUID from app.schemas.user_schema import UserAuth, UserUpdate from app.models.user_model import User from app.core.security import get_password, verify_password from pymongo.errors import DuplicateKeyError from bson import Binary from dotenv import load_dotenv from app.db import async_mongodb # Load environment variables load_dotenv() class UserService: @property def users_collection(self): return async_mongodb.db.users async def create_user(self, user: UserAuth) -> User: user_obj = User( email=user.email, first_name=user.first_name, last_name=user.last_name, hashed_password=get_password(user.password), role="user", # Set default role to "user" ) user_dict = user_obj.to_mongo() try: result = await self.users_collection.insert_one(user_dict) user_dict["_id"] = result.inserted_id return User.from_mongo(user_dict) except DuplicateKeyError: raise ValueError("Username or email already exists") async def authenticate(self, email: str, password: str) -> Optional[User]: user = await self.get_user_by_email(email=email) if not user: return None if not verify_password(password=password, hashed_pass=user.hashed_password): return None return user async def get_user_by_email(self, email: str) -> Optional[User]: user_dict = await self.users_collection.find_one({"email": email}) return User.from_mongo(user_dict) if user_dict else None async def get_user_by_id(self, id: UUID) -> Optional[User]: user_dict = await self.users_collection.find_one( {"user_id": Binary.from_uuid(id)} ) return User.from_mongo(user_dict) if user_dict else None async def update_user(self, id: UUID, data: UserUpdate) -> User: update_data = data.model_dump(exclude_unset=True) result = await self.users_collection.update_one( {"user_id": Binary.from_uuid(id)}, {"$set": update_data} ) if result.modified_count == 0: raise ValueError("User not found") updated_user = await self.get_user_by_id(id) return updated_user user_service = UserService() ================================================ FILE: backend/app/settings.py ================================================ import os from typing import Dict from llama_index.core.settings import Settings def init_settings(): model_provider = os.getenv("MODEL_PROVIDER") match model_provider: case "openai": init_openai() case "groq": init_groq() case "ollama": init_ollama() case "anthropic": init_anthropic() case "gemini": init_gemini() case "mistral": init_mistral() case "azure-openai": init_azure_openai() case "t-systems": from .llmhub import init_llmhub init_llmhub() case _: raise ValueError(f"Invalid model provider: {model_provider}") Settings.chunk_size = int(os.getenv("CHUNK_SIZE", "1024")) Settings.chunk_overlap = int(os.getenv("CHUNK_OVERLAP", "20")) def init_ollama(): from llama_index.embeddings.ollama import OllamaEmbedding from llama_index.llms.ollama.base import DEFAULT_REQUEST_TIMEOUT, Ollama base_url = os.getenv("OLLAMA_BASE_URL") or "http://127.0.0.1:11434" request_timeout = float( os.getenv("OLLAMA_REQUEST_TIMEOUT", DEFAULT_REQUEST_TIMEOUT) ) Settings.embed_model = OllamaEmbedding( base_url=base_url, model_name=os.getenv("EMBEDDING_MODEL"), ) Settings.llm = Ollama( base_url=base_url, model=os.getenv("MODEL"), request_timeout=request_timeout ) def init_openai(): from llama_index.core.constants import DEFAULT_TEMPERATURE from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI max_tokens = os.getenv("LLM_MAX_TOKENS") config = { "model": os.getenv("MODEL"), "temperature": float(os.getenv("LLM_TEMPERATURE", DEFAULT_TEMPERATURE)), "max_tokens": int(max_tokens) if max_tokens is not None else None, } Settings.llm = OpenAI(**config) dimensions = os.getenv("EMBEDDING_DIM") config = { "model": os.getenv("EMBEDDING_MODEL"), "dimensions": int(dimensions) if dimensions is not None else None, } Settings.embed_model = OpenAIEmbedding(**config) def init_azure_openai(): from llama_index.core.constants import DEFAULT_TEMPERATURE from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding from llama_index.llms.azure_openai import AzureOpenAI llm_deployment = os.environ["AZURE_OPENAI_LLM_DEPLOYMENT"] embedding_deployment = os.environ["AZURE_OPENAI_EMBEDDING_DEPLOYMENT"] max_tokens = os.getenv("LLM_MAX_TOKENS") temperature = os.getenv("LLM_TEMPERATURE", DEFAULT_TEMPERATURE) dimensions = os.getenv("EMBEDDING_DIM") azure_config = { "api_key": os.environ["AZURE_OPENAI_API_KEY"], "azure_endpoint": os.environ["AZURE_OPENAI_ENDPOINT"], "api_version": os.getenv("AZURE_OPENAI_API_VERSION") or os.getenv("OPENAI_API_VERSION"), } Settings.llm = AzureOpenAI( model=os.getenv("MODEL"), max_tokens=int(max_tokens) if max_tokens is not None else None, temperature=float(temperature), deployment_name=llm_deployment, **azure_config, ) Settings.embed_model = AzureOpenAIEmbedding( model=os.getenv("EMBEDDING_MODEL"), dimensions=int(dimensions) if dimensions is not None else None, deployment_name=embedding_deployment, **azure_config, ) def init_fastembed(): """ Use Qdrant Fastembed as the local embedding provider. """ from llama_index.embeddings.fastembed import FastEmbedEmbedding embed_model_map: Dict[str, str] = { # Small and multilingual "all-MiniLM-L6-v2": "sentence-transformers/all-MiniLM-L6-v2", # Large and multilingual "paraphrase-multilingual-mpnet-base-v2": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", # noqa: E501 } # This will download the model automatically if it is not already downloaded Settings.embed_model = FastEmbedEmbedding( model_name=embed_model_map[os.getenv("EMBEDDING_MODEL")] ) def init_groq(): from llama_index.llms.groq import Groq model_map: Dict[str, str] = { "llama3-8b": "llama3-8b-8192", "llama3-70b": "llama3-70b-8192", "mixtral-8x7b": "mixtral-8x7b-32768", } Settings.llm = Groq(model=model_map[os.getenv("MODEL")]) # Groq does not provide embeddings, so we use FastEmbed instead init_fastembed() def init_anthropic(): from llama_index.llms.anthropic import Anthropic model_map: Dict[str, str] = { "claude-3-opus": "claude-3-opus-20240229", "claude-3-sonnet": "claude-3-sonnet-20240229", "claude-3-haiku": "claude-3-haiku-20240307", "claude-2.1": "claude-2.1", "claude-instant-1.2": "claude-instant-1.2", } Settings.llm = Anthropic(model=model_map[os.getenv("MODEL")]) # Anthropic does not provide embeddings, so we use FastEmbed instead init_fastembed() def init_gemini(): from llama_index.embeddings.gemini import GeminiEmbedding from llama_index.llms.gemini import Gemini model_name = f"models/{os.getenv('MODEL')}" embed_model_name = f"models/{os.getenv('EMBEDDING_MODEL')}" Settings.llm = Gemini(model=model_name) Settings.embed_model = GeminiEmbedding(model_name=embed_model_name) def init_mistral(): from llama_index.embeddings.mistralai import MistralAIEmbedding from llama_index.llms.mistralai import MistralAI Settings.llm = MistralAI(model=os.getenv("MODEL")) Settings.embed_model = MistralAIEmbedding(model_name=os.getenv("EMBEDDING_MODEL")) ================================================ FILE: backend/config/loaders.yaml ================================================ file: # use_llama_parse: Use LlamaParse if `true`. Needs a `LLAMA_CLOUD_API_KEY` from https://cloud.llamaindex.ai set as environment variable use_llama_parse: false ================================================ FILE: backend/config/tools.yaml ================================================ local: {} llamahub: {} ================================================ FILE: backend/main.py ================================================ # flake8: noqa: E402 from dotenv import load_dotenv from app.config import DATA_DIR load_dotenv() import logging import os import json import uvicorn from app.api.chat import chat_router from app.api.chat import config_router from app.api.chat import file_upload_router from app.api.auth import auth_router from app.api.conversation import conversation_router from app.api.admin import admin_router from app.observability import init_observability from app.settings import init_settings from app.db import async_mongodb, sync_mongodb from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse from fastapi.staticfiles import StaticFiles from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): await async_mongodb.connect_to_database() sync_mongodb.connect_to_database() await async_mongodb.database_init() yield # Shutdown: Close the database connection sync_mongodb.close_database_connection() await async_mongodb.close_database_connection() app = FastAPI(lifespan=lifespan) init_settings() init_observability() environment = os.getenv("ENVIRONMENT", "dev") # Default to 'development' if not set logger = logging.getLogger("uvicorn") # if environment == "dev": # logger.warning("Running in development mode - allowing CORS for all origins") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Redirect to documentation page when accessing base URL @app.get("/") async def redirect_to_docs(): return RedirectResponse(url="/docs") def mount_static_files(directory, path): if os.path.exists(directory): logger.info(f"Mounting static files '{directory}' at '{path}'") app.mount( path, StaticFiles(directory=directory, check_dir=False), name=f"{directory}-static", ) # Mount the data files to serve the file viewer mount_static_files(DATA_DIR, "/api/files/data") # Mount the output files from tools mount_static_files("output", "/api/files/output") app.include_router(auth_router, prefix="/api/auth", tags=["Authentication"]) app.include_router(chat_router, prefix="/api/chat", tags=["Chat"]) app.include_router(config_router, prefix="/api/chat/config", tags=["Chat"]) app.include_router(file_upload_router, prefix="/api/chat/upload", tags=["Chat"]) app.include_router( conversation_router, prefix="/api/conversation", tags=["Conversation"] ) app.include_router(admin_router, prefix="/api/admin", tags=["Admin"]) if __name__ == "__main__": app_host = os.getenv("APP_HOST", "0.0.0.0") app_port = int(os.getenv("APP_PORT", "8000")) reload = True if environment == "dev" else False uvicorn.run(app="main:app", host=app_host, port=app_port, reload=reload) ================================================ FILE: backend/pyproject.toml ================================================ [tool] [tool.poetry] name = "app" version = "0.1.0" description = "⚡ Ship RAG Solutions Quickly" authors = [ "Adithya S K " ] readme = "README.md" [tool.poetry.scripts] generate = "app.api.chat.engine.generate:generate_datasource" [tool.poetry.dependencies] python = ">=3.11,<3.12" fastapi = {extras = ["all"], version = "^0.112.2"} python-dotenv = "^1.0.0" aiostream = "^0.5.2" llama-index = "0.10.58" cachetools = "^5.3.3" pymongo = "^4.8.0" motor = "^3.5.1" python-jose = "^3.3.0" passlib = {extras = ["bcrypt"], version = "^1.7.4"} python-multipart = "^0.0.9" pydantic = {extras = ["email"], version = "^2.8.2"} pydantic-settings = "^2.4.0" fastapi-mail = "^1.4.1" beanie = "^1.26.0" python-decouple = "^3.8" boto3 = "^1.35.6" openinference-instrumentation = "^0.1.12" openinference-instrumentation-llama-index = "^2.2.1" openinference-instrumentation-openai = "^0.1.12" openinference-semantic-conventions = "^0.1.9" opentelemetry-api = "^1.26.0" opentelemetry-exporter-otlp = "^1.26.0" arize-phoenix = {extras = ["evals"], version = "^4.19.0"} [tool.poetry.dependencies.uvicorn] extras = [ "standard" ] version = "^0.23.2" [tool.poetry.dependencies.llama-index-vector-stores-qdrant] version = "^0.2.8" [tool.poetry.dependencies.docx2txt] version = "^0.8" [tool.poetry.dependencies.llama-index-agent-openai] version = "0.2.6" [build-system] requires = [ "poetry-core" ] build-backend = "poetry.core.masonry.api" ================================================ FILE: backend/tests/__init__.py ================================================ ================================================ FILE: docker-compose.yaml ================================================ version: '3.8' services: qdrant: image: qdrant/qdrant:latest container_name: qdrant ports: - 6333:6333 - 6334:6334 networks: - ragsaas-network mongodb: image: mongo:latest container_name: mongodb ports: - 27017:27017 environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: password networks: - ragsaas-network volumes: - mongodb_data:/data/db arizephoenix: image: arizephoenix/phoenix:latest container_name: arizephoenix ports: - '6006:6006' - '4317:4317' networks: - ragsaas-network backend: build: context: ./backend dockerfile: Dockerfile image: ragsaas/backend:latest container_name: backend ports: - '8000:8000' environment: # MongoDB Configuration MONGODB_NAME: RAGSAAS MONGODB_URI: mongodb://admin:password@mongodb:27017/ # Qdrant Configuration QDRANT_COLLECTION: default QDRANT_URL: http://qdrant:6333 # QDRANT_API_KEY: OPENAI_API_KEY: # Backend Application Configuration MODEL_PROVIDER: openai MODEL: gpt-4o-mini EMBEDDING_MODEL: text-embedding-3-small EMBEDDING_DIM: 1536 FILESERVER_URL_PREFIX: http://backend:8000/api/files SYSTEM_PROMPT: 'You are a helpful assistant who helps users with their questions.' APP_HOST: 0.0.0.0 APP_PORT: 8000 ADMIN_EMAIL: admin@ragsaas.com ADMIN_PASSWORD: ragsaas JWT_SECRET_KEY: JWT_REFRESH_SECRET_KEY: ARIZE_PHOENIX_ENDPOINT: http://arizephoenix:6006 depends_on: - qdrant - mongodb - arizephoenix networks: - ragsaas-network frontend: build: context: ./frontend dockerfile: Dockerfile image: ragsaas/frontend:latest container_name: frontend ports: - '3000:3000' environment: NEXT_PUBLIC_SERVER_URL: http://backend:8000 NEXT_PUBLIC_CHAT_API: http://backend:8000/api/chat depends_on: - backend networks: - ragsaas-network networks: ragsaas-network: name: ragsaas-network driver: bridge volumes: mongodb_data: ================================================ FILE: frontend/.eslintrc.json ================================================ { "extends": "next/core-web-vitals" } ================================================ FILE: frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js .yarn/install-state.gz # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # local env files .env*.local # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: frontend/Dockerfile ================================================ FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json ./ RUN npm update && npm install # If you want yarn update and install uncomment the bellow # RUN yarn install && yarn upgrade FROM base AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . RUN npm run build FROM base AS runner WORKDIR /app ENV NODE_ENV production RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nextjs COPY --from=builder /app/public ./public RUN mkdir .next RUN chown nextjs:nodejs .next COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 3000 ENV PORT 3000 CMD ["node", "server.js"] ================================================ FILE: frontend/README.md ================================================ 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). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The 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. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. ================================================ FILE: frontend/app/(auth)/signin/page.tsx ================================================ 'use client'; import Image from 'next/image'; import Link from 'next/link'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import BannerCard from '@/components/banner-card'; import { ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react'; import { useState, FormEvent, Suspense } from 'react'; import { useRouter } from 'next/navigation'; import { useAuth } from '@/app/authProvider'; import axios, { AxiosError } from 'axios'; import { toast } from 'sonner'; import Loading from '@/components/loading'; interface LoginResponse { access_token: string; refresh_token: string; } interface UserResponse { id: string; email: string; first_name: string; last_name: string; role: string; } function SignInContent() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [error, setError] = useState(''); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const { login } = useAuth(); const togglePasswordVisibility = () => { setShowPassword(!showPassword); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setError(''); setIsLoading(true); const formData = new FormData(); formData.append('username', email); formData.append('password', password); try { const response = await axios.post( `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/login`, formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, } ); const { access_token, refresh_token } = response.data; // Get user details const userResponse = await axios.get( `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/me`, { headers: { Authorization: `Bearer ${access_token}` }, } ); const { email: userEmail, first_name, last_name, role, } = userResponse.data; login(access_token, refresh_token, userEmail, first_name, last_name); toast.success('Sign In successful'); router.push('/chat'); } catch (error) { if (axios.isAxiosError(error)) { const axiosError = error as AxiosError<{ detail: string }>; setError( axiosError.response?.data?.detail || 'An error occurred during sign in' ); } else { setError('An unexpected error occurred'); } toast.error('Sign In failed. Please try again.'); } finally { setIsLoading(false); } }; return (

Login

Enter your email below to login to your account

setEmail(e.target.value)} />
setPassword(e.target.value)} />
{error &&

{error}

}
Don't have an account?{' '} Sign up
); } export default function SignUp() { return ( }> ); } ================================================ FILE: frontend/app/(auth)/signup/page.tsx ================================================ 'use client'; import React, { Suspense, lazy, useState } from 'react'; import Image from 'next/image'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { useAuth } from '@/app/authProvider'; import axios from 'axios'; import { ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; // import BannerCard from '@/components/banner-card'; import { Alert, AlertDescription } from '@/components/ui/alert'; import Loading from '@/components/loading'; const BannerCard = lazy(() => import('@/components/banner-card')); function SignUpContent() { const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '', password: '', confirmPassword: '', }); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); const [error, setError] = useState(''); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const { login } = useAuth(); const togglePasswordVisibility = (field: 'password' | 'confirmPassword') => { if (field === 'password') { setShowPassword(!showPassword); } else { setShowConfirmPassword(!showConfirmPassword); } }; const handleChange = (e: React.ChangeEvent) => { const { name, value } = e.target; setFormData((prevData) => ({ ...prevData, [name]: value })); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); setIsLoading(true); if (formData.password !== formData.confirmPassword) { setError("Passwords don't match"); setIsLoading(false); return; } try { const response = await axios.post( `${process.env.NEXT_PUBLIC_SERVER_URL}/api/auth/signup`, { first_name: formData.firstName, last_name: formData.lastName, email: formData.email, password: formData.password, } ); if (response.data.status === 'success') { toast('User Sign Up successful'); router.push('/signin'); } } catch (error: any) { toast(error.response?.data?.detail || 'An error occurred during sign up'); setError( error.response?.data?.detail || 'An error occurred during sign up' ); } finally { setIsLoading(false); } }; return (

Sign Up

Create an account to get started

{error && ( {error} )}
Already have an account?{' '} Log in
); } export default function SignUp() { return ( }> ); } ================================================ FILE: frontend/app/ConversationContext.tsx ================================================ 'use client'; import React, { createContext, useContext, useState, useEffect } from 'react'; interface Conversation { _id: string; summary: string; created_at?: string; updated_at?: string; } interface ConversationsByDate { today: Conversation[]; yesterday: Conversation[]; last_7_days: Conversation[]; before_that: Conversation[]; } interface ConversationContextProps { conversationList: ConversationsByDate; setConversationList: React.Dispatch< React.SetStateAction >; isSidebarOpen: boolean; setIsSidebarOpen: React.Dispatch>; } const ConversationContext = createContext( undefined ); export const useConversationContext = () => { const context = useContext(ConversationContext); if (context === undefined) { throw new Error( 'useConversationContext must be used within a ConversationProvider' ); } return context; }; interface ConversationProviderProps { children: React.ReactNode; } export const ConversationProvider: React.FC = ({ children, }) => { const [conversationList, setConversationList] = useState( { today: [], yesterday: [], last_7_days: [], before_that: [], } ); const [isSidebarOpen, setIsSidebarOpen] = useState(false); return ( {children} ); }; ================================================ FILE: frontend/app/admin/AdminAuthProvider.tsx ================================================ 'use client'; import React, { createContext, useState, useContext, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import axios from 'axios'; import Cookies from 'js-cookie'; interface AdminAuthContextType { isAdminAuthenticated: boolean; adminData: { email: string; firstName: string; lastName: string; role: string; } | null; } const AdminAuthContext = createContext( undefined ); export function AdminAuthProvider({ children }: { children: React.ReactNode }) { const [isAdminAuthenticated, setIsAdminAuthenticated] = useState(false); const [adminData, setAdminData] = useState(null); const router = useRouter(); const axiosInstance = axios.create({ baseURL: process.env.NEXT_PUBLIC_SERVER_URL, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${Cookies.get('accessToken')}`, }, }); useEffect(() => { const verifyAdminStatus = async () => { const accessToken = Cookies.get('accessToken'); if (!accessToken) { setIsAdminAuthenticated(false); router.push('/'); return; } try { const response = await axiosInstance.get('/api/auth/verify-admin'); if (response.data.isAdmin) { setIsAdminAuthenticated(true); fetchAdminData(); } else { setIsAdminAuthenticated(false); router.push('/'); } } catch (error) { console.error('Error verifying admin status:', error); setIsAdminAuthenticated(false); router.push('/'); } }; verifyAdminStatus(); }, [router]); const fetchAdminData = async () => { try { const response = await axiosInstance.get('/api/auth/me'); setAdminData(response.data); } catch (error) { console.error('Failed to fetch admin data:', error); } }; return ( {children} ); } export const useAdminAuth = () => { const context = useContext(AdminAuthContext); if (context === undefined) { throw new Error('useAdminAuth must be used within an AdminAuthProvider'); } return context; }; ================================================ FILE: frontend/app/admin/DataIngestion.tsx ================================================ 'use client'; import React, { useState } from 'react'; import { useAuth } from '@/app/authProvider'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Input } from '@/components/ui/input'; import { LoaderIcon, Upload } from 'lucide-react'; import { FileUpload } from '@/components/ui/file-upload'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; export default function DataIngestion() { const { axiosInstance } = useAuth(); const [file, setFile] = useState(null); const [isUploading, setIsUploading] = useState(false); const [uploadResult, setUploadResult] = useState(null); const handleFileUpload = (files: File[]) => { if (files.length > 0) { setFile(files[0]); } }; const uploadFile = async () => { if (!file) return; setIsUploading(true); setUploadResult(null); const formData = new FormData(); formData.append('file', file); try { const response = await axiosInstance.post( '/api/admin/upload_data', formData, { headers: { 'Content-Type': 'multipart/form-data', }, } ); setUploadResult(`File uploaded successfully. ${response.data.message}`); } catch (error) { console.error('Error uploading file:', error); setUploadResult('Error uploading file. Please try again.'); } finally { setIsUploading(false); setFile(null); } }; return ( Data Ingestion Manage data ingestion processes.
{file && (
)} {uploadResult && (
{uploadResult}
)}
); } ================================================ FILE: frontend/app/admin/RAGConfiguration.tsx ================================================ 'use client'; import React, { useEffect, useState } from 'react'; import { useAuth } from '@/app/authProvider'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { Separator } from '@/components/ui/separator'; import { PlusCircle, Trash2 } from 'lucide-react'; export default function RAGConfiguration() { const { axiosInstance } = useAuth(); const [systemPrompt, setSystemPrompt] = useState(''); const [suggestedQuestions, setSuggestedQuestions] = useState([]); const [configLoading, setConfigLoading] = useState(true); const [configError, setConfigError] = useState(null); const [systemPromptLoading, setSystemPromptLoading] = useState(false); const [startersLoading, setStartersLoading] = useState(false); const [initialSystemPrompt, setInitialSystemPrompt] = useState(''); const [initialSuggestedQuestions, setInitialSuggestedQuestions] = useState< string[] >([]); useEffect(() => { fetchConfig(); }, [axiosInstance]); const fetchConfig = async () => { setConfigLoading(true); setConfigError(null); try { const [configResponse, systemPromptResponse] = await Promise.all([ axiosInstance.get('/api/chat/config'), axiosInstance.get('/api/admin/system-prompt'), ]); const config = configResponse.data; const systemPromptData = systemPromptResponse.data; setSystemPrompt(systemPromptData.system_prompt || ''); setInitialSystemPrompt(systemPromptData.system_prompt || ''); setSuggestedQuestions(config.starterQuestions || []); setInitialSuggestedQuestions(config.starterQuestions || []); setConfigLoading(false); } catch (err: any) { setConfigError(err.message || 'Failed to fetch configuration'); setConfigLoading(false); } }; const updateSystemPrompt = async () => { setSystemPromptLoading(true); try { const response = await axiosInstance.put('/api/admin/system-prompt', { new_prompt: systemPrompt, }); if (response.status === 200) { console.log('System prompt updated successfully'); setInitialSystemPrompt(systemPrompt); } } catch (error) { console.error('Failed to update system prompt:', error); } finally { setSystemPromptLoading(false); } }; const updateConversationStarters = async () => { setStartersLoading(true); try { const newStarters = suggestedQuestions.filter((q) => q.trim() !== ''); const response = await axiosInstance.put( '/api/admin/conversation-starters', { new_starters: newStarters } ); if (response.status === 200) { console.log('Conversation starters updated successfully'); setInitialSuggestedQuestions(newStarters); } } catch (error) { console.error('Failed to update conversation starters:', error); } finally { setStartersLoading(false); } }; const addSuggestedQuestion = () => { setSuggestedQuestions([...suggestedQuestions, '']); }; const updateSuggestedQuestion = (index: number, value: string) => { const updatedQuestions = [...suggestedQuestions]; updatedQuestions[index] = value; setSuggestedQuestions(updatedQuestions); }; const deleteSuggestedQuestion = (index: number) => { const updatedQuestions = suggestedQuestions.filter((_, i) => i !== index); setSuggestedQuestions(updatedQuestions); }; const isSystemPromptChanged = systemPrompt !== initialSystemPrompt; const areSuggestedQuestionsChanged = JSON.stringify(suggestedQuestions) !== JSON.stringify(initialSuggestedQuestions); if (configLoading) return
Loading configuration...
; if (configError) return
Error: {configError}
; return ( RAG Configuration Configure Retrieval-Augmented Generation settings.