├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── app_sql.py ├── github ├── introspection1.png ├── preview1.png ├── preview2.png └── preview3.png └── requirements.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ 153 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Roman Gailit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GPT Data Analyst 2 | 3 | [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://raymanyyy-gpt-data-analyst-app-sql-zyh93t.streamlit.app) 4 | 5 | This app utilizes chatGPT API to introspect a DB and query it using user's prompt. It also utilizes Streamlit as simple UI. 6 | 7 | ## Examples 8 | General queries 9 | ![Preview](github/preview1.png) 10 | 11 | Finance reports 12 | ![Preview](github/preview2.png) 13 | 14 | Additional context parsing like "West states" 15 | ![Preview](github/preview3.png) 16 | 17 | On-the-fly schema introspection reference 18 | ![Preview](github/introspection1.png) 19 | -------------------------------------------------------------------------------- /app_sql.py: -------------------------------------------------------------------------------- 1 | import openai 2 | import streamlit as st 3 | import pandas as pd 4 | from sqlalchemy import create_engine, inspect, text 5 | 6 | openai.api_key = st.secrets['OPENAI_API_KEY'] 7 | public_db_schema_link = st.secrets['public_db_schema_link'] 8 | 9 | db_products_dict = { 10 | 'public DB 👍': ['postgres', 'postgresql+psycopg2'], 11 | 'custom Postgres': ['postgres', 'postgresql+psycopg2'], 12 | # todo: add more DBs 13 | # 'custom mySQL': ['mySQL', '...'], 14 | } 15 | 16 | with st.sidebar: 17 | st.write('Pick your DB connection:') 18 | db_type = st.selectbox('DB connection', db_products_dict.keys()) 19 | 20 | # if the user has selected a custom database, then show the input fields, else use the public DB 21 | if db_type == 'custom Postgres': 22 | db_host = st.text_input('host', 'localhost') 23 | db_port = st.text_input('port', '5432') 24 | db_user = st.text_input('user', 'postgres') 25 | db_password = st.text_input('password', 'postgres', type='password') 26 | db_name = st.text_input('database', 'postgres') 27 | else: # public DB 28 | db_host = st.secrets['pub_db_host'] 29 | db_port = st.secrets['pub_db_port'] 30 | db_user = st.secrets['pub_db_user'] 31 | db_password = st.secrets['pub_db_password'] 32 | db_name = st.secrets['pub_db_name'] 33 | 34 | st.write(f'[Schema of the public DB]({public_db_schema_link})') 35 | 36 | with st.form(key='my_form_to_submit'): 37 | user_request = st.text_area("Let chatGPT to do SQL for you") 38 | submit_button = st.form_submit_button(label='Submit') 39 | 40 | if submit_button: 41 | # check if the user has entered a request 42 | if not user_request: 43 | st.error('Please enter a request') 44 | st.stop() 45 | 46 | # check if the user has entered a database credentials 47 | if not db_host or not db_user or not db_password or not db_name or not db_port: 48 | st.error('Please enter a database credentials') 49 | st.stop() 50 | 51 | # try to create an engine to connect to the database 52 | try: 53 | engine = create_engine( 54 | f'{db_products_dict[db_type][1]}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}') 55 | inspector = inspect(engine) 56 | except Exception as e: 57 | st.error(f'Could not connect to the database. Error: {e}') 58 | st.stop() 59 | 60 | table_names = inspector.get_table_names() 61 | 62 | # create an empty dictionary to store the column names for each table 63 | column_names = {} 64 | 65 | # iterate through each table and get its column names 66 | for table_name in table_names: 67 | columns = inspector.get_columns(table_name) 68 | column_names[table_name] = [column['name'] for column in columns] 69 | 70 | # form an introspection doc 71 | doc = f""" 72 | AUTO-GENERATED DATABASE SCHEMA DOCUMENTATION\n 73 | Total Tables: {len(table_names)} 74 | """ 75 | for table_name in table_names: 76 | doc += f""" 77 | --- 78 | Table Name: {table_name}\n 79 | Columns: 80 | """ 81 | for column_name in column_names[table_name]: 82 | doc += f""" 83 | - {column_name} 84 | """ 85 | 86 | intro = 'You are a helpful assistant. You will complete a task and write the results.' 87 | prompt = 'Given the database schema, write a SQL query that returns the following information: ' 88 | prompt += f'{user_request}.\n' 89 | prompt += f'You only need to write SQL code, do not comment or explain code and do not add any additional info. \ 90 | I need code only. Always use table name in column reference to avoid ambiguity. \ 91 | SQL dialect is {db_products_dict[db_type][0]}.\ 92 | Only use columns and tables mentioned in the doc below. \n{doc}' 93 | 94 | response = openai.ChatCompletion.create( 95 | model="gpt-3.5-turbo", 96 | messages=[ 97 | {"role": "system", "content": intro}, 98 | {"role": "user", "content": prompt} 99 | ] 100 | ) 101 | code = response.choices[0].message.content 102 | pretty_code = '```sql\n' + code + '\n```' 103 | code = code.replace('\n', ' ') 104 | 105 | with st.expander("See executed code"): 106 | st.write(pretty_code) 107 | with st.expander("See introspected BD structure"): 108 | st.write(doc) 109 | 110 | df = pd.read_sql_query(sql=text(code), con=engine.connect()) 111 | 112 | st.write("## The results") 113 | st.write(df) 114 | st.write("Is it time to fire your Data Analysts? 😱") 115 | -------------------------------------------------------------------------------- /github/introspection1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raymanyyy/GPT-data-analyst/125c83e647680d1522944a9d3b6975d4bc05d43c/github/introspection1.png -------------------------------------------------------------------------------- /github/preview1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raymanyyy/GPT-data-analyst/125c83e647680d1522944a9d3b6975d4bc05d43c/github/preview1.png -------------------------------------------------------------------------------- /github/preview2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raymanyyy/GPT-data-analyst/125c83e647680d1522944a9d3b6975d4bc05d43c/github/preview2.png -------------------------------------------------------------------------------- /github/preview3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raymanyyy/GPT-data-analyst/125c83e647680d1522944a9d3b6975d4bc05d43c/github/preview3.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.8.4 2 | aiosignal==1.3.1 3 | altair==4.2.2 4 | async-timeout==4.0.2 5 | attrs==22.2.0 6 | blinker==1.5 7 | cachetools==5.3.0 8 | certifi==2022.12.7 9 | charset-normalizer==3.1.0 10 | click==8.1.3 11 | decorator==5.1.1 12 | entrypoints==0.4 13 | frozenlist==1.3.3 14 | gitdb==4.0.10 15 | GitPython==3.1.31 16 | idna==3.4 17 | importlib-metadata==6.0.0 18 | Jinja2==3.1.2 19 | jsonschema==4.17.3 20 | markdown-it-py==2.2.0 21 | MarkupSafe==2.1.2 22 | mdurl==0.1.2 23 | multidict==6.0.4 24 | numpy==1.24.2 25 | openai==0.27.1 26 | packaging==23.0 27 | pandas==1.5.3 28 | Pillow==9.4.0 29 | protobuf==3.20.3 30 | psycopg2-binary==2.9.5 31 | pyarrow==11.0.0 32 | pydeck==0.8.0 33 | Pygments==2.14.0 34 | Pympler==1.0.1 35 | pyrsistent==0.19.3 36 | python-dateutil==2.8.2 37 | pytz==2022.7.1 38 | pytz-deprecation-shim==0.1.0.post0 39 | requests==2.28.2 40 | rich==13.3.2 41 | semver==2.13.0 42 | six==1.16.0 43 | smmap==5.0.0 44 | SQLAlchemy==2.0.5.post1 45 | streamlit==1.20.0 46 | toml==0.10.2 47 | toolz==0.12.0 48 | tornado==6.2 49 | tqdm==4.65.0 50 | typing_extensions==4.5.0 51 | tzdata==2022.7 52 | tzlocal==4.2 53 | urllib3==1.26.14 54 | validators==0.20.0 55 | yarl==1.8.2 56 | zipp==3.15.0 57 | --------------------------------------------------------------------------------