├── logo.png ├── sct.png ├── requirements.txt ├── LICENSE ├── .gitignore ├── README.md └── main.py /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AIAnytime/Graphy-v1/HEAD/logo.png -------------------------------------------------------------------------------- /sct.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AIAnytime/Graphy-v1/HEAD/sct.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | langchain 2 | langchain-community 3 | sentence-transformers 4 | langchain-experimental 5 | neo4j 6 | pypdf 7 | python-dotenv 8 | langchain_openai 9 | streamlit -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 AI Anytime 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 | -------------------------------------------------------------------------------- /.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 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Graphy v1 2 | 3 | ![Graphy Logo](./logo.png) 4 | 5 | Graphy v1 is a real-time GraphRAG (Graph Retrieval-Augmented Generation) application that leverages the power of [LangChain](https://python.langchain.com/), [Neo4j](https://neo4j.com/), and OpenAI's GPT models to extract knowledge from documents and enable natural language querying over a graph database. 6 | 7 | ![App Screenshot](./sct.png) 8 | 9 | ## Table of Contents 10 | 11 | - [Overview](#overview) 12 | - [Features](#features) 13 | - [Demo](#demo) 14 | - [Getting Started](#getting-started) 15 | - [Prerequisites](#prerequisites) 16 | - [Installation](#installation) 17 | - [Usage](#usage) 18 | - [Contributing](#contributing) 19 | - [License](#license) 20 | - [Contact](#contact) 21 | 22 | ## Overview 23 | 24 | Graphy v1 allows users to upload a PDF document, which is then processed to extract entities and relationships using OpenAI's GPT models (e.g., `gpt-4o` and `text-ada-002`). The extracted information is stored in a Neo4j graph database. Users can then interact with the graph in real-time by asking natural language questions, which are converted into Cypher queries to retrieve answers from the graph. 25 | 26 | ## Features 27 | 28 | - **Real-time GraphRAG**: Extracts knowledge from documents and allows real-time querying. 29 | - **Modular and Configurable**: Users can set their own credentials for OpenAI and Neo4j. 30 | - **Natural Language Interface**: Ask questions in plain English and get answers from the graph database. 31 | - **Visualization**: (Coming Soon) Visual representation of the graph and query results. 32 | - **Extensible**: Designed to support multiple documents and more conversational interactions in future versions. 33 | 34 | ## Demo 35 | 36 | [![Watch the video](https://img.youtube.com/vi/odtGLUPXqfs/hqdefault.jpg)](https://youtu.be/odtGLUPXqfs) 37 | 38 | 39 | *Click the image above to watch the demo video on YouTube.* 40 | 41 | ## Getting Started 42 | 43 | ### Prerequisites 44 | 45 | - Python 3.10 or higher 46 | - An OpenAI API key with access to GPT models (e.g., `gpt-4o` or `ada 002`) 47 | - A Neo4j database instance (local or remote) 48 | - [Streamlit](https://streamlit.io/) 49 | 50 | ### Installation 51 | 52 | 1. **Clone the Repository** 53 | 54 | ```bash 55 | git clone https://github.com/yourusername/graphy-v1.git 56 | cd graphy-v1 57 | ``` 58 | 59 | 2. **Install Dependencies** 60 | 61 | Create a virtual environment (optional but recommended): 62 | 63 | ```bash 64 | python -m venv venv 65 | source venv/bin/activate # On Windows, use `venv\Scripts\activate` 66 | ``` 67 | 68 | Install the required packages: 69 | 70 | ```bash 71 | pip install -r requirements.txt 72 | ``` 73 | 74 | ### Usage 75 | 76 | 1. **Set Up Credentials** 77 | 78 | - Place your OpenAI API key and Neo4j credentials in a `.env` file or enter them directly in the app's sidebar when running. 79 | 80 | Example `.env` file: 81 | 82 | ```env 83 | OPENAI_API_KEY=your-openai-api-key 84 | NEO4J_URL=neo4j+s://your-neo4j-url 85 | NEO4J_USERNAME=your-username 86 | NEO4J_PASSWORD=your-password 87 | ``` 88 | 89 | 2. **Run the App** 90 | 91 | ```bash 92 | streamlit run app.py 93 | ``` 94 | 95 | 3. **Interact with the App** 96 | 97 | - Upload a PDF file using the file uploader. 98 | - Once the document is processed, ask questions in the provided text input field. 99 | - View the generated Cypher query and the answer retrieved from the graph. 100 | 101 | ## Contributing 102 | 103 | Contributions are welcome! Here are some ways you can help: 104 | 105 | - **Enhancements**: Make the app more conversational or extend it to support multiple documents. 106 | - **Bug Reports**: Submit issues for any bugs you encounter. 107 | - **Feature Requests**: Suggest new features or improvements. 108 | - **Documentation**: Improve documentation and tutorials. 109 | 110 | To contribute: 111 | 112 | 1. Fork the repository. 113 | 2. Create a new branch for your feature or bugfix. 114 | 3. Commit your changes with clear commit messages. 115 | 4. Open a pull request describing your changes. 116 | 117 | ## License 118 | 119 | This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details. 120 | 121 | ## Contact 122 | 123 | For questions or inquiries, please contact the developer: 124 | 125 | - **Email**: [aianytime07@gmail.com](mailto:aianytime07@gmail.com) 126 | 127 | --- 128 | 129 | *Disclaimer: This project is for educational purposes. Please ensure compliance with all applicable laws and regulations when using OpenAI's API and handling data.* 130 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from langchain.document_loaders import PyPDFLoader 4 | from langchain.text_splitter import RecursiveCharacterTextSplitter 5 | from langchain.schema import Document 6 | from langchain.prompts import PromptTemplate 7 | from langchain.vectorstores import Neo4jVector 8 | from langchain.chat_models import ChatOpenAI 9 | from langchain.embeddings import OpenAIEmbeddings 10 | from langchain.graphs import Neo4jGraph 11 | from langchain_experimental.graph_transformers import LLMGraphTransformer 12 | from langchain.chains.graph_qa.cypher import GraphCypherQAChain 13 | import streamlit as st 14 | import tempfile 15 | from neo4j import GraphDatabase 16 | 17 | def main(): 18 | st.set_page_config( 19 | layout="wide", 20 | page_title="Graphy v1", 21 | page_icon=":graph:" 22 | ) 23 | st.sidebar.image('logo.png', use_column_width=True) 24 | with st.sidebar.expander("Expand Me"): 25 | st.markdown(""" 26 | This application allows you to upload a PDF file, extract its content into a Neo4j graph database, and perform queries using natural language. 27 | It leverages LangChain and OpenAI's GPT models to generate Cypher queries that interact with the Neo4j database in real-time. 28 | """) 29 | st.title("Graphy: Realtime GraphRAG App") 30 | 31 | load_dotenv() 32 | 33 | # Set OpenAI API key 34 | if 'OPENAI_API_KEY' not in st.session_state: 35 | st.sidebar.subheader("OpenAI API Key") 36 | openai_api_key = st.sidebar.text_input("Enter your OpenAI API Key:", type='password') 37 | if openai_api_key: 38 | os.environ['OPENAI_API_KEY'] = openai_api_key 39 | st.session_state['OPENAI_API_KEY'] = openai_api_key 40 | st.sidebar.success("OpenAI API Key set successfully.") 41 | embeddings = OpenAIEmbeddings() 42 | llm = ChatOpenAI(model_name="gpt-4o") # Use model that supports function calling 43 | st.session_state['embeddings'] = embeddings 44 | st.session_state['llm'] = llm 45 | else: 46 | embeddings = st.session_state['embeddings'] 47 | llm = st.session_state['llm'] 48 | 49 | # Initialize variables 50 | neo4j_url = None 51 | neo4j_username = None 52 | neo4j_password = None 53 | graph = None 54 | 55 | # Set Neo4j connection details 56 | if 'neo4j_connected' not in st.session_state: 57 | st.sidebar.subheader("Connect to Neo4j Database") 58 | neo4j_url = st.sidebar.text_input("Neo4j URL:", value="neo4j+s://") 59 | neo4j_username = st.sidebar.text_input("Neo4j Username:", value="neo4j") 60 | neo4j_password = st.sidebar.text_input("Neo4j Password:", type='password') 61 | connect_button = st.sidebar.button("Connect") 62 | if connect_button and neo4j_password: 63 | try: 64 | graph = Neo4jGraph( 65 | url=neo4j_url, 66 | username=neo4j_username, 67 | password=neo4j_password 68 | ) 69 | st.session_state['graph'] = graph 70 | st.session_state['neo4j_connected'] = True 71 | # Store connection parameters for later use 72 | st.session_state['neo4j_url'] = neo4j_url 73 | st.session_state['neo4j_username'] = neo4j_username 74 | st.session_state['neo4j_password'] = neo4j_password 75 | st.sidebar.success("Connected to Neo4j database.") 76 | except Exception as e: 77 | st.error(f"Failed to connect to Neo4j: {e}") 78 | else: 79 | graph = st.session_state['graph'] 80 | neo4j_url = st.session_state['neo4j_url'] 81 | neo4j_username = st.session_state['neo4j_username'] 82 | neo4j_password = st.session_state['neo4j_password'] 83 | 84 | # Ensure that the Neo4j connection is established before proceeding 85 | if graph is not None: 86 | # File uploader 87 | uploaded_file = st.file_uploader("Please select a PDF file.", type="pdf") 88 | 89 | if uploaded_file is not None and 'qa' not in st.session_state: 90 | with st.spinner("Processing the PDF..."): 91 | # Save uploaded file to temporary file 92 | with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: 93 | tmp_file.write(uploaded_file.read()) 94 | tmp_file_path = tmp_file.name 95 | 96 | # Load and split the PDF 97 | loader = PyPDFLoader(tmp_file_path) 98 | pages = loader.load_and_split() 99 | 100 | text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=40) 101 | docs = text_splitter.split_documents(pages) 102 | 103 | lc_docs = [] 104 | for doc in docs: 105 | lc_docs.append(Document(page_content=doc.page_content.replace("\n", ""), 106 | metadata={'source': uploaded_file.name})) 107 | 108 | # Clear the graph database 109 | cypher = """ 110 | MATCH (n) 111 | DETACH DELETE n; 112 | """ 113 | graph.query(cypher) 114 | 115 | # Define allowed nodes and relationships 116 | allowed_nodes = ["Patient", "Disease", "Medication", "Test", "Symptom", "Doctor"] 117 | allowed_relationships = ["HAS_DISEASE", "TAKES_MEDICATION", "UNDERWENT_TEST", "HAS_SYMPTOM", "TREATED_BY"] 118 | 119 | # Transform documents into graph documents 120 | transformer = LLMGraphTransformer( 121 | llm=llm, 122 | allowed_nodes=allowed_nodes, 123 | allowed_relationships=allowed_relationships, 124 | node_properties=False, 125 | relationship_properties=False 126 | ) 127 | 128 | graph_documents = transformer.convert_to_graph_documents(lc_docs) 129 | graph.add_graph_documents(graph_documents, include_source=True) 130 | 131 | # Use the stored connection parameters 132 | index = Neo4jVector.from_existing_graph( 133 | embedding=embeddings, 134 | url=neo4j_url, 135 | username=neo4j_username, 136 | password=neo4j_password, 137 | database="neo4j", 138 | node_label="Patient", # Adjust node_label as needed 139 | text_node_properties=["id", "text"], 140 | embedding_node_property="embedding", 141 | index_name="vector_index", 142 | keyword_index_name="entity_index", 143 | search_type="hybrid" 144 | ) 145 | 146 | st.success(f"{uploaded_file.name} preparation is complete.") 147 | 148 | # Retrieve the graph schema 149 | schema = graph.get_schema 150 | 151 | # Set up the QA chain 152 | template = """ 153 | Task: Generate a Cypher statement to query the graph database. 154 | 155 | Instructions: 156 | Use only relationship types and properties provided in schema. 157 | Do not use other relationship types or properties that are not provided. 158 | 159 | schema: 160 | {schema} 161 | 162 | Note: Do not include explanations or apologies in your answers. 163 | Do not answer questions that ask anything other than creating Cypher statements. 164 | Do not include any text other than generated Cypher statements. 165 | 166 | Question: {question}""" 167 | 168 | question_prompt = PromptTemplate( 169 | template=template, 170 | input_variables=["schema", "question"] 171 | ) 172 | 173 | qa = GraphCypherQAChain.from_llm( 174 | llm=llm, 175 | graph=graph, 176 | cypher_prompt=question_prompt, 177 | verbose=True, 178 | allow_dangerous_requests=True 179 | ) 180 | st.session_state['qa'] = qa 181 | else: 182 | st.warning("Please connect to the Neo4j database before you can upload a PDF.") 183 | 184 | if 'qa' in st.session_state: 185 | st.subheader("Ask a Question") 186 | with st.form(key='question_form'): 187 | question = st.text_input("Enter your question:") 188 | submit_button = st.form_submit_button(label='Submit') 189 | 190 | if submit_button and question: 191 | with st.spinner("Generating answer..."): 192 | res = st.session_state['qa'].invoke({"query": question}) 193 | st.write("\n**Answer:**\n" + res['result']) 194 | 195 | if __name__ == "__main__": 196 | main() 197 | 198 | 199 | 200 | --------------------------------------------------------------------------------