├── .github
├── ISSUE_TEMPLATE
│ ├── bug-report.md
│ └── feature-request.md
├── PULL_REQUEST_TEMPLATE
│ └── pull_request_template.md
└── workflows
│ └── codeql.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── mindsql
├── __init__.py
├── _helper
│ ├── __init__.py
│ └── helper.py
├── _utils
│ ├── __init__.py
│ ├── constants.py
│ ├── logger.py
│ └── prompts.py
├── core
│ ├── __init__.py
│ └── mindsql_core.py
├── databases
│ ├── __init__.py
│ ├── idatabase.py
│ ├── mysql.py
│ ├── postgres.py
│ ├── sqlite.py
│ └── sqlserver.py
├── llms
│ ├── __init__.py
│ ├── anthropic.py
│ ├── googlegenai.py
│ ├── huggingface.py
│ ├── illm.py
│ ├── llama.py
│ ├── ollama.py
│ └── open_ai.py
└── vectorstores
│ ├── __init__.py
│ ├── chromadb.py
│ ├── faiss_db.py
│ └── ivectorstore.py
├── pyproject.toml
└── tests
├── __init__.py
├── ollama_test.py
├── sqlserver_test.py
└── test.py
/.github/ISSUE_TEMPLATE/bug-report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug Report
3 | about: Create a report to help us improve
4 | title: "[BUG]"
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | ## Description
11 |
12 | Describe the issue or feature request in detail.
13 |
14 | ## Expected Behavior
15 |
16 | Describe the behavior you expected.
17 |
18 | ## Current Behavior
19 |
20 | Describe the current behavior, which is considered incorrect or needs improvement.
21 |
22 | ## Steps to Reproduce (for Bugs)
23 |
24 | 1.
25 | 2.
26 | 3.
27 | Provide steps to reproduce the issue, if applicable.
28 |
29 | ## Screenshots or Code Snippets (if applicable)
30 |
31 | If applicable, include screenshots or code snippets to help explain the issue.
32 |
33 | ## Possible Solution
34 |
35 | If you have a suggestion for how to fix the issue, please describe it here.
36 |
37 | ## Additional Context
38 |
39 | Add any other context about the problem here.
40 |
41 | ## Your Environment
42 |
43 | - Operating System:
44 | - Python Version:
45 | - LLM, Vectorstore or Database (with version):
46 | - Version of MindSQL (if known):
47 | - Any other relevant details:
48 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature-request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement, question
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 |
12 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
13 |
14 | **Describe the solution you'd like**
15 |
16 | A clear and concise description of what you want to happen.
17 |
18 | **Describe alternatives you've considered**
19 |
20 | A clear and concise description of any alternative solutions or features you've considered.
21 |
22 | **Additional context**
23 |
24 | Add any other context or screenshots about the feature request here.
25 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
3 | Describe the changes made in this pull request.
4 |
5 | ## Related Issue
6 |
7 | If this pull request addresses a specific issue, reference it here.
8 |
9 | ## Proposed Changes
10 |
11 | Explain the changes made in this pull request and how they address the issue.
12 |
13 | ## Checklist
14 |
15 | - [ ] My code follows the coding standards and conventions of the project.
16 | - [ ] I have added test cases in the `tests` folder to cover my changes, if applicable.
17 | - [ ] I have updated the documentation, if necessary.
18 | - [ ] I have tested my changes locally.
19 |
20 | ## Screenshots or GIFs (if applicable)
21 |
22 | Include any relevant screenshots or GIFs to visually demonstrate the changes.
23 |
24 | ## Additional Notes
25 |
26 | Add any additional notes or comments regarding the pull request.
27 |
28 | ## Reviewer Checklist
29 |
30 | - [ ] Code review completed.
31 | - [ ] Tests passed successfully.
32 | - [ ] Documentation reviewed and updated, if necessary.
33 | - [ ] Any potential side effects or edge cases considered.
34 |
--------------------------------------------------------------------------------
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "master" ]
17 | pull_request:
18 | branches: [ "master" ]
19 | schedule:
20 | - cron: '15 12 * * 5'
21 |
22 | jobs:
23 | analyze:
24 | name: Analyze
25 | # Runner size impacts CodeQL analysis time. To learn more, please see:
26 | # - https://gh.io/recommended-hardware-resources-for-running-codeql
27 | # - https://gh.io/supported-runners-and-hardware-resources
28 | # - https://gh.io/using-larger-runners
29 | # Consider using larger runners for possible analysis time improvements.
30 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
31 | timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
32 | permissions:
33 | # required for all workflows
34 | security-events: write
35 |
36 | # only required for workflows in private repositories
37 | actions: read
38 | contents: read
39 |
40 | strategy:
41 | fail-fast: false
42 | matrix:
43 | language: [ 'python' ]
44 | # CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ]
45 | # Use only 'java-kotlin' to analyze code written in Java, Kotlin or both
46 | # Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
47 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
48 |
49 | steps:
50 | - name: Checkout repository
51 | uses: actions/checkout@v4
52 |
53 | # Initializes the CodeQL tools for scanning.
54 | - name: Initialize CodeQL
55 | uses: github/codeql-action/init@v3
56 | with:
57 | languages: ${{ matrix.language }}
58 | # If you wish to specify custom queries, you can do so here or in a config file.
59 | # By default, queries listed here will override any specified in a config file.
60 | # Prefix the list here with "+" to use these queries and those in the config file.
61 |
62 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
63 | # queries: security-extended,security-and-quality
64 |
65 |
66 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
67 | # If this step fails, then you should remove it and run the build manually (see below)
68 | - name: Autobuild
69 | uses: github/codeql-action/autobuild@v3
70 |
71 | # ℹ️ Command-line programs to run using the OS shell.
72 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
73 |
74 | # If the Autobuild fails above, remove it and uncomment the following three lines.
75 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
76 |
77 | # - run: |
78 | # echo "Run, Build Application using script"
79 | # ./location_of_script_within_repo/buildscript.sh
80 |
81 | - name: Perform CodeQL Analysis
82 | uses: github/codeql-action/analyze@v3
83 | with:
84 | category: "/language:${{matrix.language}}"
85 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.toptal.com/developers/gitignore/api/pycharm+all,python,git
2 | # Edit at https://www.toptal.com/developers/gitignore?templates=pycharm+all,python,git
3 |
4 | ### Git ###
5 | # Created by git for backups. To disable backups in Git:
6 | # $ git config --global mergetool.keepBackup false
7 | *.orig
8 |
9 | # Created by git when using merge tools for conflicts
10 | *.BACKUP.*
11 | *.BASE.*
12 | *.LOCAL.*
13 | *.REMOTE.*
14 | *_BACKUP_*.txt
15 | *_BASE_*.txt
16 | *_LOCAL_*.txt
17 | *_REMOTE_*.txt
18 |
19 | ### PyCharm+all ###
20 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
21 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
22 |
23 | # User-specific stuff
24 | .idea/**/workspace.xml
25 | .idea/**/tasks.xml
26 | .idea/**/usage.statistics.xml
27 | .idea/**/dictionaries
28 | .idea/**/shelf
29 |
30 | # AWS User-specific
31 | .idea/**/aws.xml
32 |
33 | # Generated files
34 | .idea/**/contentModel.xml
35 |
36 | # Sensitive or high-churn files
37 | .idea/**/dataSources/
38 | .idea/**/dataSources.ids
39 | .idea/**/dataSources.local.xml
40 | .idea/**/sqlDataSources.xml
41 | .idea/**/dynamic.xml
42 | .idea/**/uiDesigner.xml
43 | .idea/**/dbnavigator.xml
44 |
45 | # Gradle
46 | .idea/**/gradle.xml
47 | .idea/**/libraries
48 |
49 | # Gradle and Maven with auto-import
50 | # When using Gradle or Maven with auto-import, you should exclude module files,
51 | # since they will be recreated, and may cause churn. Uncomment if using
52 | # auto-import.
53 | # .idea/artifacts
54 | # .idea/compiler.xml
55 | # .idea/jarRepositories.xml
56 | # .idea/modules.xml
57 | # .idea/*.iml
58 | # .idea/modules
59 | # *.iml
60 | # *.ipr
61 |
62 | # CMake
63 | cmake-build-*/
64 |
65 | # Mongo Explorer plugin
66 | .idea/**/mongoSettings.xml
67 |
68 | # File-based project format
69 | *.iws
70 |
71 | # IntelliJ
72 | out/
73 |
74 | # mpeltonen/sbt-idea plugin
75 | .idea_modules/
76 |
77 | # JIRA plugin
78 | atlassian-ide-plugin.xml
79 |
80 | # Cursive Clojure plugin
81 | .idea/replstate.xml
82 |
83 | # SonarLint plugin
84 | .idea/sonarlint/
85 |
86 | # Crashlytics plugin (for Android Studio and IntelliJ)
87 | com_crashlytics_export_strings.xml
88 | crashlytics.properties
89 | crashlytics-build.properties
90 | fabric.properties
91 |
92 | # Editor-based Rest Client
93 | .idea/httpRequests
94 |
95 | # Android studio 3.1+ serialized cache file
96 | .idea/caches/build_file_checksums.ser
97 |
98 | ### PyCharm+all Patch ###
99 | # Ignore everything but code style settings and run configurations
100 | # that are supposed to be shared within teams.
101 |
102 | .idea/*
103 |
104 | !.idea/codeStyles
105 | !.idea/runConfigurations
106 |
107 | ### Python ###
108 | # Byte-compiled / optimized / DLL files
109 | __pycache__/
110 | *.py[cod]
111 | *$py.class
112 |
113 | # C extensions
114 | *.so
115 |
116 | # Distribution / packaging
117 | .Python
118 | build/
119 | develop-eggs/
120 | dist/
121 | downloads/
122 | eggs/
123 | .eggs/
124 | lib/
125 | lib64/
126 | parts/
127 | testing/*
128 | sdist/
129 | var/
130 | wheels/
131 | share/python-wheels/
132 | *.egg-info/
133 | .installed.cfg
134 | *.egg
135 | MANIFEST
136 |
137 | # PyInstaller
138 | # Usually these files are written by a python script from a template
139 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
140 | *.manifest
141 | *.spec
142 |
143 | # Installer logs
144 | pip-log.txt
145 | pip-delete-this-directory.txt
146 |
147 | # Unit test / coverage reports
148 | htmlcov/
149 | .tox/
150 | .nox/
151 | .coverage
152 | .coverage.*
153 | .cache
154 | nosetests.xml
155 | coverage.xml
156 | *.cover
157 | *.py,cover
158 | .hypothesis/
159 | .pytest_cache/
160 | cover/
161 |
162 | # Translations
163 | *.mo
164 | *.pot
165 |
166 | # Django stuff:
167 | *.log
168 | local_settings.py
169 | db.sqlite3
170 | db.sqlite3-journal
171 |
172 | # Flask stuff:
173 | instance/
174 | .webassets-cache
175 |
176 | # Scrapy stuff:
177 | .scrapy
178 |
179 | # Sphinx documentation
180 | docs/_build/
181 |
182 | # PyBuilder
183 | .pybuilder/
184 | target/
185 |
186 | # Jupyter Notebook
187 | .ipynb_checkpoints
188 |
189 | # IPython
190 | profile_default/
191 | ipython_config.py
192 |
193 | # pyenv
194 | # For a library or package, you might want to ignore these files since the code is
195 | # intended to run in multiple environments; otherwise, check them in:
196 | # .python-version
197 |
198 | # pipenv
199 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
200 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
201 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
202 | # install all needed dependencies.
203 | #Pipfile.lock
204 |
205 | # poetry
206 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
207 | # This is especially recommended for binary packages to ensure reproducibility, and is more
208 | # commonly ignored for libraries.
209 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
210 | #poetry.lock
211 |
212 | # pdm
213 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
214 | #pdm.lock
215 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
216 | # in version control.
217 | # https://pdm.fming.dev/#use-with-ide
218 | .pdm.toml
219 |
220 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
221 | __pypackages__/
222 |
223 | # Celery stuff
224 | celerybeat-schedule
225 | celerybeat.pid
226 |
227 | # SageMath parsed files
228 | *.sage.py
229 |
230 | # Environments
231 | .env
232 | .venv
233 | env/
234 | venv/
235 | ENV/
236 | env.bak/
237 | venv.bak/
238 |
239 | # Spyder project settings
240 | .spyderproject
241 | .spyproject
242 |
243 | # Rope project settings
244 | .ropeproject
245 |
246 | # mkdocs documentation
247 | /site
248 |
249 | # mypy
250 | .mypy_cache/
251 | .dmypy.json
252 | dmypy.json
253 |
254 | # Pyre type checker
255 | .pyre/
256 |
257 | # pytype static type analyzer
258 | .pytype/
259 |
260 | # Cython debug symbols
261 | cython_debug/
262 |
263 | # PyCharm
264 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
265 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
266 | # and can be added to the global gitignore or merged into this file. For a more nuclear
267 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
268 | #.idea/
269 |
270 | ### Python Patch ###
271 | # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
272 | poetry.toml
273 | poetry.lock
274 | # ruff
275 | .ruff_cache/
276 |
277 | # LSP config files
278 | pyrightconfig.json
279 |
280 | # End of https://www.toptal.com/developers/gitignore/api/pycharm+all,python,git
281 | *.lock
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | [Moderator Email](mailto:samarpatel.mi@gmail.com).
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to MindSQL! Your contributions help improve the project for everyone. Before you get started, please take a moment to review these guidelines to ensure a smooth collaboration process.
4 |
5 | ## Getting Started
6 |
7 | 1. **Fork the Repository**: Fork the MindSQL repository to your own GitHub account.
8 |
9 | 2. **Clone the Repository**: Clone your fork of the repository locally onto your machine.
10 |
11 | ```bash
12 | git clone https://github.com/{YourUsername}/MindSQL.git
13 | ```
14 |
15 | 3. **Create a Branch**: Create a new branch for your work based on the `master` branch.
16 |
17 | ```bash
18 | git checkout -b your-branch-name master
19 | ```
20 |
21 | ## Making Changes
22 |
23 | 1. **Adhere to Coding Standards**: Make sure your code follows the PEP8 coding standards and conventions used in the project. Consistency makes maintenance easier for everyone.
24 |
25 | 2. **Test Your Changes**: Thoroughly test your changes to ensure they work as intended. Add a test case in the `tests` folder to cover your changes if applicable.
26 |
27 | ## Submitting Changes
28 |
29 | 1. **Commit Your Changes**: Once you've made your changes, commit them to your branch with clear and descriptive commit messages.
30 |
31 | ```bash
32 | git commit -am 'Add descriptive commit message'
33 | ```
34 |
35 | 2. **Push Your Changes**: Push your changes to your fork on GitHub.
36 |
37 | ```bash
38 | git push origin your-branch-name
39 | ```
40 |
41 | 3. **Submit a Pull Request**: Go to the MindSQL repository on GitHub and submit a pull request from your branch to the `master` branch. Be sure to include a clear description of the problem you're solving and the solution you're proposing.
42 |
43 | ## Code of Conduct
44 |
45 | Please note that MindSQL has a [Code of Conduct](./CODE_OF_CONDUCT.md). By participating in this project, you agree to abide by its terms.
46 |
47 | ## Need Help?
48 |
49 | If you need any assistance or have questions about contributing, feel free to reach out to us via GitHub issues or email.
50 |
51 | We appreciate your contributions to MindSQL and thank you for helping make it better!
52 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🧠 MindSQL
2 |
3 | MindSQL is a Python RAG (Retrieval-Augmented Generation) Library designed to streamline the interaction between users and their databases using just a few lines of code. With seamless integration for renowned databases such as PostgreSQL, MySQL, and SQLite, MindSQL also extends its capabilities to major databases like Snowflake and BigQuery by extending the `IDatabase` Interface. This library utilizes large language models (LLM) like GPT-4, Llama 2, Google Gemini, and supports knowledge bases like ChromaDB and Faiss.
4 |
5 | 
6 |
7 |
8 | ## 🚀 Installation
9 |
10 | To install MindSQL, you can use pip:
11 |
12 | ```commandline
13 | pip install mindsql
14 | ```
15 |
16 | MindSQL requires Python 3.10 or higher.
17 |
18 | ## 💡 Usage
19 | ```python
20 | # !pip install mindsql
21 |
22 | from mindsql.core import MindSQLCore
23 | from mindsql.databases import Sqlite
24 | from mindsql.llms import GoogleGenAi
25 | from mindsql.vectorstores import ChromaDB
26 |
27 | # Add Your Configurations
28 | config = {"api_key": "YOUR-API-KEY"}
29 |
30 | # Choose the Vector Store. LLM and DB You Want to Work With And
31 | # Create MindSQLCore Instance With Configured Llm, Vectorstore, And Database
32 | minds = MindSQLCore(
33 | llm=GoogleGenAi(config=config),
34 | vectorstore=ChromaDB(),
35 | database=Sqlite()
36 | )
37 |
38 | # Create a Database Connection Using The Specified URL
39 | connection = minds.database.create_connection(url="YOUR_DATABASE_CONNECTION_URL")
40 |
41 | # Index All Data Definition Language (DDL) Statements in The Specified Database Into The Vectorstore
42 | minds.index_all_ddls(connection=connection, db_name='NAME_OF_THE_DB')
43 |
44 | # Index Question-Sql Pair in Bulk From the Specified Example Path
45 | minds.index(bulk=True, path="your-qsn-sql-example.json")
46 |
47 | # Ask a Question to The Database And Visualize The Result
48 | response = minds.ask_db(
49 | question="YOUR_QUESTION",
50 | connection=connection,
51 | visualize=True
52 | )
53 |
54 | # Extract And Display The Chart From The Response
55 | chart = response["chart"]
56 | chart.show()
57 |
58 | # Close The Connection to Your DB
59 | connection.close()
60 | ```
61 | ## 📁 Code Structure
62 |
63 | - **_utils:** Utility modules containing constants and a logger.
64 | - **_helper:** The helper module.
65 | - **core:** The main core module, `minds_core.py`.
66 | - **databases:** Database-related modules.
67 | - **llms:** Modules related to Language Models.
68 | - **testing:** Testing scripts.
69 | - **vectorstores:** Modules related to vector stores.
70 | - **poetry.lock** and **pyproject.toml:** Poetry dependencies and configuration files.
71 | - **tests:** Testcases.
72 |
73 | ## 🤝 Contributing Guidelines
74 |
75 | Thank you for considering contributing to our project! Please follow these guidelines for smooth collaboration:
76 |
77 | 1. Fork the repository and create your branch from master.
78 | 2. Ensure your code adheres to our coding standards and conventions.
79 | 3. Test your changes thoroughly and add a test case in the `tests` folder.
80 | 4. Submit a pull request with a clear description of the problem and solution.
81 |
82 | [Learn more](CONTRIBUTING.md)
83 |
84 | ## 🐛 Bug Reports
85 |
86 | If you encounter a bug while using MindSQL, help us resolve it by following these steps:
87 |
88 | 1. Check existing issues to see if the bug has been reported.
89 | 2. If not, open a new issue with a detailed description, including steps to reproduce and relevant screenshots or error messages.
90 |
91 | [Learn more](.github/ISSUE_TEMPLATE/bug-report.md)
92 |
93 | ## 🚀 Feature Requests
94 |
95 | We welcome suggestions for new features or improvements to MindSQL. Here's how you can request a new feature:
96 |
97 | 1. Check existing feature requests to avoid duplication.
98 | 2. If your feature request is unique, open a new issue and describe the feature you would like to see.
99 | 3. Provide as much context and detail as possible to help us understand your request.
100 |
101 | [Learn more](.github/ISSUE_TEMPLATE/feature-request.md)
102 |
103 | ## 📣 Feedback
104 |
105 | We value your feedback and strive to improve MindSQL. Here's how you can share your thoughts with us:
106 |
107 | - Open an issue to provide general feedback, suggestions, or comments.
108 | - Be constructive and specific in your feedback to help us understand your perspective better.
109 |
110 | Thank you for your interest in contributing to our project! We appreciate your support and look forward to working with you. 🚀
111 |
112 |
113 |
114 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Versions which are currently being supported with security updates.
6 |
7 | | Version | Supported |
8 | | ------- | ------------------ |
9 | | 0.2.1 | :white_check_mark: |
10 | | 0.2.0 | :white_check_mark: |
11 | |< 0.1.x | :x: |
12 |
13 | ## Reporting a Vulnerability
14 |
15 | **GitHub Repository Security Vulnerability Reporting Policy**
16 |
17 | **1. Introduction:**
18 |
19 | This document outlines the procedure for reporting security vulnerabilities found within the GitHub repository associated with MindSQL. We take security vulnerabilities seriously and encourage responsible disclosure to ensure the integrity and security of our project.
20 |
21 | **2. Reporting Process:**
22 |
23 | 2.1. **Responsible Disclosure:**
24 | - We encourage security researchers, collaborators, and users to responsibly disclose any security vulnerabilities they discover in our project.
25 | - Vulnerabilities should be reported promptly and privately to samarpatel.mi@gmail.com, allowing us to assess and address the issue before it is publicly disclosed.
26 |
27 | 2.2. **Information to Include:**
28 | - When reporting a security vulnerability, please provide detailed information to help us understand and reproduce the issue. This may include:
29 | - Description of the vulnerability
30 | - Steps to reproduce
31 | - Affected versions
32 | - Impact and potential exploit scenarios
33 | - Any additional context or mitigating factors
34 |
35 | 2.3. **Confidentiality:**
36 | - We respect the privacy and security of individuals reporting vulnerabilities and will handle all reports with confidentiality.
37 | - Vulnerability reports should not be shared publicly until an appropriate fix has been implemented and released.
38 |
39 | **3. Response and Resolution:**
40 |
41 | 3.1. **Acknowledgment:**
42 | - Upon receiving a vulnerability report, we will acknowledge receipt within a week.
43 | - We appreciate the effort and responsible behavior of those reporting vulnerabilities and will keep them informed throughout the resolution process.
44 |
45 | 3.2. **Assessment and Validation:**
46 | - Our team will promptly assess and validate the reported vulnerability to determine its severity and impact on the project.
47 | - We may request additional information or clarification from the reporter if needed to fully understand the issue.
48 |
49 | 3.3. **Mitigation and Fix:**
50 | - Once validated, we will work diligently to develop and implement an appropriate fix for the vulnerability.
51 | - Depending on the nature of the vulnerability, we may release a patch, update, or workaround to address the issue.
52 |
53 | **4. Public Disclosure:**
54 |
55 | 4.1. **Coordination:**
56 | - We aim to coordinate the public disclosure of security vulnerabilities to ensure that users have access to relevant information and mitigation measures.
57 | - Public disclosure will be coordinated with the reporter to ensure that it aligns with their preferences and any responsible disclosure agreements.
58 |
59 | 4.2. **Timing:**
60 | - We will aim to disclose security vulnerabilities publicly only after an appropriate fix has been implemented and released to minimize the risk of exploitation.
61 |
62 | **5. Legal and Ethical Considerations:**
63 |
64 | 5.1. **Non-Disclosure Agreement (NDA):**
65 | - If requested, we are open to signing a non-disclosure agreement (NDA) with reporters to protect sensitive information exchanged during the vulnerability disclosure process.
66 |
67 | 5.2. **Legal Protections:**
68 | - We are committed to complying with applicable laws and regulations governing the reporting and handling of security vulnerabilities, including protections for security researchers.
69 |
70 | **6. Conclusion:**
71 |
72 | By following this security vulnerability reporting policy, we aim to foster a collaborative and transparent approach to addressing security issues within our project. We appreciate the cooperation of security researchers, collaborators, and users in helping us maintain the security and integrity of our GitHub repository.
73 |
--------------------------------------------------------------------------------
/mindsql/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/MindSQL/f7e24b3022ddc2d820e85021637ad38f6fdda073/mindsql/__init__.py
--------------------------------------------------------------------------------
/mindsql/_helper/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/MindSQL/f7e24b3022ddc2d820e85021637ad38f6fdda073/mindsql/_helper/__init__.py
--------------------------------------------------------------------------------
/mindsql/_helper/helper.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 |
4 | import sqlparse
5 | from sqlparse.exceptions import SQLParseError
6 | from .._utils import logger
7 | from .._utils.constants import LOG_AND_RETURN_CONSTANT, JSON_FILE_ERROR_CONSTANT
8 |
9 | log = logger.init_loggers("Helper")
10 |
11 |
12 | def _sanitize_plotly_code(raw_plotly_code: str) -> str:
13 | """
14 | A method to sanitize the plotly code.
15 |
16 | Parameters:
17 | raw_plotly_code (str): The raw plotly code.
18 |
19 | Returns:
20 | str: The sanitized plotly code.
21 | """
22 | return raw_plotly_code.replace("fig.show()", "")
23 |
24 |
25 | def has_select_and_semicolon(llm_response: str) -> bool:
26 | """
27 | A method to check if the LLM response contains a SELECT statement and a semicolon.
28 |
29 | Parameters:
30 | llm_response (str): The LLM response.
31 |
32 | Returns:
33 | bool: True if the LLM response contains a SELECT statement and a semicolon, False otherwise.
34 | """
35 | index_select = llm_response.upper().find("SELECT")
36 | index_semicolon = llm_response.find(";")
37 |
38 | return index_select != -1 and index_semicolon != -1 and index_select < index_semicolon
39 |
40 |
41 | def extract_sql(llm_response: str) -> str:
42 | """
43 | A method to extract the SQL from the LLM response.
44 |
45 | Parameters:
46 | llm_response (str): The LLM response.
47 |
48 | Returns:
49 | str: The extracted SQL.
50 | """
51 |
52 | def log_and_return(extracted_sql: str) -> str:
53 | """
54 | A helper function to log and return the extracted SQL.
55 |
56 | Parameters:
57 | extracted_sql (str): The extracted SQL.
58 |
59 | Returns:
60 | str: The extracted SQL.
61 | """
62 | log.info(LOG_AND_RETURN_CONSTANT.format(llm_response, extracted_sql))
63 | return extracted_sql
64 |
65 | sql_match = re.search(r"```(sql)?\n(.+?)```", llm_response, re.DOTALL)
66 | if sql_match:
67 | return log_and_return(sql_match.group(2).replace("`", ""))
68 | elif has_select_and_semicolon(llm_response):
69 | start_sql = llm_response.find("SELECT")
70 | end_sql = llm_response.find(";")
71 | return log_and_return(llm_response[start_sql:end_sql + 1].replace("`", ""))
72 | return llm_response
73 |
74 |
75 | def validate_sql(sql: str) -> bool:
76 | """
77 | A method to validate the SQL.
78 |
79 | Parameters:
80 | sql (str): The SQL.
81 |
82 | Returns:
83 | bool: True if the SQL is valid, False otherwise.
84 | """
85 | try:
86 | parsed_statements = sqlparse.parse(sql)
87 |
88 | if not parsed_statements:
89 | return False
90 |
91 | for statement in parsed_statements:
92 | if any(token.ttype in sqlparse.tokens.Error for token in statement.tokens):
93 | return False
94 |
95 | return has_select_and_semicolon(sql)
96 |
97 | except SQLParseError:
98 | return False
99 |
100 |
101 | def load_json_to_dict(json_filepath: str) -> dict:
102 | """
103 | A method to load the JSON file to a dictionary.
104 |
105 | Parameters:
106 | json_filepath (str): The path to the JSON file.
107 |
108 | Returns:
109 | dict: The dictionary.
110 | """
111 | try:
112 | with open(json_filepath, 'r') as json_file:
113 | json_data = json.load(json_file)
114 | return json_data
115 | except Exception as e:
116 | log.info(JSON_FILE_ERROR_CONSTANT.format(e))
117 | return {}
118 |
--------------------------------------------------------------------------------
/mindsql/_utils/__init__.py:
--------------------------------------------------------------------------------
1 | from . import constants
2 | from . import prompts
3 | from . import logger
--------------------------------------------------------------------------------
/mindsql/_utils/constants.py:
--------------------------------------------------------------------------------
1 | LOG_AND_RETURN_CONSTANT = "Output from LLM: {}\nExtracted SQL: {}"
2 | JSON_FILE_ERROR_CONSTANT = "Error loading JSON file: {}"
3 | LOGS_FILE_PATH = "logs/mindsql-{}.log"
4 | LOGS_FORMATTER = "%(levelname)s — %(asctime)s — %(name)s — Function:%(funcName)s — Line:%(lineno)d — %(message)s"
5 | CONNECTION_ESTABLISH_ERROR_CONSTANT = "Connection is None. Please establish a connection first."
6 | NO_DATA_FOUND_IN_JSON_CONSTANT = "No data found in JSON file at {}"
7 | BULK_FALSE_ERROR = "`path` was provided but `bulk` is set to False."
8 | BULK_DATA_SUCCESS_MESSAGE_CONSTANT = "Bulk data processed successfully"
9 | SQL_NOT_PROVIDED_CONSTANT = "Please also provide a SQL query"
10 | ADD_QUESTION_SQL_MESSAGE_CONSTANT = "Adding question and sql...."
11 | ADD_DOCS_MESSAGE_CONSTANT = "Adding documentation...."
12 | ADD_DDL_MESSAGE_CONSTANT = "Adding DDL...."
13 | DDL_PROCESSED_SUCCESSFULLY = "DDLs Processed Successfully"
14 | SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT = "Successfully connected to {} database"
15 | ERROR_CONNECTING_TO_DB_CONSTANT = "Error connecting to {} database\n{}"
16 | INVALID_DB_CONNECTION_OBJECT = "Invalid {} database connection object."
17 | ERROR_WHILE_RUNNING_QUERY = "Error while running query: {}"
18 | MYSQL_SHOW_DATABASE_QUERY = "SHOW DATABASES;"
19 | MYSQL_DB_TABLES_INFO_SCHEMA_QUERY = "SELECT table_name FROM information_schema.tables WHERE table_schema = '{}';"
20 | MYSQL_SHOW_CREATE_TABLE_QUERY = "SHOW CREATE TABLE `{}`;"
21 | POSTGRESQL_SHOW_DATABASE_QUERY = "SELECT datname as DATABASE_NAME FROM pg_database WHERE datistemplate = false;"
22 | POSTGRESQL_DB_TABLES_INFO_SCHEMA_QUERY = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_catalog = '{db}';"
23 | ERROR_DOWNLOADING_SQLITE_DB_CONSTANT = "Error downloading sqlite db: {}"
24 | SQLLITE_GET_DB_QUERY = "SELECT DISTINCT name FROM pragma_database_list;"
25 | SQLLIE_TABLE_INFO_SCHEMA_CONSTANT = "SELECT name FROM sqlite_master WHERE type='table';"
26 | SQLLITE_TRAINING_DATASET_QUERY_CONSTANT = "SELECT sql FROM sqlite_master WHERE name = '{}';"
27 | GOOGLE_GEN_AI_VALUE_ERROR = "For GoogleGenAI, config must be provided with an api_key"
28 | GOOGLE_GEN_AI_APIKEY_ERROR = "config must contain a Google AI Studio api_key"
29 | LLAMA_VALUE_ERROR = "For LlamaAI, config must be provided with a model_path"
30 | CONFIG_REQUIRED_ERROR = "Configuration is required."
31 | LLAMA_PROMPT_EXCEPTION = "Prompt cannot be empty."
32 | OPENAI_VALUE_ERROR = "OpenAI API key is required"
33 | PROMPT_EMPTY_EXCEPTION = "Prompt cannot be empty."
34 | POSTGRESQL_SHOW_CREATE_TABLE_QUERY = """SELECT 'CREATE TABLE "' || table_name || '" (' || array_to_string(array_agg(column_name || ' ' || data_type), ', ') || ');' AS create_statement FROM information_schema.columns WHERE table_name = '{table}' GROUP BY table_name;"""
35 | ANTHROPIC_VALUE_ERROR = "Anthropic API key is required"
36 | SQLSERVER_SHOW_DATABASE_QUERY= "SELECT name FROM sys.databases;"
37 | SQLSERVER_DB_TABLES_INFO_SCHEMA_QUERY = "SELECT CONCAT(TABLE_SCHEMA,'.',TABLE_NAME) FROM [{db}].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"
38 | SQLSERVER_SHOW_CREATE_TABLE_QUERY = "DECLARE @TableName NVARCHAR(MAX) = '{table}'; DECLARE @SchemaName NVARCHAR(MAX) = '{schema}'; DECLARE @SQL NVARCHAR(MAX); SELECT @SQL = 'CREATE TABLE ' + @SchemaName + '.' + t.name + ' (' + CHAR(13) + ( SELECT ' ' + c.name + ' ' + UPPER(tp.name) + CASE WHEN tp.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(10)) END + ')' WHEN tp.name IN ('decimal', 'numeric') THEN '(' + CAST(c.precision AS VARCHAR(10)) + ',' + CAST(c.scale AS VARCHAR(10)) + ')' ELSE '' END + ',' + CHAR(13) FROM sys.columns c JOIN sys.types tp ON c.user_type_id = tp.user_type_id WHERE c.object_id = t.object_id ORDER BY c.column_id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') + CHAR(13) + ')' FROM sys.tables t JOIN sys.schemas s ON t.schema_id = s.schema_id WHERE t.name = @TableName AND s.name = @SchemaName; SELECT @SQL AS SQLQuery;"
39 | OLLAMA_CONFIG_REQUIRED = "{type} configuration is required."
40 |
--------------------------------------------------------------------------------
/mindsql/_utils/logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import sys
4 | from datetime import datetime
5 |
6 | from .constants import LOGS_FILE_PATH, LOGS_FORMATTER
7 |
8 | FORMATTER = logging.Formatter(LOGS_FORMATTER)
9 |
10 |
11 | def get_console_handler():
12 | """
13 | Get the console handler.
14 |
15 | Returns:
16 | logging.StreamHandler: The console handler object.
17 | """
18 | console_handler = logging.StreamHandler(sys.stdout)
19 | console_handler.setFormatter(FORMATTER)
20 | return console_handler
21 |
22 |
23 | def get_file_handler():
24 | """
25 | Get the file handler.
26 |
27 | Returns:
28 | logging.FileHandler: The file handler object.
29 | """
30 | log_directory = "logs"
31 | if not os.path.exists(log_directory):
32 | os.makedirs(log_directory)
33 | today_date = datetime.now().strftime("%d-%m-%Y")
34 | filename = LOGS_FILE_PATH.format(today_date)
35 | file_handler = logging.FileHandler(filename)
36 | file_handler.setFormatter(FORMATTER)
37 | return file_handler
38 |
39 |
40 | def init_loggers(logger_name: str = "Mindsql") -> logging.Logger:
41 | """
42 | Initialize the loggers.
43 |
44 | Parameters:
45 | logger_name (str): The name of the logger.
46 |
47 | Returns:
48 | logging.Logger: The logger object.
49 | """
50 | logger = logging.getLogger(logger_name)
51 | if not logger.handlers:
52 | logger.setLevel(logging.DEBUG)
53 | logger.addHandler(get_console_handler())
54 | logger.addHandler(get_file_handler())
55 | logger.propagate = False
56 | return logger
57 |
--------------------------------------------------------------------------------
/mindsql/_utils/prompts.py:
--------------------------------------------------------------------------------
1 | DEFAULT_PROMPT: str = """As a {dialect_name} expert, your task is to generate SQL queries based on user questions. Ensure that your {dialect_name} queries are syntactically correct and tailored to the user's inquiry. Retrieve at most 10 results using the LIMIT clause and order them for relevance. Avoid querying for all columns from a table. Select only the necessary columns wrapped in backticks (`). Use CURDATE() to handle 'today' queries and employ the LIKE clause for precise matches in {dialect_name}. Carefully consider column names and their respective tables to avoid querying non-existent columns. Stop after delivering the SQLQuery, avoiding follow-up questions.
2 |
3 | Follow this format:
4 | Question: User's question here
5 | SQLQuery: Your SQL query without preamble
6 |
7 | No preamble
8 |
9 |
10 | """
11 |
12 | DDL_PROMPT = """Only use the following tables:
13 | {}
14 |
15 | """
16 | FEW_SHOT_EXAMPLE = """Make use of the following Example 'SQLQuery' for generating SQL query:
17 | {}
18 |
19 | """
20 |
21 | FINAL_RESPONSE_PROMPT = """You are the helpful assistant designed to answer user questions based on the data provided from the database in context. Your goal is to analyze the user's query and provide a helpful response using only the information available in the context. If Context is None or Empty, say you don't have the data to answer the question.
22 |
23 | ###DATAFRAME CONTEXT:
24 | {context_df}
25 |
26 | ###USER QUESTION:
27 | {user_query}
28 |
29 | ###ASSISTANT RESPONSE:
30 | """
31 |
32 | PLOTLY_PROMPT = """You are a proficient Python developer with expertise in the Plotly library. Your objective is to generate Python code to create a BEAUTIFUL chart based on the query using the
33 | provided Pandas dataframe. You can create any chart you want.
34 |
35 | ### QUERY:
36 | {query}
37 |
38 | ### DATAFRAME:
39 | {df}
40 |
41 | ### INSTRUCTIONS: 1. Create a function called 'get_chart'. 2. Begin by importing the necessary libraries (Pandas,
42 | Plotly, and Decimal if needed). 3. Utilize the 'plotly.graph_objects' library if the provided dataframe has more
43 | than 2 columns to showcase multi bar plots. Otherwise, utilize the 'plotly.express' library. 4. Generate a chart
44 | using the provided dataframe and the Plotly library. 5. Accurately interpret the x-axis title, y-axis title,
45 | and chart title as per the user's query and the dataframe. 6. Utilize the 'update_layout' method to include the
46 | x-axis title, y-axis title, chart title, plot background color, and paper background color, setting both of them
47 | to blue (HEX code: #0e243b). 7. Set the font color to white (HEX code: #f7f9fa) using the 'update_layout' method.
48 | Execute the created function with the argument as the provided dataframe, at the outer indent at the end and
49 | store the result in a variable called 'chart'.
50 |
51 | ### CODE CRITERIA
52 | - Optimize the code for efficiency and clarity.
53 | - Avoid using incorrect syntax.
54 | - Ensure that the code is well-commented for readability and syntactically correct.
55 | """
56 |
57 | SQL_EXCEPTION_RESPONSE = """Apologies for the inconvenience! 🙏 It seems the database is currently experiencing a bit
58 | of a hiccup and isn't cooperating as we'd like. 🤖"""
59 |
60 |
--------------------------------------------------------------------------------
/mindsql/core/__init__.py:
--------------------------------------------------------------------------------
1 | from .mindsql_core import MindSQLCore
2 |
--------------------------------------------------------------------------------
/mindsql/core/mindsql_core.py:
--------------------------------------------------------------------------------
1 | import re
2 | import sys
3 | from abc import ABC
4 | from typing import Union, Optional
5 |
6 | import pandas as pd
7 | import plotly.express as px
8 | import plotly.graph_objects as go
9 | from plotly.subplots import make_subplots
10 |
11 | from .. import _helper
12 | from .._helper.helper import load_json_to_dict
13 | from .._utils import prompts, logger
14 | from .._utils.constants import NO_DATA_FOUND_IN_JSON_CONSTANT, \
15 | BULK_DATA_SUCCESS_MESSAGE_CONSTANT, SQL_NOT_PROVIDED_CONSTANT, ADD_QUESTION_SQL_MESSAGE_CONSTANT, \
16 | ADD_DOCS_MESSAGE_CONSTANT, ADD_DDL_MESSAGE_CONSTANT, BULK_FALSE_ERROR, DDL_PROCESSED_SUCCESSFULLY
17 | from .._utils.prompts import DDL_PROMPT, SQL_EXCEPTION_RESPONSE, FEW_SHOT_EXAMPLE, FINAL_RESPONSE_PROMPT, PLOTLY_PROMPT
18 | from ..databases import IDatabase
19 | from ..llms import ILlm
20 | from ..vectorstores import IVectorstore
21 |
22 | log = logger.init_loggers("Minds Core")
23 |
24 |
25 | class MindSQLCore:
26 | def __init__(self, database: IDatabase, vectorstore: IVectorstore, llm: ILlm) -> None:
27 | """
28 | Initialize the class with an optional config parameter.
29 |
30 | Returns:
31 | None
32 | """
33 | self.database = database
34 | self.vectorstore = vectorstore
35 | self.llm = llm
36 |
37 | def create_database_query(self, question: str, connection, tables: list, **kwargs) -> str:
38 | """
39 | A method to create the database query.
40 |
41 | Parameters:
42 | question (str): The question.
43 | connection (any): The connection object.
44 | tables (list): The list of tables.
45 |
46 | Returns:
47 | str: The database query.
48 | """
49 | question_sql_list = self.vectorstore.retrieve_relevant_question_sql(question, **kwargs)
50 | prompt = self.build_sql_prompt(question=question, connection=connection, question_sql_list=question_sql_list,
51 | tables=tables, **kwargs)
52 | log.info(prompt)
53 | llm_response = self.llm.invoke(prompt, **kwargs)
54 | return _helper.helper.extract_sql(llm_response)
55 |
56 | @staticmethod
57 | def stuff_ddl_in_prompt(initial_prompt: str, ddl_list: list[str]) -> str:
58 | """
59 | A method to add DDL statements to the prompt.
60 |
61 | Parameters:
62 | initial_prompt (str): The initial prompt.
63 | ddl_list (list[str]): The list of DDL statements.
64 |
65 | Returns:
66 | str: The updated prompt with DDL statements.
67 | """
68 | if ddl_list:
69 | ddl_statements = "\n".join(ddl_list)
70 | prompt = f"{initial_prompt}\n{DDL_PROMPT.format(ddl_statements)}"
71 | return prompt
72 | return initial_prompt
73 |
74 | @staticmethod
75 | def stuff_documentation_in_prompt(initial_prompt: str, documentation_list: list[str]) -> str:
76 | """
77 | A method to add documentation statements to the prompt.
78 |
79 | Parameters:
80 | initial_prompt (str): The initial prompt.
81 | documentation_list (list[str]): The list of documentation statements.
82 |
83 | Returns:
84 | str: The updated prompt with documentation statements.
85 | """
86 | if documentation_list:
87 | doc_statements = "\n".join(documentation_list)
88 | prompt = f"{initial_prompt}\n{doc_statements}"
89 | return prompt
90 | return initial_prompt
91 |
92 | @staticmethod
93 | def stuff_sql_in_prompt(initial_prompt: str, sql_list: list[str]) -> str:
94 | """
95 | A method to add SQL statements to the prompt.
96 |
97 | Parameters:
98 | initial_prompt (str): The initial prompt.
99 | sql_list (list[str]): The list of SQL statements.
100 |
101 | Returns:
102 | str: The updated prompt with SQL statements.
103 | """
104 | if sql_list:
105 | sql_statements = "\n".join(sql_list)
106 | prompt = f"{initial_prompt}\n{sql_statements}"
107 | return prompt
108 |
109 | def build_sql_prompt(self, question: str, connection: any, question_sql_list: list[str], tables: list[str],
110 | **kwargs) -> str:
111 | """
112 | A method to build the SQL prompt.
113 |
114 | Parameters:
115 | question (str): The question.
116 | connection (any): The connection object.
117 | question_sql_list (list[str]): The list of similar questions.
118 | tables (list[str]): The list of tables.
119 |
120 | Returns:
121 | str: The SQL prompt.
122 | """
123 | dialect_name = self.database.get_dialect()
124 | initial_prompt = self.__create_initial_prompt(question_sql_list, dialect_name)
125 |
126 | ddl_statements = self.__get_ddl_statements(connection, tables, question, **kwargs)
127 | initial_prompt = self.stuff_ddl_in_prompt(initial_prompt, ddl_statements)
128 |
129 | doc_statements = self.vectorstore.retrieve_relevant_documentation(question, **kwargs)
130 | initial_prompt = self.stuff_documentation_in_prompt(initial_prompt, doc_statements)
131 | final_prompt = f"{initial_prompt}\n'Question': {question}"
132 | return final_prompt
133 |
134 | @staticmethod
135 | def __create_initial_prompt(question_sql_list: list[str], dialect_name: str) -> str:
136 | """
137 | A method to create the initial prompt.
138 |
139 | Parameters:
140 | question_sql_list (list[str]): The list of similar questions.
141 | dialect_name (str): The dialect name.
142 |
143 | Returns:
144 | str: The initial prompt.
145 | """
146 | initial_prompt = prompts.DEFAULT_PROMPT.format(dialect_name=dialect_name)
147 | return f'{initial_prompt}\n{FEW_SHOT_EXAMPLE.format(MindSQLCore.__format_qsn_sql(question_sql_list))}'
148 |
149 | @staticmethod
150 | def __format_qsn_sql(question_sql_list: list):
151 | """
152 | A method to format the question and SQL.
153 |
154 | Parameters:
155 | question_sql_list (list): The list of question and SQL.
156 |
157 | Returns:
158 | str: The formatted string.
159 | """
160 | formatted_string = "\n\n"
161 |
162 | for query_dict in question_sql_list:
163 | formatted_string += "'Question': \"{}\"\n'SQLQuery': '{}'\n\n".format(query_dict.get('Question'),
164 | query_dict.get('SQLQuery'))
165 | return formatted_string
166 |
167 | def __get_ddl_statements(self, connection: any, tables: list[str], question: str, **kwargs) -> list[str]:
168 | """
169 | A method to get the DDL statements.
170 |
171 | Parameters:
172 | connection (any): The connection object.
173 | tables (list[str]): The list of tables.
174 | question (str): The input question.
175 |
176 | Returns:
177 | list[str]: The list of DDL statements.
178 | """
179 | if tables and connection:
180 | ddl_statements = []
181 | for table_name in tables:
182 | ddl_statements.append(self.database.get_ddl(connection=connection, table_name=table_name))
183 | else:
184 | ddl_statements = self.vectorstore.retrieve_relevant_ddl(question, **kwargs)
185 | return ddl_statements
186 |
187 | def ask_db(self, connection, question: Union[str, None] = None, table_names: list = None, visualize: bool = False,
188 | **kwargs) -> dict:
189 | """
190 | A method to ask the database and return the result as a dictionary with the following keys:
191 | - sql (str): The SQL query.
192 | - sql_result (pd.DataFrame): The result of the SQL query.
193 | - response (str): The response from the LLM
194 | - chart (str): The chart
195 | - error (Exception): The error if any
196 |
197 | Parameters:
198 | connection (any): The connection object.
199 | question (str): The input question.
200 | table_names (list): The list of tables.
201 | visualize (bool): Whether to visualize the results.
202 |
203 | Returns:
204 | dict: The result dictionary.
205 |
206 | """
207 |
208 | result = {}
209 | try:
210 | sql = self.create_database_query(question=question, connection=connection, tables=table_names, **kwargs)
211 | result["sql"] = sql
212 |
213 | if _helper.helper.validate_sql(sql):
214 | df = self.database.execute_sql(connection, sql)
215 | result.update({"sql_result": df, "response": self.llm.invoke(
216 | FINAL_RESPONSE_PROMPT.format(context_df=df, user_query=question)),
217 | "chart": self.visualize(question, df, visualize)})
218 | log.info(f"Query: {question} \nLLM Response: {result.get('response')}")
219 | else:
220 | log.info(SQL_EXCEPTION_RESPONSE)
221 |
222 | except Exception as e:
223 | log.warning(f"An unexpected error occurred: {e}")
224 | result["error"] = e
225 | return result
226 |
227 | def index(self, question: str = None, sql: str = None, ddl: str = None, documentation: str = None,
228 | bulk: bool = False, path: str = None) -> str:
229 | """
230 | A method to add a question and SQL pair to the vectorstore.
231 |
232 | Parameters:
233 | question (str): The question to be added to the vectorstore.
234 | sql (str): The SQL to be added to the vectorstore.
235 | ddl (str): The DDL to be added to the vectorstore.
236 | documentation (str): The documentation to be added to the vectorstore.
237 | bulk (bool): Whether to add bulk data.
238 | path (str): The path to the JSON file.
239 |
240 | Returns:
241 | str: A message confirming the successful addition of the question and SQL pair.
242 | """
243 | if bulk and path:
244 | json_data = load_json_to_dict(path)
245 | if json_data:
246 | for item in json_data:
247 | if 'Question' in item and 'SQLQuery' in item:
248 | self.vectorstore.index_question_sql(question=item.get('Question'), sql=item.get('SQLQuery'))
249 | else:
250 | raise Exception(NO_DATA_FOUND_IN_JSON_CONSTANT.format(path))
251 | log.info(BULK_DATA_SUCCESS_MESSAGE_CONSTANT)
252 |
253 | if path and not bulk:
254 | raise ValueError(BULK_FALSE_ERROR)
255 |
256 | if question and not sql:
257 | raise ValueError(SQL_NOT_PROVIDED_CONSTANT)
258 |
259 | if question and sql:
260 | log.info(ADD_QUESTION_SQL_MESSAGE_CONSTANT)
261 | return self.vectorstore.index_question_sql(question=question, sql=sql)
262 |
263 | if documentation:
264 | log.info(ADD_DOCS_MESSAGE_CONSTANT)
265 | return self.vectorstore.index_documentation(documentation)
266 |
267 | if ddl:
268 | log.info(ADD_DDL_MESSAGE_CONSTANT)
269 | return self.vectorstore.index_ddl(ddl)
270 |
271 | @staticmethod
272 | def __extract_plotly_code(markdown_string: str) -> str:
273 | """
274 | A method to extract the plotly code from the markdown string.
275 |
276 | Parameters:
277 | markdown_string (str): The markdown string.
278 |
279 | Returns:
280 | str: The extracted plotly code.
281 | """
282 | pattern = r"```[\w\s]*python\n([\s\S]*?)```|```([\s\S]*?)```"
283 |
284 | matches = re.findall(pattern, markdown_string, re.IGNORECASE)
285 | python_code = [match[0] or match[1] for match in matches]
286 |
287 | if not python_code:
288 | return markdown_string
289 |
290 | extracted_code = ''.join(python_code)
291 | sanitized_code = extracted_code.replace("fig.show()", "")
292 | return sanitized_code
293 |
294 | @staticmethod
295 | def __execute_plotly_code(plotly_code: str, data: pd.DataFrame) -> Optional[go.Figure]:
296 | """
297 | A method to execute the plotly code.
298 |
299 | Parameters:
300 | plotly_code (str): The plotly code.
301 | data (pd.DataFrame): The data.
302 |
303 | Returns:
304 | Optional[go.Figure]: The chart.
305 | """
306 | _locals = {"pd": pd, "go": go, "px": px, "df": data, "make_subplots": make_subplots}
307 | exec(plotly_code, globals(), _locals)
308 | return _locals.get("chart", None)
309 |
310 | def visualize(self, query: str, data: pd.DataFrame, visualize: bool = False) -> Optional[go.Figure]:
311 | """
312 | A method to visualize the data.
313 |
314 | Parameters:
315 | query (str): The query.
316 | data (pd.DataFrame): The data.
317 | visualize (bool): Whether to visualize the data.
318 |
319 | Returns:
320 | Optional[go.Figure]: The chart.
321 | """
322 | if visualize and not data.empty:
323 | try:
324 | if len(data.columns) == 1:
325 | log.warning("Cannot create a chart for a one-dimensional DataFrame with only one column.")
326 | return None
327 | prompt = PLOTLY_PROMPT.format(query=query, df=data)
328 | result = self.llm.invoke(prompt)
329 | plotly_code = self.__extract_plotly_code(result)
330 | fig = self.__execute_plotly_code(plotly_code, data)
331 |
332 | try:
333 | if 'IPython' in sys.modules:
334 | # Running in a Jupyter environment
335 | display = __import__("IPython.display", fromlist=["display"]).display
336 | image = __import__("IPython.display", fromlist=["Image"]).Image
337 | img_bytes = fig.to_image(format="png", scale=2)
338 | display(image(img_bytes))
339 | except Exception as e:
340 | log.warning(f"Unable to display the Plotly figure: {e}")
341 |
342 | return fig
343 | except Exception as e:
344 | log.warning(f"An unexpected error occurred while generating chart: {e}")
345 | return None
346 |
347 | def index_all_ddls(self, connection, db_name):
348 | """
349 | Indexes all Data Definition Language (DDL) statements from the specified database into the vectorstore.
350 |
351 | Parameters:
352 | - connection (object): The connection object to the database.
353 | - db_name (str): The name of the database to index.
354 | """
355 | self.database.validate_connection(connection)
356 | ddls = self.database.get_all_ddls(connection=connection, database=db_name)
357 | for ind in ddls.index:
358 | self.vectorstore.index_ddl(ddls["DDL"][ind])
359 | log.info(DDL_PROCESSED_SUCCESSFULLY)
360 |
361 |
--------------------------------------------------------------------------------
/mindsql/databases/__init__.py:
--------------------------------------------------------------------------------
1 | from .idatabase import IDatabase
2 | from .mysql import MySql
3 | from .postgres import Postgres
4 | from .sqlite import Sqlite
5 | from .sqlserver import SQLServer
6 |
--------------------------------------------------------------------------------
/mindsql/databases/idatabase.py:
--------------------------------------------------------------------------------
1 | import abc
2 | import pandas as pd
3 | from typing import List
4 |
5 |
6 | class IDatabase(metaclass=abc.ABCMeta):
7 | @classmethod
8 | def __subclasshook__(cls, subclass):
9 | return (hasattr(subclass, 'create_connection') and
10 | callable(subclass.create_connection) and
11 | hasattr(subclass, 'execute_sql') and
12 | callable(subclass.execute_sql) and
13 | hasattr(subclass, 'get_databases') and
14 | callable(subclass.get_databases) and
15 | hasattr(subclass, 'get_table_names') and
16 | callable(subclass.get_table_names) and
17 | hasattr(subclass, 'get_all_ddls') and
18 | callable(subclass.get_all_ddls) and
19 | hasattr(subclass, 'get_ddl') and
20 | callable(subclass.get_ddl) and
21 | hasattr(subclass, 'get_dialect') and
22 | callable(subclass.get_dialect) and
23 | hasattr(subclass, 'validate_connection') and
24 | callable(subclass.validate_connection) or
25 | NotImplemented)
26 |
27 | @abc.abstractmethod
28 | def create_connection(self, url: str, **kwargs) -> any:
29 | """
30 | A method to create a connection to the database.
31 |
32 | Parameters:
33 | url (str): The URL of the database.
34 | **kwargs: Additional keyword arguments.
35 |
36 | Returns:
37 | any: The connection object.
38 | """
39 | raise NotImplementedError
40 |
41 | @abc.abstractmethod
42 | def execute_sql(self, connection, sql: str) -> pd.DataFrame:
43 | """
44 | A method to execute SQL on the database.
45 |
46 | Parameters:
47 | connection (any): The connection object.
48 | sql (str): The SQL to be executed.
49 |
50 | Returns:
51 | pd.DataFrame: The result of the SQL query.
52 | """
53 | raise NotImplementedError
54 |
55 | @abc.abstractmethod
56 | def get_databases(self, connection) -> List[str]:
57 | """
58 | A method to get the list of databases in the database.
59 |
60 | Parameters:
61 | connection (any): The connection object.
62 |
63 | Returns:
64 | List[str]: The list of databases.
65 | """
66 | raise NotImplementedError
67 |
68 | @abc.abstractmethod
69 | def get_table_names(self, connection, database: str) -> pd.DataFrame:
70 | """
71 | A method to get the list of tables in the database.
72 |
73 | Parameters:
74 | connection (any): The connection object.
75 | database (str): The name of the database.
76 |
77 | Returns:
78 | pd.DataFrame: The list of tables.
79 | """
80 | raise NotImplementedError
81 |
82 | @abc.abstractmethod
83 | def get_all_ddls(self, connection: any, database: str) -> pd.DataFrame:
84 | """
85 | A method to get all DDLs in the database.
86 |
87 | Parameters:
88 | database (str): DB name
89 | connection (any): The connection object.
90 |
91 | Returns:
92 | pd.DataFrame: The list of DDLs.
93 | """
94 | raise NotImplementedError
95 |
96 | @abc.abstractmethod
97 | def validate_connection(self, connection: any) -> None:
98 | """
99 | A method to validate the connection.
100 |
101 | Parameters:
102 | connection (any): The connection object.
103 |
104 | Raises:
105 | ValueError: If the connection is None.
106 | """
107 | raise NotImplementedError
108 |
109 | @abc.abstractmethod
110 | def get_ddl(self, connection: any, table_name: str, **kwargs) -> str:
111 | """
112 | A method to get the DDL of a table in the database.
113 |
114 | Parameters:
115 | connection (any): The connection object.
116 | table_name (str): The name of the table.
117 |
118 | Returns:
119 | str: The DDL of the table.
120 | """
121 | raise NotImplementedError
122 |
123 | @abc.abstractmethod
124 | def get_dialect(self) -> str:
125 | """
126 | A method to get the dialect of the database
127 |
128 | Returns:
129 | str: The dialect of the database
130 | """
131 | raise NotImplementedError
132 |
--------------------------------------------------------------------------------
/mindsql/databases/mysql.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | from urllib.parse import urlparse
3 |
4 | import mysql.connector
5 | import pandas as pd
6 |
7 | from .._utils import logger
8 | from .._utils.constants import SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT, ERROR_CONNECTING_TO_DB_CONSTANT, \
9 | INVALID_DB_CONNECTION_OBJECT, ERROR_WHILE_RUNNING_QUERY, MYSQL_DB_TABLES_INFO_SCHEMA_QUERY, \
10 | MYSQL_SHOW_DATABASE_QUERY, MYSQL_SHOW_CREATE_TABLE_QUERY, CONNECTION_ESTABLISH_ERROR_CONSTANT
11 | from . import IDatabase
12 |
13 | log = logger.init_loggers("MySQL")
14 |
15 |
16 | class MySql(IDatabase):
17 | def create_connection(self, url: str, **kwargs) -> any:
18 | """
19 | A method to create a connection with the database.
20 |
21 | Parameters:
22 | url (str): The URL in the format mysql://username:password@host:port/database_name
23 | **kwargs: Additional keyword arguments for the connection.
24 |
25 | Returns:
26 | any: The connection object.
27 | """
28 | url = urlparse(url)
29 | try:
30 | # Establish the connection using the URL string
31 | conn = mysql.connector.connect(host=url.hostname, port=url.port, user=url.username, password=url.password,
32 | database=url.path.lstrip('/'))
33 |
34 | if conn.is_connected():
35 | log.info(SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT.format("MySQL"))
36 | return conn
37 |
38 | except mysql.connector.Error as e:
39 | log.info(ERROR_CONNECTING_TO_DB_CONSTANT.format("MySQL", e))
40 |
41 | def validate_connection(self, connection: any) -> None:
42 | """
43 | A function that validates if the provided connection is a MySQL connection.
44 |
45 | Parameters:
46 | connection: The connection object for accessing the database.
47 |
48 | Raises:
49 | ValueError: If the provided connection is not a MySQL connection.
50 |
51 | Returns:
52 | None
53 | """
54 | if connection is None:
55 | raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT)
56 |
57 | if not isinstance(connection, mysql.connector.connection_cext.CMySQLConnection):
58 | raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("MySQL"))
59 |
60 | def execute_sql(self, connection, sql: str) -> pd.DataFrame:
61 | """
62 | A method to execute SQL on the database.
63 |
64 | Parameters:
65 | connection (any): The connection object.
66 | sql (str): The SQL to be executed.
67 |
68 | Returns:
69 | pd.DataFrame: The result of the SQL query.
70 | """
71 | try:
72 | self.validate_connection(connection)
73 | cursor = connection.cursor()
74 | cursor.execute(sql)
75 | results = cursor.fetchall()
76 | column_names = [i[0] for i in cursor.description]
77 | df = pd.DataFrame(results, columns=column_names)
78 | cursor.close()
79 | return df
80 | except mysql.connector.Error as e:
81 | log.info(ERROR_WHILE_RUNNING_QUERY.format(e))
82 |
83 | def get_databases(self, connection) -> List[str]:
84 | """
85 | Get a list of databases from the given connection and SQL query.
86 |
87 | Parameters:
88 | connection (object): The connection object for the database.
89 |
90 | Returns:
91 | List[str]: A list of unique database names.
92 | """
93 | try:
94 | self.validate_connection(connection)
95 | df_databases = self.execute_sql(connection=connection, sql=MYSQL_SHOW_DATABASE_QUERY)
96 | except Exception as e:
97 | log.info(e)
98 | return []
99 |
100 | return df_databases["DATABASE_NAME"].unique().tolist()
101 |
102 | def get_table_names(self, connection, database: str) -> pd.DataFrame:
103 | """
104 | Retrieves the tables from the information schema for the specified database.
105 |
106 | Parameters:
107 | connection: The database connection object.
108 | database (str): The name of the database.
109 |
110 | Returns:
111 | DataFrame: A pandas DataFrame containing the table names from the information schema.
112 | """
113 | self.validate_connection(connection)
114 | df_tables = self.execute_sql(connection, MYSQL_DB_TABLES_INFO_SCHEMA_QUERY.format(database))
115 | return df_tables
116 |
117 | def get_all_ddls(self, connection, database: str) -> pd.DataFrame:
118 | """
119 | Get all DDLs from the specified database using the provided connection object.
120 |
121 | Parameters:
122 | connection (any): The connection object.
123 | database (str): The name of the database.
124 |
125 | Returns:
126 | pd.DataFrame: A pandas DataFrame containing the DDLs for each table in the specified database.
127 | """
128 | self.validate_connection(connection)
129 | df_tables = self.get_table_names(connection, database)
130 | df_ddl = pd.DataFrame(columns=['Table', 'DDL'])
131 | for index, row in df_tables.iterrows():
132 | table_name = row['TABLE_NAME']
133 | ddl_df = self.get_ddl(connection, table_name)
134 | df_ddl = df_ddl._append({'Table': table_name, 'DDL': ddl_df}, ignore_index=True)
135 | return df_ddl
136 |
137 | def get_ddl(self, connection: any, table_name: str, **kwargs) -> str:
138 | """
139 | A method to get the DDL for the table.
140 |
141 | Parameters:
142 | connection (any): The connection object.
143 | table_name (str): The name of the table.
144 | **kwargs: Additional keyword arguments.
145 |
146 | Returns:
147 | str: The DDL for the table.
148 | """
149 | ddl_df = self.execute_sql(connection, MYSQL_SHOW_CREATE_TABLE_QUERY.format(table_name))
150 | return ddl_df["Create Table"].iloc[0]
151 |
152 | def get_dialect(self) -> str:
153 | """
154 | A method to get the dialect of the database.
155 |
156 | Returns:
157 | str: The dialect of the database.
158 | """
159 | return 'mysql'
160 |
--------------------------------------------------------------------------------
/mindsql/databases/postgres.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | from urllib.parse import urlparse
3 |
4 | import pandas as pd
5 | import psycopg2
6 | from psycopg2 import extensions
7 |
8 | from . import IDatabase
9 | from .._utils import logger
10 | from .._utils.constants import ERROR_CONNECTING_TO_DB_CONSTANT, INVALID_DB_CONNECTION_OBJECT, ERROR_WHILE_RUNNING_QUERY, \
11 | POSTGRESQL_SHOW_DATABASE_QUERY, POSTGRESQL_DB_TABLES_INFO_SCHEMA_QUERY, \
12 | POSTGRESQL_SHOW_CREATE_TABLE_QUERY, CONNECTION_ESTABLISH_ERROR_CONSTANT
13 |
14 | log = logger.init_loggers("Postgres")
15 |
16 |
17 | class Postgres(IDatabase):
18 | @staticmethod
19 | def create_connection(url: str, **kwargs) -> any:
20 | """
21 | Connects to a PostgreSQL database using the provided URL.
22 |
23 | Parameters:
24 | - url (str): The URL in the format postgresql://username:password@host:port/database_name
25 | - **kwargs: Additional keyword arguments for the connection
26 |
27 | Returns:
28 | - connection: A connection to the PostgreSQL database
29 |
30 | Exceptions:
31 | - psycopg2.OperationalError: If an error occurs while connecting to the PostgreSQL database
32 | """
33 | try:
34 | parsed_url = urlparse(url)
35 | connection = psycopg2.connect(user=parsed_url.username, password=parsed_url.password,
36 | host=parsed_url.hostname, port=parsed_url.port,
37 | database=parsed_url.path.lstrip('/'))
38 | return connection
39 | except psycopg2.OperationalError as e:
40 | log.info(ERROR_CONNECTING_TO_DB_CONSTANT.format("PostgreSQL", e))
41 |
42 | def validate_connection(self, connection: any) -> None:
43 | """
44 | A function that validates if the provided connection is a PostgreSQL connection.
45 |
46 | Parameters:
47 | connection: The connection object for accessing the database.
48 |
49 | Raises:
50 | ValueError: If the provided connection is not a PostgreSQL connection.
51 | """
52 | if connection is None:
53 | raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT)
54 | if not isinstance(connection, psycopg2.extensions.connection):
55 | raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("PostgreSQL"))
56 |
57 | def execute_sql(self, connection, sql: str) -> pd.DataFrame:
58 | """
59 | A function that runs an SQL query using the provided connection and returns the results as a pandas DataFrame.
60 |
61 | Parameters:
62 | connection: The connection object for accessing the database.
63 | sql (str): The SQL query to be executed.
64 |
65 | Returns:
66 | pd.DataFrame: A DataFrame containing the results of the SQL query.
67 | """
68 | try:
69 | self.validate_connection(connection)
70 | cursor = connection.cursor()
71 | cursor.execute(sql)
72 | results = cursor.fetchall()
73 | column_names = [desc[0] for desc in cursor.description]
74 | df = pd.DataFrame(results, columns=column_names)
75 | cursor.close()
76 | return df
77 | except psycopg2.Error as e:
78 | log.info(ERROR_WHILE_RUNNING_QUERY.format(e))
79 |
80 | def get_databases(self, connection) -> List[str]:
81 | """
82 | Get a list of databases from the given connection and SQL query.
83 |
84 | Parameters:
85 | connection: The connection object for the database.
86 |
87 | Returns:
88 | List[str]: A list of unique database names.
89 | """
90 | try:
91 | self.validate_connection(connection)
92 | df_databases = self.execute_sql(connection=connection, sql=POSTGRESQL_SHOW_DATABASE_QUERY)
93 | except Exception as e:
94 | log.info(e)
95 | return []
96 |
97 | return df_databases["DATABASE_NAME"].unique().tolist()
98 |
99 | def get_table_names(self, connection, database: str) -> pd.DataFrame:
100 | """
101 | Retrieves the tables from the information schema for the specified database.
102 |
103 | Parameters:
104 | connection: The database connection object.
105 | database (str): The name of the database.
106 |
107 | Returns:
108 | DataFrame: A pandas DataFrame containing the table names from the information schema.
109 | """
110 | self.validate_connection(connection)
111 | query = POSTGRESQL_DB_TABLES_INFO_SCHEMA_QUERY.format(db=database)
112 | df_tables = self.execute_sql(connection, query)
113 | return df_tables
114 |
115 | def get_all_ddls(self, connection, database: str) -> pd.DataFrame:
116 | """
117 | A method to get the DDLs for all the tables in the database.
118 |
119 | Parameters:
120 | connection (any): The connection object.
121 | database (str): The name of the database.
122 |
123 | Returns:
124 | DataFrame: A pandas DataFrame containing the DDLs for all the tables in the database.
125 | """
126 | self.validate_connection(connection)
127 | df_tables = self.get_table_names(connection, database)
128 | df_ddl = pd.DataFrame(columns=['Table', 'DDL'])
129 | for index, row in df_tables.iterrows():
130 | table_name = row.get('table_name')
131 | ddl_df = self.get_ddl(connection, table_name)
132 | df_ddl = df_ddl._append({'Table': table_name, 'DDL': ddl_df}, ignore_index=True)
133 | return df_ddl
134 |
135 | def get_ddl(self, connection, table_name: str, **kwargs) -> str:
136 | """
137 | A method to get the DDL for the table.
138 |
139 | Parameters:
140 | connection (any): The connection object.
141 | table_name (str): The name of the table.
142 |
143 | Returns:
144 | str: The DDL for the table.
145 | """
146 | self.validate_connection(connection)
147 | ddl_df = self.execute_sql(connection, POSTGRESQL_SHOW_CREATE_TABLE_QUERY.format(table=table_name))
148 | return ddl_df.get('create_statement').iloc[0]
149 |
150 | def get_dialect(self) -> str:
151 | return 'postgres'
152 |
--------------------------------------------------------------------------------
/mindsql/databases/sqlite.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sqlite3
3 | import warnings
4 | from sqlite3 import Connection
5 | from typing import List
6 | from urllib.parse import urlparse
7 |
8 | import pandas as pd
9 | import requests
10 |
11 | from .._utils import logger
12 | from .._utils.constants import ERROR_DOWNLOADING_SQLITE_DB_CONSTANT, ERROR_CONNECTING_TO_DB_CONSTANT, \
13 | INVALID_DB_CONNECTION_OBJECT, ERROR_WHILE_RUNNING_QUERY, SQLLITE_GET_DB_QUERY, SQLLIE_TABLE_INFO_SCHEMA_CONSTANT, \
14 | SQLLITE_TRAINING_DATASET_QUERY_CONSTANT, CONNECTION_ESTABLISH_ERROR_CONSTANT
15 | from . import IDatabase
16 |
17 | warnings.simplefilter(action='ignore', category=UserWarning)
18 | log = logger.init_loggers("Sqlite")
19 |
20 |
21 | class Sqlite(IDatabase):
22 | @staticmethod
23 | def __download_database(url: str, destination_path: str) -> None:
24 | """
25 | Download the database if it doesn't exist
26 |
27 | Parameters:
28 | url (str): The URL of the database
29 | destination_path (str): The path to save the database
30 |
31 | Returns:
32 | None
33 | """
34 | try:
35 | response = requests.get(url)
36 | response.raise_for_status() # Check that the request was successful
37 | with open(destination_path, "wb") as f:
38 | f.write(response.content)
39 | except requests.RequestException as e:
40 | log.info(ERROR_DOWNLOADING_SQLITE_DB_CONSTANT.format(e))
41 |
42 | def create_connection(self, url: str, **kwargs) -> Connection | None:
43 | """
44 | A method to create a connection with the database.
45 |
46 | Parameters:
47 | url (str): The URL of the database
48 |
49 | Returns:
50 | Connection | None: A connection object
51 | """
52 | if urlparse(url).scheme == '' and os.path.isabs(url):
53 | path = url
54 | else:
55 | path = os.path.basename(urlparse(url).path)
56 |
57 | # Download the database if it doesn't exist
58 | if not os.path.exists(path):
59 | self.__download_database(url, path)
60 |
61 | try:
62 | conn = sqlite3.connect(path)
63 | return conn
64 | except sqlite3.Error as e:
65 | log.info(ERROR_CONNECTING_TO_DB_CONSTANT.format("SQLite", e))
66 | return None
67 |
68 | def validate_connection(self, connection):
69 | """
70 | A function that validates if the provided connection is a SQLite connection.
71 |
72 | Parameters:
73 | connection (Connection): A connection object
74 |
75 | Returns:
76 | None
77 | """
78 | if connection is None:
79 | raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT)
80 |
81 | if not isinstance(connection, sqlite3.Connection):
82 | raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("SQLite"))
83 |
84 | def execute_sql(self, connection, sql: str) -> pd.DataFrame:
85 | """
86 | A method to run a SQL query on the database.
87 |
88 | Parameters:
89 | connection (Connection): A connection object
90 | sql (str): The SQL query to run
91 |
92 | Returns:
93 | pd.DataFrame: A DataFrame containing the query results
94 | """
95 | self.validate_connection(connection)
96 | try:
97 | result = pd.read_sql_query(sql, connection)
98 | return result
99 | except sqlite3.Error as e:
100 | log.info(ERROR_WHILE_RUNNING_QUERY.format(e))
101 | return pd.DataFrame()
102 |
103 | def get_databases(self, connection) -> List[str]:
104 | """
105 | Get a list of databases from the given connection and SQL query.
106 |
107 | Parameters:
108 | connection (Connection): A connection object
109 |
110 | Returns:
111 | List[str]: A list of unique database names
112 | """
113 | self.validate_connection(connection)
114 | try:
115 | df_databases = pd.read_sql_query(SQLLITE_GET_DB_QUERY, connection)
116 | return df_databases["name"].tolist()
117 | except Exception as e:
118 | log.info(e)
119 | return []
120 |
121 | def get_table_names(self, connection, database: str) -> pd.DataFrame:
122 | """
123 | A method to get the list of tables in the database.
124 |
125 | Parameters:
126 | connection (Connection): A connection object
127 | database (str): The name of the database
128 |
129 | Returns:
130 | pd.DataFrame: The list of tables
131 | """
132 | self.validate_connection(connection)
133 | try:
134 | result = pd.read_sql_query(SQLLIE_TABLE_INFO_SCHEMA_CONSTANT, connection)
135 | return result
136 | except sqlite3.Error as e:
137 | log.info(ERROR_WHILE_RUNNING_QUERY.format(e))
138 | return pd.DataFrame()
139 |
140 | def get_all_ddls(self, connection, database: str) -> pd.DataFrame:
141 | """
142 | A method to get all DDLs in the database.
143 |
144 | Parameters:
145 | connection (Connection): A connection object
146 | database (str): The name of the database
147 |
148 | Returns:
149 | pd.DataFrame: The list of DDLs
150 | """
151 | self.validate_connection(connection)
152 |
153 | df_tables = self.get_table_names(connection, database)
154 | df_ddl = pd.DataFrame(columns=['Table', 'DDL'])
155 |
156 | for _, row in df_tables.iterrows():
157 | table_name = row['name']
158 | ddl_df = self.get_ddl(connection, table_name)
159 | df_ddl = df_ddl._append({'Table': table_name, 'DDL': ddl_df}, ignore_index=True)
160 | return df_ddl
161 |
162 | def get_ddl(self, connection, table_name: str, **kwargs) -> str:
163 | """
164 | A method to get the DDL for the table.
165 |
166 | Parameters:
167 | connection (Connection): A connection object
168 | table_name (str): The name of the table
169 |
170 | Returns:
171 | str: The DDL for the table
172 | """
173 | self.validate_connection(connection)
174 | ddl_df = pd.read_sql_query(SQLLITE_TRAINING_DATASET_QUERY_CONSTANT.format(table_name), connection)
175 | return ddl_df["sql"].iloc[0]
176 |
177 | def get_dialect(self) -> str:
178 | """
179 | A method to get the dialect of the database.
180 |
181 | Returns:
182 | str: The dialect
183 | """
184 | return 'sqlite3'
185 |
--------------------------------------------------------------------------------
/mindsql/databases/sqlserver.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional
2 | from urllib.parse import urlparse
3 |
4 | import pandas as pd
5 | import pyodbc
6 |
7 | from . import IDatabase
8 | from .._utils import logger
9 | from .._utils.constants import ERROR_WHILE_RUNNING_QUERY, ERROR_CONNECTING_TO_DB_CONSTANT, INVALID_DB_CONNECTION_OBJECT, \
10 | CONNECTION_ESTABLISH_ERROR_CONSTANT, SQLSERVER_SHOW_DATABASE_QUERY, SQLSERVER_DB_TABLES_INFO_SCHEMA_QUERY, \
11 | SQLSERVER_SHOW_CREATE_TABLE_QUERY
12 |
13 | log = logger.init_loggers("SQL Server")
14 |
15 |
16 | class SQLServer(IDatabase):
17 | @staticmethod
18 | def create_connection(url: str, **kwargs) -> any:
19 | """
20 | Connects to a SQL Server database using the provided URL.
21 |
22 | Parameters:
23 | - url (str): The connection string to the SQL Server database in the format:
24 | 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=server_name;DATABASE=database_name;UID=user;PWD=password'
25 | - **kwargs: Additional keyword arguments for the connection
26 |
27 | Returns:
28 | - connection: A connection to the SQL Server database
29 | """
30 |
31 | try:
32 | connection = pyodbc.connect(url, **kwargs)
33 | return connection
34 | except pyodbc.Error as e:
35 | log.error(ERROR_CONNECTING_TO_DB_CONSTANT.format("SQL Server", e))
36 |
37 | def execute_sql(self, connection, sql:str) -> Optional[pd.DataFrame]:
38 | """
39 | A function that runs an SQL query using the provided connection and returns the results as a pandas DataFrame.
40 |
41 | Parameters:
42 | connection: The connection object for the database.
43 | sql (str): The SQL query to be executed
44 |
45 | Returns:
46 | pd.DataFrame: A DataFrame containing the results of the SQL query.
47 | """
48 | try:
49 | self.validate_connection(connection)
50 | cursor = connection.cursor()
51 | cursor.execute(sql)
52 | columns = [column[0] for column in cursor.description]
53 | data = cursor.fetchall()
54 | data = [list(row) for row in data]
55 | cursor.close()
56 | return pd.DataFrame(data, columns=columns)
57 | except pyodbc.Error as e:
58 | log.error(ERROR_WHILE_RUNNING_QUERY.format(e))
59 | return None
60 |
61 | def get_databases(self, connection) -> List[str]:
62 | """
63 | Get a list of databases from the given connection and SQL query.
64 |
65 | Parameters:
66 | connection: The connection object for the database.
67 |
68 | Returns:
69 | List[str]: A list of unique database names.
70 | """
71 | try:
72 | self.validate_connection(connection)
73 | cursor = connection.cursor()
74 | cursor.execute(SQLSERVER_SHOW_DATABASE_QUERY)
75 | databases = [row[0] for row in cursor.fetchall()]
76 | cursor.close()
77 | return databases
78 | except pyodbc.Error as e:
79 | log.error(ERROR_WHILE_RUNNING_QUERY.format(e))
80 | return []
81 |
82 | def get_table_names(self, connection, database: str) -> pd.DataFrame:
83 | """
84 | Retrieves the tables along with their schema (schema.table_name) from the information schema for the specified
85 | database.
86 |
87 | Parameters:
88 | connection: The database connection object.
89 | database (str): The name of the database.
90 |
91 | Returns:
92 | DataFrame: A pandas DataFrame containing the table names from the information schema.
93 | """
94 | self.validate_connection(connection)
95 | query = SQLSERVER_DB_TABLES_INFO_SCHEMA_QUERY.format(db=database)
96 | return self.execute_sql(connection, query)
97 |
98 |
99 |
100 |
101 | def get_all_ddls(self, connection: any, database: str) -> pd.DataFrame:
102 | """
103 | A method to get the DDLs for all the tables in the database.
104 |
105 | Parameters:
106 | connection (any): The connection object.
107 | database (str): The name of the database.
108 |
109 | Returns:
110 | DataFrame: A pandas DataFrame containing the DDLs for all the tables in the database.
111 | """
112 | df_tables = self.get_table_names(connection, database)
113 | ddl_df = pd.DataFrame(columns=['Table', 'DDL'])
114 | for index, row in df_tables.iterrows():
115 | ddl = self.get_ddl(connection, row.iloc[0])
116 | ddl_df = ddl_df._append({'Table': row.iloc[0], 'DDL': ddl}, ignore_index=True)
117 |
118 | return ddl_df
119 |
120 |
121 |
122 | def validate_connection(self, connection: any) -> None:
123 | """
124 | A function that validates if the provided connection is a SQL Server connection.
125 |
126 | Parameters:
127 | connection: The connection object for accessing the database.
128 |
129 | Raises:
130 | ValueError: If the provided connection is not a SQL Server connection.
131 |
132 | Returns:
133 | None
134 | """
135 | if connection is None:
136 | raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT)
137 | if not isinstance(connection, pyodbc.Connection):
138 | raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("SQL Server"))
139 |
140 | def get_ddl(self, connection: any, table_name: str, **kwargs) -> str:
141 | schema_name, table_name = table_name.split('.')
142 | query = SQLSERVER_SHOW_CREATE_TABLE_QUERY.format(table=table_name, schema=schema_name)
143 | df_ddl = self.execute_sql(connection, query)
144 | return df_ddl['SQLQuery'][0]
145 |
146 | def get_dialect(self) -> str:
147 | return 'tsql'
148 |
--------------------------------------------------------------------------------
/mindsql/llms/__init__.py:
--------------------------------------------------------------------------------
1 | from .illm import ILlm
2 | from .anthropic import AnthropicAi
3 | from .googlegenai import GoogleGenAi
4 | from .huggingface import HuggingFace
5 | from .llama import LlamaCpp
6 | from .open_ai import OpenAi
7 |
--------------------------------------------------------------------------------
/mindsql/llms/anthropic.py:
--------------------------------------------------------------------------------
1 | from anthropic import Anthropic
2 |
3 | from .illm import ILlm
4 | from .._utils.constants import ANTHROPIC_VALUE_ERROR, PROMPT_EMPTY_EXCEPTION
5 |
6 |
7 | class AnthropicAi(ILlm):
8 | def __init__(self, config=None, client=None):
9 | """
10 | Initialize the class with an optional config parameter.
11 |
12 | Parameters:
13 | config (any): The configuration parameter.
14 | client (any): The client parameter.
15 |
16 | Returns:
17 | None
18 | """
19 | self.config = config
20 | self.client = client
21 |
22 | if client is not None:
23 | self.client = client
24 | return
25 |
26 | if 'api_key' not in config:
27 | raise ValueError(ANTHROPIC_VALUE_ERROR)
28 | api_key = config.pop('api_key')
29 | self.client = Anthropic(api_key=api_key, **config)
30 |
31 | def system_message(self, message: str) -> any:
32 | """
33 | Create a system message.
34 |
35 | Parameters:
36 | message (str): The message parameter.
37 |
38 | Returns:
39 | any
40 | """
41 | return {"role": "system", "content": message}
42 |
43 | def user_message(self, message: str) -> any:
44 | """
45 | Create a user message.
46 |
47 | Parameters:
48 | message (str): The message parameter.
49 |
50 | Returns:
51 | any
52 | """
53 | return {"role": "user", "content": message}
54 |
55 | def assistant_message(self, message: str) -> any:
56 | """
57 | Create an assistant message.
58 |
59 | Parameters:
60 | message (str): The message parameter.
61 |
62 | Returns:
63 | any
64 | """
65 | return {"role": "assistant", "content": message}
66 |
67 | def invoke(self, prompt, **kwargs) -> str:
68 | """
69 | Submit a prompt to the model for generating a response.
70 |
71 | Parameters:
72 | prompt (str): The prompt parameter.
73 | **kwargs: Additional keyword arguments (optional).
74 | - temperature (float): The temperature parameter for controlling randomness in generation.
75 | - max_tokens (int): Maximum number of tokens to be generated.
76 | Returns:
77 | str: The generated response from the model.
78 | """
79 | if prompt is None or len(prompt) == 0:
80 | raise Exception(PROMPT_EMPTY_EXCEPTION)
81 |
82 | model = self.config.get("model", "claude-3-opus-20240229")
83 | temperature = kwargs.get("temperature", 0.1)
84 | max_tokens = kwargs.get("max_tokens", 1024)
85 | response = self.client.messages.create(model=model, messages=[{"role": "user", "content": prompt}],
86 | max_tokens=max_tokens, temperature=temperature)
87 | for content in response.content:
88 | if isinstance(content, dict) and content.get("type") == "text":
89 | return content["text"]
90 | elif hasattr(content, "text"):
91 | return content.text
92 |
--------------------------------------------------------------------------------
/mindsql/llms/googlegenai.py:
--------------------------------------------------------------------------------
1 | import google.generativeai as genai
2 |
3 | from .._utils.constants import GOOGLE_GEN_AI_VALUE_ERROR, GOOGLE_GEN_AI_APIKEY_ERROR
4 | from .illm import ILlm
5 |
6 |
7 | class GoogleGenAi(ILlm):
8 | def __init__(self, config=None):
9 | """
10 | Initialize the class with an optional config parameter.
11 |
12 | Parameters:
13 | config (any): The configuration parameter.
14 |
15 | Returns:
16 | None
17 | """
18 | if config is None:
19 | raise ValueError(GOOGLE_GEN_AI_VALUE_ERROR)
20 |
21 | if 'api_key' not in config:
22 | raise ValueError(GOOGLE_GEN_AI_APIKEY_ERROR)
23 | api_key = config.pop('api_key')
24 | genai.configure(api_key=api_key)
25 | self.model = genai.GenerativeModel('gemini-pro', **config)
26 |
27 | def system_message(self, message: str) -> any:
28 | """
29 | Create a system message.
30 |
31 | Parameters:
32 | message (str): The content of the system message.
33 |
34 | Returns:
35 | any: A formatted system message.
36 | """
37 | return {"role": "system", "parts": message}
38 |
39 | def user_message(self, message: str) -> any:
40 | """
41 | Create a user message.
42 |
43 | Parameters:
44 | message (str): The content of the user message.
45 |
46 | Returns:
47 | any: A formatted user message.
48 | """
49 | return {"role": "user", "parts": message}
50 |
51 | def assistant_message(self, message: str) -> any:
52 | """
53 | Create an assistant message.
54 |
55 | Parameters:
56 | message (str): The content of the assistant message.
57 |
58 | Returns:
59 | any: A formatted assistant message.
60 | """
61 | return {'role': 'model', 'parts': message}
62 |
63 | def invoke(self, prompt, **kwargs) -> str:
64 | """
65 | Submit a prompt to the model for generating a response.
66 |
67 | Parameters:
68 | prompt (str): The prompt parameter.
69 | **kwargs: Additional keyword arguments (optional).
70 | - temperature (float): The temperature parameter for controlling randomness in generation.
71 |
72 | Returns:
73 | str: The generated response from the model.
74 | """
75 | if prompt is None or len(prompt) == 0:
76 | raise Exception("Prompt cannot be empty.")
77 |
78 | temperature = kwargs.get("temperature", 0.1)
79 | response = self.model.generate_content(prompt,
80 | generation_config=genai.GenerationConfig(temperature=temperature))
81 | return response.text
82 |
--------------------------------------------------------------------------------
/mindsql/llms/huggingface.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from transformers import AutoModelForCausalLM, LlamaTokenizerFast
3 |
4 | from .illm import ILlm
5 | from .._utils.constants import LLAMA_VALUE_ERROR, LLAMA_PROMPT_EXCEPTION, CONFIG_REQUIRED_ERROR
6 |
7 |
8 | class HuggingFace(ILlm):
9 | def __init__(self, config=None):
10 | """
11 | Initialize the class with an optional config parameter.
12 |
13 | Parameters:
14 | config (any): The configuration parameter.
15 |
16 | Returns:
17 | None
18 | """
19 | if config is None:
20 | raise ValueError(CONFIG_REQUIRED_ERROR)
21 |
22 | if 'model_name' not in config:
23 | raise ValueError(LLAMA_VALUE_ERROR)
24 | model_name = config.pop('model_name') or 'gpt2'
25 |
26 | self.tokenizer = LlamaTokenizerFast.from_pretrained(model_name)
27 | self.model = AutoModelForCausalLM.from_pretrained(model_name, **config)
28 |
29 | def system_message(self, message: str) -> any:
30 | """
31 | Create a system message.
32 |
33 | Parameters:
34 | message (str): The content of the system message.
35 |
36 | Returns:
37 | any: A formatted system message.
38 |
39 | Example:
40 | system_msg = system_message("System update: Server maintenance scheduled.")
41 | """
42 | return {"role": "system", "content": message}
43 |
44 | def user_message(self, message: str) -> any:
45 | """
46 | Create a user message.
47 |
48 | Parameters:
49 | message (str): The content of the user message.
50 |
51 | Returns:
52 | any: A formatted user message.
53 | """
54 | return {"role": "user", "content": message}
55 |
56 | def assistant_message(self, message: str) -> any:
57 | """
58 | Create an assistant message.
59 |
60 | Parameters:
61 | message (str): The content of the assistant message.
62 |
63 | Returns:
64 | any: A formatted assistant message.
65 | """
66 | return {"role": "assistant", "content": message}
67 |
68 | def invoke(self, prompt, **kwargs) -> str:
69 | """
70 | Submit a prompt to the model for generating a response.
71 |
72 | Parameters:
73 | prompt (str): The prompt parameter.
74 | **kwargs: Additional keyword arguments (optional).
75 | - temperature (float): The temperature parameter for controlling randomness in generation.
76 |
77 | Returns:
78 | str: The generated response from the model.
79 | """
80 | if prompt is None or len(prompt) == 0:
81 | raise Exception(LLAMA_PROMPT_EXCEPTION)
82 |
83 | inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2000)
84 | temperature = kwargs.get("temperature", 0.1)
85 |
86 | with torch.no_grad():
87 | output = self.model.generate(input_ids=inputs.input_ids, attention_mask=inputs.attention_mask,
88 | max_length=2000, temperature=temperature,
89 | pad_token_id=self.tokenizer.pad_token_id,
90 | eos_token_id=self.tokenizer.eos_token_id,
91 | bos_token_id=self.tokenizer.bos_token_id, **kwargs)
92 |
93 | data = self.tokenizer.decode(output[0], skip_special_tokens=True)
94 | return data
95 |
--------------------------------------------------------------------------------
/mindsql/llms/illm.py:
--------------------------------------------------------------------------------
1 | import abc
2 |
3 |
4 | class ILlm(metaclass=abc.ABCMeta):
5 | def __subclasshook__(cls, subclass):
6 | return (hasattr(subclass, 'system_message') and
7 | callable(subclass.system_message) and
8 | hasattr(subclass, 'user_message') and
9 | callable(subclass.user_message) and
10 | hasattr(subclass, 'assistant_message') and
11 | callable(subclass.assistant_message) and
12 | hasattr(subclass, 'invoke') and
13 | callable(subclass.invoke) or
14 | NotImplemented)
15 |
16 | @abc.abstractmethod
17 | def system_message(self, message: str) -> any:
18 | """
19 | A method to handle system messages.
20 |
21 | Parameters:
22 | message (str): The message received from the system.
23 |
24 | Returns:
25 | any: The return type of the function.
26 | """
27 | raise NotImplementedError
28 |
29 | @abc.abstractmethod
30 | def user_message(self, message: str) -> any:
31 | """
32 | A method to handle user messages.
33 |
34 | Parameters:
35 | message (str): The message received from the user.
36 |
37 | Returns:
38 | any: The return type of the function.
39 | """
40 | raise NotImplementedError
41 |
42 | @abc.abstractmethod
43 | def assistant_message(self, message: str) -> any:
44 | """
45 | A method to handle assistant messages.
46 |
47 | Parameters:
48 | message (str): The message received from the assistant.
49 |
50 | Returns:
51 | any: The return type of the function.
52 | """
53 | raise NotImplementedError
54 |
55 | @abc.abstractmethod
56 | def invoke(self, prompt, **kwargs) -> str:
57 | """
58 | A method to invoke the LLM.
59 |
60 | Parameters:
61 | prompt (str): The prompt to be sent to the LLM.
62 | **kwargs: Additional keyword arguments.
63 |
64 | Returns:
65 | str: The response from the LLM.
66 | """
67 | raise NotImplementedError
68 |
--------------------------------------------------------------------------------
/mindsql/llms/llama.py:
--------------------------------------------------------------------------------
1 | from llama_cpp import Llama
2 |
3 | from .._utils.constants import LLAMA_VALUE_ERROR, LLAMA_PROMPT_EXCEPTION, CONFIG_REQUIRED_ERROR
4 | from .illm import ILlm
5 |
6 |
7 | class LlamaCpp(ILlm):
8 | def __init__(self, config=None):
9 | """
10 | Initialize the class with an optional config parameter.
11 |
12 | Parameters:
13 | config (any): The configuration parameter.
14 |
15 | Returns:
16 | None
17 | """
18 | if config is None:
19 | raise ValueError(CONFIG_REQUIRED_ERROR)
20 |
21 | if 'model_path' not in config:
22 | raise ValueError(LLAMA_VALUE_ERROR)
23 | path = config.pop('model_path')
24 |
25 | self.model = Llama(model_path=path, **config)
26 |
27 | def system_message(self, message: str) -> any:
28 | """
29 | Create a system message.
30 |
31 | Parameters:
32 | message (str): The content of the system message.
33 |
34 | Returns:
35 | any: A formatted system message.
36 |
37 | Example:
38 | system_msg = system_message("System update: Server maintenance scheduled.")
39 | """
40 | return {"role": "system", "content": message}
41 |
42 | def user_message(self, message: str) -> any:
43 | """
44 | Create a user message.
45 |
46 | Parameters:
47 | message (str): The content of the user message.
48 |
49 | Returns:
50 | any: A formatted user message.
51 | """
52 | return {"role": "user", "content": message}
53 |
54 | def assistant_message(self, message: str) -> any:
55 | """
56 | Create an assistant message.
57 |
58 | Parameters:
59 | message (str): The content of the assistant message.
60 |
61 | Returns:
62 | any: A formatted assistant message.
63 | """
64 | return {"role": "assistant", "content": message}
65 |
66 | def invoke(self, prompt, **kwargs) -> str:
67 | """
68 | Submit a prompt to the model for generating a response.
69 |
70 | Parameters:
71 | prompt (str): The prompt parameter.
72 | **kwargs: Additional keyword arguments (optional).
73 | - temperature (float): The temperature parameter for controlling randomness in generation.
74 |
75 | Returns:
76 | str: The generated response from the model.
77 | """
78 | if prompt is None or len(prompt) == 0:
79 | raise Exception(LLAMA_PROMPT_EXCEPTION)
80 |
81 | temperature = kwargs.get("temperature", 0.1)
82 | return self.model(prompt=prompt, temperature=temperature, echo=False)["choices"][0]["text"]
83 |
--------------------------------------------------------------------------------
/mindsql/llms/ollama.py:
--------------------------------------------------------------------------------
1 | from ollama import Client, Options
2 |
3 | from .illm import ILlm
4 | from .._utils.constants import PROMPT_EMPTY_EXCEPTION, OLLAMA_CONFIG_REQUIRED
5 | from .._utils import logger
6 |
7 | log = logger.init_loggers("Ollama Client")
8 |
9 |
10 | class Ollama(ILlm):
11 | def __init__(self, model_config: dict, client_config=None, client: Client = None):
12 | """
13 | Initialize the class with an optional config parameter.
14 |
15 | Parameters:
16 | model_config (dict): The model configuration parameter.
17 | config (dict): The configuration parameter.
18 | client (Client): The client parameter.
19 |
20 | Returns:
21 | None
22 | """
23 | self.client = client
24 | self.client_config = client_config
25 | self.model_config = model_config
26 |
27 | if self.client is not None:
28 | if self.client_config is not None:
29 | log.warning("Client object provided. Ignoring client_config parameter.")
30 | return
31 |
32 | if client_config is None:
33 | raise ValueError(OLLAMA_CONFIG_REQUIRED.format(type="Client"))
34 |
35 | if model_config is None:
36 | raise ValueError(OLLAMA_CONFIG_REQUIRED.format(type="Model"))
37 |
38 | if 'model' not in model_config:
39 | raise ValueError(OLLAMA_CONFIG_REQUIRED.format(type="Model name"))
40 |
41 | self.client = Client(**client_config)
42 |
43 | def system_message(self, message: str) -> any:
44 | """
45 | Create a system message.
46 |
47 | Parameters:
48 | message (str): The message parameter.
49 |
50 | Returns:
51 | any
52 | """
53 | return {"role": "system", "content": message}
54 |
55 | def user_message(self, message: str) -> any:
56 | """
57 | Create a user message.
58 |
59 | Parameters:
60 | message (str): The message parameter.
61 |
62 | Returns:
63 | any
64 | """
65 | return {"role": "user", "content": message}
66 |
67 | def assistant_message(self, message: str) -> any:
68 | """
69 | Create an assistant message.
70 |
71 | Parameters:
72 | message (str): The message parameter.
73 |
74 | Returns:
75 | any
76 | """
77 | return {"role": "assistant", "content": message}
78 |
79 | def invoke(self, prompt, **kwargs) -> str:
80 | """
81 | Submit a prompt to the model for generating a response.
82 |
83 | Parameters:
84 | prompt (str): The prompt parameter.
85 | **kwargs: Additional keyword arguments (optional).
86 | - temperature (float): The temperature parameter for controlling randomness in generation.
87 |
88 | Returns:
89 | str
90 | """
91 | if not prompt:
92 | raise ValueError(PROMPT_EMPTY_EXCEPTION)
93 |
94 | model = self.model_config.get('model')
95 | temperature = kwargs.get('temperature', 0.1)
96 |
97 | response = self.client.chat(
98 | model=model,
99 | messages=[self.user_message(prompt)],
100 | options=Options(
101 | temperature=temperature
102 | )
103 | )
104 |
105 | return response['message']['content']
106 |
--------------------------------------------------------------------------------
/mindsql/llms/open_ai.py:
--------------------------------------------------------------------------------
1 | from openai import OpenAI
2 |
3 | from .illm import ILlm
4 | from .._utils.constants import OPENAI_VALUE_ERROR, PROMPT_EMPTY_EXCEPTION
5 |
6 |
7 | class OpenAi(ILlm):
8 | def __init__(self, config=None, client=None):
9 | """
10 | Initialize the class with an optional config parameter.
11 |
12 | Parameters:
13 | config (any): The configuration parameter.
14 | client (any): The client parameter.
15 |
16 | Returns:
17 | None
18 | """
19 | self.config = config
20 | self.client = client
21 |
22 | if client is not None:
23 | self.client = client
24 | return
25 |
26 | if 'api_key' not in config:
27 | raise ValueError(OPENAI_VALUE_ERROR)
28 | api_key = config.pop('api_key')
29 | self.client = OpenAI(api_key=api_key, **config)
30 |
31 | def system_message(self, message: str) -> any:
32 | """
33 | Create a system message.
34 |
35 | Parameters:
36 | message (str): The message parameter.
37 |
38 | Returns:
39 | any
40 | """
41 | return {"role": "system", "content": message}
42 |
43 | def user_message(self, message: str) -> any:
44 | """
45 | Create a user message.
46 |
47 | Parameters:
48 | message (str): The message parameter.
49 |
50 | Returns:
51 | any
52 | """
53 | return {"role": "user", "content": message}
54 |
55 | def assistant_message(self, message: str) -> any:
56 | """
57 | Create an assistant message.
58 |
59 | Parameters:
60 | message (str): The message parameter.
61 |
62 | Returns:
63 | any
64 | """
65 | return {"role": "assistant", "content": message}
66 |
67 | def invoke(self, prompt, **kwargs) -> str:
68 | """
69 | Submit a prompt to the model for generating a response.
70 |
71 | Parameters:
72 | prompt (str): The prompt parameter.
73 | **kwargs: Additional keyword arguments (optional).
74 | - temperature (float): The temperature parameter for controlling randomness in generation.
75 |
76 | Returns:
77 | str: The generated response from the model.
78 | """
79 | if prompt is None or len(prompt) == 0:
80 | raise Exception(PROMPT_EMPTY_EXCEPTION)
81 |
82 | model = self.config.get("model", "gpt-3.5-turbo")
83 | temperature = kwargs.get("temperature", 0.1)
84 | max_tokens = kwargs.get("max_tokens", 500)
85 | response = self.client.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}],
86 | max_tokens=max_tokens, stop=None, temperature=temperature)
87 | return response.choices[0].message.content
88 |
--------------------------------------------------------------------------------
/mindsql/vectorstores/__init__.py:
--------------------------------------------------------------------------------
1 | from .ivectorstore import IVectorstore
2 | from .chromadb import ChromaDB
3 | from .faiss_db import Faiss
4 |
--------------------------------------------------------------------------------
/mindsql/vectorstores/chromadb.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import uuid
4 | from typing import List
5 |
6 | import chromadb
7 | import pandas as pd
8 | from chromadb.config import Settings
9 | from chromadb.utils import embedding_functions
10 |
11 | from . import IVectorstore
12 |
13 | sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="WhereIsAI/UAE-Large-V1")
14 |
15 |
16 | class ChromaDB(IVectorstore):
17 | def __init__(self, config=None):
18 | if config is not None:
19 | directory = config.get("path", ".")
20 | self.embedding_function = config.get("embedding_function", sentence_transformer_ef)
21 | else:
22 | directory = "./vectorstore"
23 | if not os.path.exists(directory):
24 | os.makedirs(directory)
25 | self.embedding_function = sentence_transformer_ef
26 |
27 | self.chroma_client = chromadb.PersistentClient(path=directory, settings=Settings(anonymized_telemetry=False))
28 | self.documentation_collection = self.chroma_client.get_or_create_collection(name="documentation",
29 | embedding_function=self.embedding_function)
30 | self.ddl_collection = self.chroma_client.get_or_create_collection(name="ddl",
31 | embedding_function=self.embedding_function)
32 | self.sql_collection = self.chroma_client.get_or_create_collection(name="sql",
33 | embedding_function=self.embedding_function)
34 |
35 | def index_question_sql(self, question: str, sql: str, **kwargs) -> str:
36 | """
37 | Add a question and its corresponding SQL query to the vectorstore.
38 |
39 | Args:
40 | question (str): The question to be associated with the SQL query.
41 | sql (str): The SQL query to be stored.
42 | **kwargs: Additional keyword arguments (optional).
43 |
44 | Returns:
45 | str: A unique identifier (chunk_id) associated with the stored question and SQL query.
46 |
47 | Example:
48 | chunk_id = add_question_sql("What is the total sales?", "SELECT SUM(sales) FROM transactions")
49 | """
50 | question_sql_json = json.dumps({"Question": question, "SQLQuery": sql, }, ensure_ascii=False, )
51 | chunk_id = str(uuid.uuid4()) + "-sql"
52 | self.sql_collection.add(documents=question_sql_json, ids=chunk_id, )
53 |
54 | return chunk_id
55 |
56 | def index_ddl(self, ddl: str, **kwargs) -> str:
57 | """
58 | Add a Data Definition Language (DDL) statement to the vectorstore.
59 |
60 | Args:
61 | ddl (str): The DDL statement to be stored.
62 | **kwargs: Additional keyword arguments (optional).
63 | - table (str): Name of the table associated with the DDL statement.
64 |
65 | Returns:
66 | str: A unique identifier (chunk_id) associated with the stored DDL statement.
67 |
68 | Example:
69 | chunk_id = add_ddl("CREATE TABLE employees (id INT, name VARCHAR(255))", table="employees")
70 | """
71 | chunk_id = str(uuid.uuid4()) + "-ddl"
72 | collection_params = {"documents": ddl, "ids": chunk_id, }
73 | if 'table' in kwargs:
74 | collection_params["metadatas"] = {"table_name": kwargs['table']}
75 | self.ddl_collection.add(**collection_params)
76 | return chunk_id
77 |
78 | def index_documentation(self, documentation: str, **kwargs) -> str:
79 | """
80 | Add documentation to the database.
81 |
82 | Args:
83 | documentation (str): The documentation content to be stored.
84 | **kwargs: Additional keyword arguments (optional).
85 |
86 | Returns:
87 | str: A unique identifier (chunk_id) associated with the stored documentation.
88 |
89 | Example:
90 | chunk_id = add_documentation("This function performs data validation.")
91 | """
92 | chunk_id = str(uuid.uuid4()) + "-doc"
93 | self.documentation_collection.add(documents=documentation, ids=chunk_id, )
94 | return chunk_id
95 |
96 | def fetch_all_vectorstore_data(self, **kwargs) -> pd.DataFrame:
97 | """
98 | Retrieve training data from different collections in the database.
99 |
100 | Args:
101 | **kwargs: Additional keyword arguments (optional).
102 |
103 | Returns: pd.DataFrame: A DataFrame containing training data with columns 'id', 'question', 'content',
104 | and 'training_data_type'.
105 |
106 | Example:
107 | training_df = get_training_data()
108 | """
109 | sql_data = self.sql_collection.get()
110 |
111 | df = pd.DataFrame()
112 |
113 | if sql_data is not None:
114 | # Extract the documents and ids
115 | documents = [json.loads(doc) for doc in sql_data["documents"]]
116 | ids = sql_data["ids"]
117 |
118 | # Create a DataFrame
119 | df_sql = pd.DataFrame({"id": ids, "question": [doc["question"] for doc in documents],
120 | "content": [doc["sql"] for doc in documents], })
121 |
122 | df_sql["training_data_type"] = "sql"
123 |
124 | df = pd.concat([df, df_sql])
125 |
126 | ddl_data = self.ddl_collection.get()
127 |
128 | if ddl_data is not None:
129 | # Extract the documents and ids
130 | documents = [doc for doc in ddl_data["documents"]]
131 | ids = ddl_data["ids"]
132 |
133 | # Create a DataFrame
134 | df_ddl = pd.DataFrame(
135 | {"id": ids, "question": [None for doc in documents], "content": [doc for doc in documents], })
136 |
137 | df_ddl["training_data_type"] = "ddl"
138 |
139 | df = pd.concat([df, df_ddl])
140 |
141 | doc_data = self.documentation_collection.get()
142 |
143 | if doc_data is not None:
144 | # Extract the documents and ids
145 | documents = [doc for doc in doc_data["documents"]]
146 | ids = doc_data["ids"]
147 |
148 | # Create a DataFrame
149 | df_doc = pd.DataFrame(
150 | {"id": ids, "question": [None for doc in documents], "content": [doc for doc in documents], })
151 |
152 | df_doc["training_data_type"] = "documentation"
153 |
154 | df = pd.concat([df, df_doc])
155 |
156 | return df
157 |
158 | def delete_vectorstore_data(self, item_id: str, **kwargs) -> bool:
159 | """
160 | Remove training data from the respective collection based on the provided item_id.
161 |
162 | Args:
163 | item_id (str): The unique identifier associated with the training data.
164 | **kwargs: Additional keyword arguments (optional).
165 |
166 | Returns:
167 | bool: True if the removal was successful, False otherwise.
168 |
169 | Example:
170 | result = remove_training_data("example-id-sql")
171 | """
172 | if item_id.endswith("-sql"):
173 | self.sql_collection.delete(ids=[item_id])
174 | return True
175 | elif item_id.endswith("-ddl"):
176 | self.ddl_collection.delete(ids=[item_id])
177 | return True
178 | elif item_id.endswith("-doc"):
179 | self.documentation_collection.delete(ids=[item_id])
180 | return True
181 | else:
182 | return False
183 |
184 | def remove_collection(self, collection_name: str) -> bool:
185 | """
186 | This function can reset the collection to empty state.
187 |
188 | Args:
189 | collection_name (str): sql or ddl or documentation
190 |
191 | Returns:
192 | bool: True if collection is deleted, False otherwise
193 | """
194 | if collection_name == "sql":
195 | self.chroma_client.delete_collection(name="sql")
196 | self.sql_collection = self.chroma_client.get_or_create_collection(name="sql",
197 | embedding_function=self.embedding_function)
198 | return True
199 | elif collection_name == "ddl":
200 | self.chroma_client.delete_collection(name="ddl")
201 | self.ddl_collection = self.chroma_client.get_or_create_collection(name="ddl",
202 | embedding_function=self.embedding_function)
203 | return True
204 | elif collection_name == "documentation":
205 | self.chroma_client.delete_collection(name="documentation")
206 | self.documentation_collection = self.chroma_client.get_or_create_collection(name="documentation",
207 | embedding_function=self.embedding_function)
208 | return True
209 | else:
210 | return False
211 |
212 | @staticmethod
213 | def _extract_documents(query_results) -> list:
214 | """
215 | Static method to extract the documents from the QueryResult.
216 |
217 | Args:
218 | query_results (chromadb.api.types.QueryResult): The dataframe to use.
219 |
220 | Returns:
221 | List[str] or None: The extracted documents, or an empty list or single document if an error occurred.
222 | """
223 | if query_results is None:
224 | return []
225 | if ('documents' in query_results and query_results['documents'] is not None and len(
226 | query_results['documents']) > 0):
227 | documents = query_results["documents"]
228 |
229 | if len(documents) == 1 and isinstance(documents[0], list):
230 | try:
231 | documents = [json.loads(doc) for doc in documents[0]]
232 | except Exception as e:
233 | return documents[0]
234 |
235 | return documents
236 |
237 | def retrieve_relevant_question_sql(self, question: str, **kwargs) -> list:
238 | """
239 | Get a list of similar questions based on the provided question using the SQL collection.
240 |
241 | Args:
242 | question (str): The question for which similar questions are sought.
243 | **kwargs: Additional keyword arguments (optional).
244 |
245 | Returns:
246 | list: A list of similar questions.
247 |
248 | Example:
249 | similar_questions = get_similar_question_sql("How to retrieve total sales?")
250 | """
251 | n = kwargs.get("n_results", 2)
252 | return ChromaDB._extract_documents(self.sql_collection.query(query_texts=[question], n_results=n))
253 |
254 | def retrieve_relevant_ddl(self, question: str, **kwargs) -> list:
255 | """
256 | Get a list of related Data Definition Language (DDL) statements based on the provided question.
257 |
258 | Args:
259 | question (str): The question for which related DDL statements are sought.
260 | **kwargs: Additional keyword arguments (optional).
261 |
262 | Returns:
263 | list: A list of related DDL statements.
264 |
265 | Example:
266 | related_ddl = get_related_ddl("How to create a table for employee records?")
267 | """
268 | n = kwargs.get("n_results", 2)
269 | return ChromaDB._extract_documents(self.ddl_collection.query(query_texts=[question], n_results=n, ))
270 |
271 | def retrieve_relevant_documentation(self, question: str, **kwargs) -> list:
272 | """
273 | Get a list of related documentation based on the provided question.
274 |
275 | Args:
276 | question (str): The question for which related documentation is sought.
277 | **kwargs: Additional keyword arguments (optional).
278 |
279 | Returns:
280 | list: A list of related documentation.
281 |
282 | Example:
283 | related_docs = get_related_documentation("How to use the data validation function?")
284 | """
285 | n = kwargs.get("n_results", 2)
286 | return ChromaDB._extract_documents(self.documentation_collection.query(query_texts=[question], n_results=n, ))
287 |
--------------------------------------------------------------------------------
/mindsql/vectorstores/faiss_db.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import uuid
4 |
5 | import faiss
6 | import numpy as np
7 | import pandas as pd
8 | from sentence_transformers import SentenceTransformer
9 |
10 | from . import IVectorstore
11 |
12 | sentence_transformer_ef = SentenceTransformer("WhereIsAI/UAE-Large-V1")
13 |
14 |
15 | class Faiss(IVectorstore):
16 | def __init__(self, config=None):
17 | """
18 | Initialize the FAISS vector store.
19 |
20 | Parameters:
21 | config (any): The configuration parameter.
22 |
23 | Returns:
24 | None
25 | """
26 | if config is not None:
27 | directory = config.get("path", ".")
28 | self.dimension = config.get("dimension", 1024)
29 | self.embedding_function = config.get("embedding_function", sentence_transformer_ef)
30 | self.index_builder = config.get("index_builder", faiss.IndexFlatL2)
31 | self.metric_type = config.get("metric_type", "euclidean")
32 | else:
33 | directory = "./vectorstore"
34 | if not os.path.exists(directory):
35 | os.makedirs(directory)
36 |
37 | self.dimension = 1024
38 | self.embedding_function = sentence_transformer_ef
39 | self.index_builder = faiss.IndexFlatL2
40 | self.metric_type = "euclidean"
41 |
42 | self.sql_index, self.sql_chunk_ids, self.sql_index_mapping = self._initialize_index(
43 | os.path.join(directory, "sql"))
44 | self.ddl_index, self.ddl_chunk_ids, self.ddl_index_mapping = self._initialize_index(
45 | os.path.join(directory, "ddl"))
46 | self.documentation_index, self.documentation_chunk_ids, self.documentation_index_mapping = self._initialize_index(
47 | os.path.join(directory, "documentation"))
48 | self.ddl_metadata = {}
49 |
50 | def _initialize_index(self, index_folder: str) -> tuple:
51 | """
52 | Initializes the index for the given index_folder.
53 |
54 | Parameters:
55 | - index_folder (str): The folder path where the index will be stored.
56 |
57 | Returns:
58 | tuple: A tuple containing the following elements:
59 | - index: The initialized index.
60 | - chunk_ids (list): An empty list to store chunk IDs.
61 | - index_mapping (dict): An empty dictionary to store index mapping.
62 | """
63 | index = self.index_builder(self.dimension)
64 | chunk_ids = []
65 | index_mapping = {}
66 | return index, chunk_ids, index_mapping
67 |
68 | def index_question_sql(self, question: str, sql: str, **kwargs) -> str:
69 | """
70 | Adds a question and its corresponding SQL query to the SQL index.
71 |
72 | Parameters:
73 | - question (str): The question to be associated with the SQL query.
74 | - sql (str): The SQL query.
75 | - **kwargs: Additional keyword arguments.
76 |
77 | Returns:
78 | str: The chunk ID generated for the added question-SQL pair.
79 | """
80 | question_sql_json = json.dumps({"Question": question, "SQLQuery": sql}, ensure_ascii=False)
81 | chunk_id = str(uuid.uuid4()) + "-sql"
82 |
83 | vectors = self.embedding_function.encode([question_sql_json]).astype('float32')
84 | self.sql_index.add(vectors)
85 | self.sql_chunk_ids.append(question_sql_json)
86 | self.sql_index_mapping[chunk_id] = len(self.sql_chunk_ids) - 1
87 |
88 | return chunk_id
89 |
90 | def index_ddl(self, ddl: str, **kwargs) -> str:
91 | """
92 | Adds a Data Definition Language (DDL) statement to the DDL index.
93 |
94 | Parameters:
95 | - ddl (str): The DDL statement to be added.
96 | - **kwargs: Additional keyword arguments.
97 |
98 | Returns:
99 | str: The chunk ID generated for the added DDL statement.
100 | """
101 | chunk_id = str(uuid.uuid4()) + "-ddl"
102 |
103 | table_name = kwargs.get('table', None)
104 | vectors = self.embedding_function.encode([ddl]).astype('float32')
105 | self.ddl_index.add(vectors)
106 | self.ddl_chunk_ids.append(ddl)
107 | self.ddl_index_mapping[chunk_id] = len(self.ddl_chunk_ids) - 1
108 | self.ddl_metadata[chunk_id] = {'table': table_name}
109 |
110 | return chunk_id
111 |
112 | def index_documentation(self, documentation: str, **kwargs) -> str:
113 | """
114 | Adds documentation text to the documentation index.
115 |
116 | Parameters:
117 | - documentation (str): The documentation text to be added.
118 | - **kwargs: Additional keyword arguments.
119 |
120 | Returns:
121 | str: The chunk ID generated for the added documentation.
122 | """
123 | chunk_id = str(uuid.uuid4()) + "-doc"
124 |
125 | vectors = self.embedding_function.encode([documentation]).astype('float32')
126 | self.documentation_index.add(vectors)
127 | self.documentation_chunk_ids.append(documentation)
128 | self.documentation_index_mapping[chunk_id] = len(self.documentation_chunk_ids) - 1
129 |
130 | return chunk_id
131 |
132 | def fetch_all_vectorstore_data(self, **kwargs) -> pd.DataFrame:
133 | """
134 | Retrieves training data from the indexes and organizes it into a pandas DataFrame.
135 |
136 | Parameters:
137 | - **kwargs: Additional keyword arguments.
138 |
139 | Returns:
140 | pd.DataFrame: A DataFrame containing the training data with columns:
141 | - 'id': The chunk ID.
142 | - 'question': Empty placeholder (None).
143 | - 'content': Empty placeholder (None).
144 | - 'training_data_type': The type of training data ('sql', 'ddl', or 'documentation').
145 | """
146 | combined_data = []
147 |
148 | for index, chunk_ids, index_mapping, index_name in zip(
149 | [self.sql_index, self.ddl_index, self.documentation_index],
150 | [self.sql_chunk_ids, self.ddl_chunk_ids, self.documentation_chunk_ids],
151 | [self.sql_index_mapping, self.ddl_index_mapping, self.documentation_index_mapping],
152 | ["sql", "ddl", "documentation"]):
153 | n_total = index.n_total
154 | if n_total > 0:
155 | _, ids = index.search(np.arange(n_total), n_total)
156 | for idx, doc_vec in enumerate(ids):
157 | combined_data.append([chunk_ids[idx], None, None, index_name])
158 |
159 | cols = ['id', 'question', 'content', 'training_data_type']
160 | return pd.DataFrame(combined_data, columns=cols)
161 |
162 | def delete_vectorstore_data(self, item_id: str, **kwargs) -> bool:
163 | """
164 | Removes a training data item identified by its item_id from the respective index.
165 |
166 | Parameters:
167 | - item_id (str): The ID of the item to be removed.
168 | - **kwargs: Additional keyword arguments.
169 |
170 | Returns:
171 | bool: True if the item was successfully removed, False otherwise.
172 | """
173 | if item_id.startswith("sql"):
174 | index = self.sql_index
175 | chunk_ids = self.sql_chunk_ids
176 | index_mapping = self.sql_index_mapping
177 | elif item_id.startswith("ddl"):
178 | index = self.ddl_index
179 | chunk_ids = self.ddl_chunk_ids
180 | index_mapping = self.ddl_index_mapping
181 | elif item_id.startswith("doc"):
182 | index = self.documentation_index
183 | chunk_ids = self.documentation_chunk_ids
184 | index_mapping = self.documentation_index_mapping
185 | else:
186 | return False
187 |
188 | doc_index = index_mapping[item_id]
189 |
190 | index.remove_ids(np.array([doc_index]))
191 |
192 | del chunk_ids[doc_index]
193 |
194 | for i, chunk_id in enumerate(chunk_ids):
195 | index_mapping[chunk_id] = i
196 |
197 | return True
198 |
199 | def remove_collection(self, collection_name: str) -> bool:
200 | """
201 | Removes all items from a specified collection.
202 |
203 | Parameters:
204 | - collection_name (str): The name of the collection to be removed.
205 |
206 | Returns:
207 | bool: True if the collection was successfully removed, False otherwise.
208 | """
209 | if collection_name == "sql":
210 | index = self.sql_index
211 | chunk_ids = self.sql_chunk_ids
212 | index_mapping = self.sql_index_mapping
213 | elif collection_name == "ddl":
214 | index = self.ddl_index
215 | chunk_ids = self.ddl_chunk_ids
216 | index_mapping = self.ddl_index_mapping
217 | elif collection_name == "documentation":
218 | index = self.documentation_index
219 | chunk_ids = self.documentation_chunk_ids
220 | index_mapping = self.documentation_index_mapping
221 | else:
222 | return False
223 |
224 | index.reset()
225 | chunk_ids.clear()
226 | index_mapping.clear()
227 |
228 | return True
229 |
230 | def retrieve_relevant_question_sql(self, question: str, **kwargs) -> list:
231 | """
232 | Retrieves similar question-SQL pairs based on the provided question.
233 |
234 | Parameters:
235 | - question (str): The question for which similar question-SQL pairs are to be retrieved.
236 | - **kwargs: Additional keyword arguments.
237 | - k (int): Number of similar question-SQL pairs to retrieve (default is 2).
238 |
239 | Returns:
240 | list: A list of IDs representing the similar question-SQL pairs.
241 | """
242 | vectors = self.embedding_function.encode([question]).astype('float32')
243 | distances, indices = self.sql_index.search(vectors, kwargs.pop('k', 2))
244 | result = []
245 | if np.all(indices[0] == -1):
246 | return result
247 |
248 | for idx in indices[0]:
249 | if idx != -1:
250 | question_sql_json = self.sql_chunk_ids[idx]
251 | question_sql_dict = json.loads(question_sql_json)
252 | result.append(question_sql_dict)
253 | return result
254 |
255 | def retrieve_relevant_ddl(self, question: str, **kwargs) -> list:
256 | """
257 | Retrieves related Data Definition Language (DDL) statements based on the provided question.
258 |
259 | Parameters:
260 | - question (str): The question for which related DDL statements are to be retrieved.
261 | - **kwargs: Additional keyword arguments.
262 | - k (int): Number of related DDL statements to retrieve (default is 2).
263 |
264 | Returns:
265 | list: A list of related DDL statements.
266 | """
267 | vectors = self.embedding_function.encode([question]).astype('float32')
268 | distances, indices = self.ddl_index.search(vectors, kwargs.pop('k', 2))
269 | result = []
270 | if np.all(indices[0] == -1):
271 | return result
272 |
273 | for idx in indices[0]:
274 | if idx != -1:
275 | ddl_statement = self.ddl_chunk_ids[idx]
276 | result.append(ddl_statement)
277 | return result
278 |
279 | def retrieve_relevant_documentation(self, question: str, **kwargs) -> list:
280 | """
281 | Retrieves related documentation based on the provided question.
282 |
283 | Parameters:
284 | - question (str): The question for which related documentation is to be retrieved.
285 | - **kwargs: Additional keyword arguments.
286 | - k (int): Number of related documentation items to retrieve (default is 2).
287 |
288 | Returns:
289 | list: A list of IDs representing the related documentation items.
290 | """
291 | vectors = self.embedding_function.encode([question]).astype('float32')
292 | distances, indices = self.documentation_index.search(vectors, kwargs.pop('k', 2))
293 | result = []
294 | if np.all(indices[0] == -1):
295 | return result
296 |
297 | for idx in indices[0]:
298 | if idx != -1:
299 | doc_statement = self.documentation_chunk_ids[idx]
300 | result.append(doc_statement)
301 | return result
302 |
--------------------------------------------------------------------------------
/mindsql/vectorstores/ivectorstore.py:
--------------------------------------------------------------------------------
1 | import abc
2 | import pandas as pd
3 |
4 |
5 | class IVectorstore(metaclass=abc.ABCMeta):
6 | @classmethod
7 | def __subclasshook__(cls, subclass):
8 | return (hasattr(subclass, 'retrieve_relevant_question_sql') and
9 | callable(subclass.retrieve_relevant_question_sql) and
10 | hasattr(subclass, 'retrieve_relevant_ddl') and
11 | callable(subclass.retrieve_relevant_ddl) and
12 | hasattr(subclass, 'index_question_sql') and
13 | callable(subclass.index_question_sql) and
14 | hasattr(subclass, 'index_ddl') and
15 | callable(subclass.index_ddl) and
16 | hasattr(subclass, 'index_documentation') and
17 | callable(subclass.index_documentation) and
18 | hasattr(subclass, 'fetch_all_vectorstore_data') and
19 | callable(subclass.fetch_all_vectorstore_data) and
20 | hasattr(subclass, 'retrieve_relevant_documentation') and
21 | callable(subclass.retrieve_relevant_documentation) and
22 | hasattr(subclass, 'delete_vectorstore_data') and
23 | callable(subclass.delete_vectorstore_data) or
24 | NotImplemented)
25 |
26 | @abc.abstractmethod
27 | def retrieve_relevant_question_sql(self, question: str, **kwargs) -> list:
28 | """
29 | This method retrieves the related question and SQL based on the provided question and optional keyword
30 | arguments.
31 |
32 | Parameters:
33 | question (str): The question for which related question and SQL is to be retrieved.
34 | **kwargs: Optional keyword arguments.
35 |
36 | Returns:
37 | list: A list of related question and SQL items.
38 | """
39 | raise NotImplementedError
40 |
41 | @abc.abstractmethod
42 | def retrieve_relevant_ddl(self, question: str, **kwargs) -> list:
43 | """
44 | A method to get related DDL statements based on a question and optional keyword arguments.
45 |
46 | Parameters:
47 | question: str - the question for which related DDL statements are to be retrieved
48 | **kwargs: additional keyword arguments
49 |
50 | Returns:
51 | list - a list of related DDL statements
52 | """
53 | raise NotImplementedError
54 |
55 | @abc.abstractmethod
56 | def retrieve_relevant_documentation(self, question: str, **kwargs) -> list:
57 | """
58 | A method to get related documentation based on a question and optional keyword arguments.
59 |
60 | Parameters:
61 | question: str - the question for which related documentation is to be retrieved
62 | **kwargs: additional keyword arguments
63 |
64 | Returns:
65 | list - a list of related documentation
66 | """
67 | raise NotImplementedError
68 |
69 | @abc.abstractmethod
70 | def index_question_sql(self, question: str, sql: str, **kwargs) -> str:
71 | """
72 | A method to add a question and SQL pair to the vectorstore.
73 |
74 | Parameters:
75 | question (str): The question to be added to the vectorstore.
76 | sql (str): The SQL to be added to the vectorstore.
77 | **kwargs: Additional keyword arguments.
78 |
79 | Returns:
80 | str: A message confirming the successful addition of the question and SQL pair.
81 | """
82 | raise NotImplementedError
83 |
84 | @abc.abstractmethod
85 | def index_ddl(self, ddl: str, **kwargs) -> str:
86 | """
87 | A method to add DDL to the vectorstore.
88 |
89 | Parameters:
90 | ddl (str): The DDL to be added to the vectorstore.
91 | **kwargs: Additional keyword arguments.
92 |
93 | Returns:
94 | str: A message confirming the successful addition of the DDL.
95 | """
96 | raise NotImplementedError
97 |
98 | @abc.abstractmethod
99 | def index_documentation(self, documentation: str, **kwargs) -> str:
100 | """
101 | A method to add documentation to the vectorstore.
102 |
103 | Parameters:
104 | documentation (str): The documentation to be added to the vectorstore.
105 | **kwargs: Additional keyword arguments.
106 |
107 | Returns:
108 | str: A message confirming the successful addition of the documentation.
109 | """
110 | raise NotImplementedError
111 |
112 | @abc.abstractmethod
113 | def fetch_all_vectorstore_data(self, **kwargs) -> pd.DataFrame:
114 | """
115 | A method to fetch all data from the vectorstore.
116 |
117 | Parameters:
118 | **kwargs: Additional keyword arguments.
119 |
120 | Returns:
121 | pd.DataFrame: The data from the vectorstore.
122 | """
123 | raise NotImplementedError
124 |
125 | @abc.abstractmethod
126 | def delete_vectorstore_data(self, item_id: str, **kwargs) -> bool:
127 | """
128 | A method to delete data from the vectorstore based on the provided item_id.
129 |
130 | Parameters:
131 | item_id (str): The unique identifier associated with the data to be deleted.
132 | **kwargs: Additional keyword arguments.
133 |
134 | Returns:
135 | bool: True if the deletion was successful, False otherwise.
136 | """
137 | raise NotImplementedError
138 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "mindsql"
3 | version = "0.2.01"
4 | description = "Text-2-SQL made easy in just a few lines of python."
5 | authors = ["Mindinventory "]
6 | readme = "README.md"
7 | repository = "https://github.com/Mindinventory/MindSQL"
8 | homepage = "https://www.mindinventory.com/text-to-sql-mindsql.php"
9 | license = "GPL-3.0-or-later"
10 | keywords = ["Text2SQL", "data", "text to sql", "Text-to-SQL", "RAG", "LLM", "NLP"]
11 | classifiers = [
12 | "Topic :: Scientific/Engineering :: Artificial Intelligence",
13 | "Topic :: Software Development :: Libraries :: Application Frameworks",
14 | "Topic :: Software Development :: Libraries :: Python Modules",
15 | ]
16 |
17 |
18 | [tool.poetry.dependencies]
19 | python = "^3.10"
20 | chromadb = "^0.4.22"
21 | pandas = "2.2.0"
22 | plotly = "5.19.0"
23 | mysql-connector-python = "^8.3.0"
24 | google-generativeai="0.3.2"
25 | llama-cpp-python = "0.2.47"
26 | openai = "^1.12.0"
27 | sqlparse = "^0.4.4"
28 | numpy = "^1.26.4"
29 | sentence-transformers = "^2.3.1"
30 | psycopg2-binary = "^2.9.9"
31 | faiss-cpu = "^1.8.0"
32 | pysqlite3-binary = "^0.5.2.post3"
33 | transformers = "^4.38.2"
34 |
35 |
36 | [build-system]
37 | requires = ["poetry-core"]
38 | build-backend = "poetry.core.masonry.api"
39 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mindinventory/MindSQL/f7e24b3022ddc2d820e85021637ad38f6fdda073/tests/__init__.py
--------------------------------------------------------------------------------
/tests/ollama_test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from unittest.mock import MagicMock, patch
3 | from ollama import Client, Options
4 |
5 | from mindsql.llms import ILlm
6 | from mindsql.llms import Ollama
7 | from mindsql._utils.constants import PROMPT_EMPTY_EXCEPTION, OLLAMA_CONFIG_REQUIRED
8 |
9 |
10 | class TestOllama(unittest.TestCase):
11 |
12 | def setUp(self):
13 | # Common setup for each test case
14 | self.model_config = {'model': 'sqlcoder'}
15 | self.client_config = {'host': 'http://localhost:11434/'}
16 | self.client_mock = MagicMock(spec=Client)
17 |
18 | def test_initialization_with_client(self):
19 | ollama = Ollama(model_config=self.model_config, client=self.client_mock)
20 | self.assertEqual(ollama.client, self.client_mock)
21 | self.assertIsNone(ollama.client_config)
22 | self.assertEqual(ollama.model_config, self.model_config)
23 |
24 | def test_initialization_with_client_config(self):
25 | ollama = Ollama(model_config=self.model_config, client_config=self.client_config)
26 | self.assertIsNotNone(ollama.client)
27 | self.assertEqual(ollama.client_config, self.client_config)
28 | self.assertEqual(ollama.model_config, self.model_config)
29 |
30 | def test_initialization_missing_client_and_client_config(self):
31 | with self.assertRaises(ValueError) as context:
32 | Ollama(model_config=self.model_config)
33 | self.assertEqual(str(context.exception), OLLAMA_CONFIG_REQUIRED.format(type="Client"))
34 |
35 | def test_initialization_missing_model_config(self):
36 | with self.assertRaises(ValueError) as context:
37 | Ollama(model_config=None, client_config=self.client_config)
38 | self.assertEqual(str(context.exception), OLLAMA_CONFIG_REQUIRED.format(type="Model"))
39 |
40 | def test_initialization_missing_model_name(self):
41 | with self.assertRaises(ValueError) as context:
42 | Ollama(model_config={}, client_config=self.client_config)
43 | self.assertEqual(str(context.exception), OLLAMA_CONFIG_REQUIRED.format(type="Model name"))
44 |
45 | def test_system_message(self):
46 | ollama = Ollama(model_config=self.model_config, client=self.client_mock)
47 | message = ollama.system_message("Test system message")
48 | self.assertEqual(message, {"role": "system", "content": "Test system message"})
49 |
50 | def test_user_message(self):
51 | ollama = Ollama(model_config=self.model_config, client=self.client_mock)
52 | message = ollama.user_message("Test user message")
53 | self.assertEqual(message, {"role": "user", "content": "Test user message"})
54 |
55 | def test_assistant_message(self):
56 | ollama = Ollama(model_config=self.model_config, client=self.client_mock)
57 | message = ollama.assistant_message("Test assistant message")
58 | self.assertEqual(message, {"role": "assistant", "content": "Test assistant message"})
59 |
60 | @patch.object(Client, 'chat', return_value={'message': {'content': 'Test response'}})
61 | def test_invoke_success(self, mock_chat):
62 | ollama = Ollama(model_config=self.model_config, client=Client())
63 | response = ollama.invoke("Test prompt")
64 |
65 | # Check if the response is as expected
66 | self.assertEqual(response, 'Test response')
67 |
68 | # Verify that the chat method was called with the correct arguments
69 | mock_chat.assert_called_once_with(
70 | model=self.model_config['model'],
71 | messages=[{"role": "user", "content": "Test prompt"}],
72 | options=Options(temperature=0.1)
73 | )
74 |
75 | def test_invoke_empty_prompt(self):
76 | ollama = Ollama(model_config=self.model_config, client=self.client_mock)
77 | with self.assertRaises(ValueError) as context:
78 | ollama.invoke("")
79 | self.assertEqual(str(context.exception), PROMPT_EMPTY_EXCEPTION)
80 |
81 |
82 | if __name__ == '__main__':
83 | unittest.main()
84 |
--------------------------------------------------------------------------------
/tests/sqlserver_test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from unittest.mock import patch, MagicMock
3 | import pyodbc
4 | import pandas as pd
5 | from mindsql.databases.sqlserver import SQLServer, ERROR_WHILE_RUNNING_QUERY, ERROR_CONNECTING_TO_DB_CONSTANT, \
6 | INVALID_DB_CONNECTION_OBJECT, CONNECTION_ESTABLISH_ERROR_CONSTANT
7 | from mindsql.databases.sqlserver import log as logger
8 |
9 |
10 | class TestSQLServer(unittest.TestCase):
11 |
12 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
13 | def test_create_connection_success(self, mock_connect):
14 | mock_connect.return_value = MagicMock(spec=pyodbc.Connection)
15 | connection = SQLServer.create_connection(
16 | 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=server_name;DATABASE=database_name;UID=user;PWD=password')
17 | self.assertIsInstance(connection, pyodbc.Connection)
18 |
19 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
20 | def test_create_connection_failure(self, mock_connect):
21 | mock_connect.side_effect = pyodbc.Error('Connection failed')
22 | with self.assertLogs(logger, level='ERROR') as cm:
23 | connection = SQLServer.create_connection(
24 | 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=server_name;DATABASE=database_name;UID=user;PWD=password')
25 | self.assertIsNone(connection)
26 | self.assertTrue(any(
27 | ERROR_CONNECTING_TO_DB_CONSTANT.format("SQL Server", 'Connection failed') in message for message in
28 | cm.output))
29 |
30 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
31 | def test_execute_sql_success(self, mock_connect):
32 | # Mock the connection and cursor
33 | mock_connection = MagicMock(spec=pyodbc.Connection)
34 | mock_cursor = MagicMock()
35 |
36 | mock_connect.return_value = mock_connection
37 | mock_connection.cursor.return_value = mock_cursor
38 |
39 | # Mock cursor behavior
40 | mock_cursor.execute.return_value = None
41 | mock_cursor.description = [('column1',), ('column2',)]
42 | mock_cursor.fetchall.return_value = [(1, 'a'), (2, 'b')]
43 |
44 | connection = SQLServer.create_connection('fake_connection_string')
45 | sql = "SELECT * FROM table"
46 | sql_server = SQLServer()
47 | result = sql_server.execute_sql(connection, sql)
48 | expected_df = pd.DataFrame(data=[(1, 'a'), (2, 'b')], columns=['column1', 'column2'])
49 | pd.testing.assert_frame_equal(result, expected_df)
50 |
51 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
52 | def test_execute_sql_failure(self, mock_connect):
53 | # Mock the connection and cursor
54 | mock_connection = MagicMock(spec=pyodbc.Connection)
55 | mock_cursor = MagicMock()
56 |
57 | mock_connect.return_value = mock_connection
58 | mock_connection.cursor.return_value = mock_cursor
59 | mock_cursor.execute.side_effect = pyodbc.Error('Query failed')
60 |
61 | connection = SQLServer.create_connection('fake_connection_string')
62 | sql = "SELECT * FROM table"
63 | sql_server = SQLServer()
64 |
65 | with self.assertLogs(logger, level='ERROR') as cm:
66 | result = sql_server.execute_sql(connection, sql)
67 | self.assertIsNone(result)
68 | self.assertTrue(any(ERROR_WHILE_RUNNING_QUERY.format('Query failed') in message for message in cm.output))
69 |
70 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
71 | def test_get_databases_success(self, mock_connect):
72 | # Mock the connection and cursor
73 | mock_connection = MagicMock(spec=pyodbc.Connection)
74 | mock_cursor = MagicMock()
75 |
76 | mock_connect.return_value = mock_connection
77 | mock_connection.cursor.return_value = mock_cursor
78 |
79 | # Mock cursor behavior
80 | mock_cursor.execute.return_value = None
81 | mock_cursor.fetchall.return_value = [('database1',), ('database2',)]
82 |
83 | connection = SQLServer.create_connection('fake_connection_string')
84 | sql_server = SQLServer()
85 | result = sql_server.get_databases(connection)
86 | self.assertEqual(result, ['database1', 'database2'])
87 |
88 | @patch('mindsql.databases.sqlserver.pyodbc.connect')
89 | def test_get_databases_failure(self, mock_connect):
90 | # Mock the connection and cursor
91 | mock_connection = MagicMock(spec=pyodbc.Connection)
92 | mock_cursor = MagicMock()
93 |
94 | mock_connect.return_value = mock_connection
95 | mock_connection.cursor.return_value = mock_cursor
96 | mock_cursor.execute.side_effect = pyodbc.Error('Query failed')
97 |
98 | connection = SQLServer.create_connection('fake_connection_string')
99 | sql_server = SQLServer()
100 |
101 | with self.assertLogs(logger, level='ERROR') as cm:
102 | result = sql_server.get_databases(connection)
103 | self.assertEqual(result, [])
104 | self.assertTrue(any(ERROR_WHILE_RUNNING_QUERY.format('Query failed') in message for message in cm.output))
105 |
106 | @patch('mindsql.databases.sqlserver.SQLServer.execute_sql')
107 | def test_get_table_names_success(self, mock_execute_sql):
108 | mock_execute_sql.return_value = pd.DataFrame(data=[('schema1.table1',), ('schema2.table2',)],
109 | columns=['table_name'])
110 |
111 | connection = MagicMock(spec=pyodbc.Connection)
112 | sql_server = SQLServer()
113 | result = sql_server.get_table_names(connection, 'database_name')
114 | expected_df = pd.DataFrame(data=[('schema1.table1',), ('schema2.table2',)], columns=['table_name'])
115 | pd.testing.assert_frame_equal(result, expected_df)
116 |
117 | @patch('mindsql.databases.sqlserver.SQLServer.execute_sql')
118 | def test_get_all_ddls_success(self, mock_execute_sql):
119 | mock_execute_sql.side_effect = [
120 | pd.DataFrame(data=[('schema1.table1',)], columns=['table_name']),
121 | pd.DataFrame(data=['CREATE TABLE schema1.table1 (...);'], columns=['SQLQuery'])
122 | ]
123 |
124 | connection = MagicMock(spec=pyodbc.Connection)
125 | sql_server = SQLServer()
126 | result = sql_server.get_all_ddls(connection, 'database_name')
127 |
128 | expected_df = pd.DataFrame(data=[{'Table': 'schema1.table1', 'DDL': 'CREATE TABLE schema1.table1 (...);'}])
129 | pd.testing.assert_frame_equal(result, expected_df)
130 |
131 | def test_validate_connection_success(self):
132 | connection = MagicMock(spec=pyodbc.Connection)
133 | sql_server = SQLServer()
134 | # Should not raise any exception
135 | sql_server.validate_connection(connection)
136 |
137 | def test_validate_connection_failure(self):
138 | sql_server = SQLServer()
139 |
140 | with self.assertRaises(ValueError) as cm:
141 | sql_server.validate_connection(None)
142 | self.assertEqual(str(cm.exception), CONNECTION_ESTABLISH_ERROR_CONSTANT)
143 |
144 | with self.assertRaises(ValueError) as cm:
145 | sql_server.validate_connection("InvalidConnectionObject")
146 | self.assertEqual(str(cm.exception), INVALID_DB_CONNECTION_OBJECT.format("SQL Server"))
147 |
148 | @patch('mindsql.databases.sqlserver.SQLServer.execute_sql')
149 | def test_get_ddl_success(self, mock_execute_sql):
150 | mock_execute_sql.return_value = pd.DataFrame(data=['CREATE TABLE schema1.table1 (...);'], columns=['SQLQuery'])
151 |
152 | connection = MagicMock(spec=pyodbc.Connection)
153 | sql_server = SQLServer()
154 | result = sql_server.get_ddl(connection, 'schema1.table1')
155 | self.assertEqual(result, 'CREATE TABLE schema1.table1 (...);')
156 |
157 | def test_get_dialect(self):
158 | sql_server = SQLServer()
159 | self.assertEqual(sql_server.get_dialect(), 'tsql')
160 |
161 |
162 | if __name__ == '__main__':
163 | unittest.main()
164 |
--------------------------------------------------------------------------------
/tests/test.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from mindsql.core import MindSQLCore
4 | from mindsql.databases import Sqlite
5 | from mindsql.llms import GoogleGenAi
6 | from mindsql.vectorstores import ChromaDB
7 |
8 | load_dotenv()
9 |
10 | api_key = os.getenv('API_KEY')
11 | db_url = os.getenv('DB_URL')
12 | example_path = os.getenv('EXAMPLE_PATH')
13 |
14 | # Set up configuration dictionary
15 | config = {'api_key': api_key}
16 |
17 | # Create MindSQLCore instance with configured llm, vectorstore, and database
18 | minds = MindSQLCore(
19 | llm=GoogleGenAi(config=config),
20 | vectorstore=ChromaDB(),
21 | database=Sqlite()
22 | )
23 |
24 | # Create a database connection using the specified URL
25 | conn = minds.database.create_connection(url=db_url)
26 |
27 | # Index all Data Definition Language (DDL) statements in the 'main' database into the vectorstore
28 | minds.index_all_ddls(connection=conn, db_name='main')
29 |
30 | # Index question-sql pair in bulk from the specified example path
31 | minds.index(bulk=True, path=example_path)
32 |
33 | # Ask a question to the database and visualize the result
34 | response = minds.ask_db(
35 | question="Show all products whose unit price is more than 30",
36 | connection=conn,
37 | visualize=True
38 | )
39 |
40 | # Extract and display the chart from the response
41 | chart = response["chart"]
42 | chart.show()
43 |
--------------------------------------------------------------------------------