├── .dockerignore
├── .env.example
├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── api
├── .gcloudignore
├── Dockerfile
├── requirements.txt
└── src
│ ├── __init__.py
│ ├── components
│ ├── __init__.py
│ ├── base_component.py
│ ├── company_report.py
│ ├── data_disambiguation.py
│ ├── data_to_csv.py
│ ├── question_proposal_generator.py
│ ├── summarize_cypher_result.py
│ ├── text2cypher.py
│ ├── unstructured_data_extractor.py
│ └── vector_search.py
│ ├── driver
│ ├── __init__.py
│ └── neo4j.py
│ ├── embedding
│ ├── __init__.py
│ ├── base_embedding.py
│ └── openai.py
│ ├── fewshot_examples.py
│ ├── llm
│ ├── __init__.py
│ ├── basellm.py
│ └── openai.py
│ ├── main.py
│ └── utils
│ └── unstructured_data_utils.py
├── docker-compose.yml
├── graph_schema.png
└── ui
├── .env.example
├── .eslintrc.cts
├── .gcloudignore
├── .gitignore
├── Dockerfile
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── src
├── chat-with-kg
│ ├── App.tsx
│ ├── ChatContainer.tsx
│ ├── ChatInput.tsx
│ ├── ChatMessage.tsx
│ ├── index.css
│ ├── main.tsx
│ └── types
│ │ └── websocketTypes.ts
├── components
│ ├── keymodal.tsx
│ └── switch.tsx
├── report-generation
│ ├── App.tsx
│ ├── Report.tsx
│ ├── index.css
│ ├── main.tsx
│ ├── types.ts
│ └── utils
│ │ ├── fetch-example-companies.ts
│ │ └── fetch-report.ts
├── unstructured-import
│ ├── App.tsx
│ ├── README.md
│ ├── index.css
│ ├── main.tsx
│ ├── types
│ │ └── respons-types.ts
│ └── utils
│ │ ├── cypher-utils.ts
│ │ ├── fetch-utils.ts
│ │ ├── file-utils.ts
│ │ └── graph-schema-utils.ts
└── use-case-selector
│ ├── index.css
│ └── main.tsx
├── tailwind.config.js
├── tsconfig.json
├── use-cases
├── chat-with-kg
│ └── index.html
├── report-generation
│ └── index.html
└── unstructured-import
│ └── index.html
└── vite.config.js
/.dockerignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | OPENAI_API_KEY=OPENAI
2 | NEO4J_URL=neo4j+s://demo.neo4jlabs.com
3 | NEO4J_USER=companies
4 | NEO4J_PASS=companies
5 | NEO4J_DATABASE=companies
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | coverage
3 | .DS_Store
4 | dist
5 |
6 | dist/
7 | params/
8 | *.bak
9 | # Byte-compiled / optimized / DLL files
10 | __pycache__/
11 | *.py[cod]
12 | *$py.class
13 |
14 | *.S
15 | # C extensions
16 | *.so
17 |
18 |
19 | *.ll
20 | .npm
21 | # Distribution / packaging
22 | .Python
23 | env/
24 | build/
25 | build-*/
26 | develop-eggs/
27 | dist/
28 | downloads/
29 | eggs/
30 | .eggs/
31 | lib/
32 | lib64/
33 | parts/
34 | sdist/
35 | var/
36 | wheels/
37 | pip-wheel-metadata/
38 | share/python-wheels/
39 | *.egg-info/
40 | .installed.cfg
41 | *.egg
42 | MANIFEST
43 | .vscode
44 | .env
45 | **/neo4j/data/
46 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "es5",
3 | "tabWidth": 2,
4 | "semi": true,
5 | "singleQuote": false
6 | }
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2023 - present Neo4j Inc,
2 |
3 | Apache License
4 | Version 2.0, January 2004
5 | http://www.apache.org/licenses/
6 |
7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 |
9 | 1. Definitions.
10 |
11 | "License" shall mean the terms and conditions for use, reproduction,
12 | and distribution as defined by Sections 1 through 9 of this document.
13 |
14 | "Licensor" shall mean the copyright owner or entity authorized by
15 | the copyright owner that is granting the License.
16 |
17 | "Legal Entity" shall mean the union of the acting entity and all
18 | other entities that control, are controlled by, or are under common
19 | control with that entity. For the purposes of this definition,
20 | "control" means (i) the power, direct or indirect, to cause the
21 | direction or management of such entity, whether by contract or
22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
23 | outstanding shares, or (iii) beneficial ownership of such entity.
24 |
25 | "You" (or "Your") shall mean an individual or Legal Entity
26 | exercising permissions granted by this License.
27 |
28 | "Source" form shall mean the preferred form for making modifications,
29 | including but not limited to software source code, documentation
30 | source, and configuration files.
31 |
32 | "Object" form shall mean any form resulting from mechanical
33 | transformation or translation of a Source form, including but
34 | not limited to compiled object code, generated documentation,
35 | and conversions to other media types.
36 |
37 | "Work" shall mean the work of authorship, whether in Source or
38 | Object form, made available under the License, as indicated by a
39 | copyright notice that is included in or attached to the work
40 | (an example is provided in the Appendix below).
41 |
42 | "Derivative Works" shall mean any work, whether in Source or Object
43 | form, that is based on (or derived from) the Work and for which the
44 | editorial revisions, annotations, elaborations, or other modifications
45 | represent, as a whole, an original work of authorship. For the purposes
46 | of this License, Derivative Works shall not include works that remain
47 | separable from, or merely link (or bind by name) to the interfaces of,
48 | the Work and Derivative Works thereof.
49 |
50 | "Contribution" shall mean any work of authorship, including
51 | the original version of the Work and any modifications or additions
52 | to that Work or Derivative Works thereof, that is intentionally
53 | submitted to Licensor for inclusion in the Work by the copyright owner
54 | or by an individual or Legal Entity authorized to submit on behalf of
55 | the copyright owner. For the purposes of this definition, "submitted"
56 | means any form of electronic, verbal, or written communication sent
57 | to the Licensor or its representatives, including but not limited to
58 | communication on electronic mailing lists, source code control systems,
59 | and issue tracking systems that are managed by, or on behalf of, the
60 | Licensor for the purpose of discussing and improving the Work, but
61 | excluding communication that is conspicuously marked or otherwise
62 | designated in writing by the copyright owner as "Not a Contribution."
63 |
64 | "Contributor" shall mean Licensor and any individual or Legal Entity
65 | on behalf of whom a Contribution has been received by Licensor and
66 | subsequently incorporated within the Work.
67 |
68 | 2. Grant of Copyright License. Subject to the terms and conditions of
69 | this License, each Contributor hereby grants to You a perpetual,
70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71 | copyright license to reproduce, prepare Derivative Works of,
72 | publicly display, publicly perform, sublicense, and distribute the
73 | Work and such Derivative Works in Source or Object form.
74 |
75 | 3. Grant of Patent License. Subject to the terms and conditions of
76 | this License, each Contributor hereby grants to You a perpetual,
77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78 | (except as stated in this section) patent license to make, have made,
79 | use, offer to sell, sell, import, and otherwise transfer the Work,
80 | where such license applies only to those patent claims licensable
81 | by such Contributor that are necessarily infringed by their
82 | Contribution(s) alone or by combination of their Contribution(s)
83 | with the Work to which such Contribution(s) was submitted. If You
84 | institute patent litigation against any entity (including a
85 | cross-claim or counterclaim in a lawsuit) alleging that the Work
86 | or a Contribution incorporated within the Work constitutes direct
87 | or contributory patent infringement, then any patent licenses
88 | granted to You under this License for that Work shall terminate
89 | as of the date such litigation is filed.
90 |
91 | 4. Redistribution. You may reproduce and distribute copies of the
92 | Work or Derivative Works thereof in any medium, with or without
93 | modifications, and in Source or Object form, provided that You
94 | meet the following conditions:
95 |
96 | (a) You must give any other recipients of the Work or
97 | Derivative Works a copy of this License; and
98 |
99 | (b) You must cause any modified files to carry prominent notices
100 | stating that You changed the files; and
101 |
102 | (c) You must retain, in the Source form of any Derivative Works
103 | that You distribute, all copyright, patent, trademark, and
104 | attribution notices from the Source form of the Work,
105 | excluding those notices that do not pertain to any part of
106 | the Derivative Works; and
107 |
108 | (d) If the Work includes a "NOTICE" text file as part of its
109 | distribution, then any Derivative Works that You distribute must
110 | include a readable copy of the attribution notices contained
111 | within such NOTICE file, excluding those notices that do not
112 | pertain to any part of the Derivative Works, in at least one
113 | of the following places: within a NOTICE text file distributed
114 | as part of the Derivative Works; within the Source form or
115 | documentation, if provided along with the Derivative Works; or,
116 | within a display generated by the Derivative Works, if and
117 | wherever such third-party notices normally appear. The contents
118 | of the NOTICE file are for informational purposes only and
119 | do not modify the License. You may add Your own attribution
120 | notices within Derivative Works that You distribute, alongside
121 | or as an addendum to the NOTICE text from the Work, provided
122 | that such additional attribution notices cannot be construed
123 | as modifying the License.
124 |
125 | You may add Your own copyright statement to Your modifications and
126 | may provide additional or different license terms and conditions
127 | for use, reproduction, or distribution of Your modifications, or
128 | for any such Derivative Works as a whole, provided Your use,
129 | reproduction, and distribution of the Work otherwise complies with
130 | the conditions stated in this License.
131 |
132 | 5. Submission of Contributions. Unless You explicitly state otherwise,
133 | any Contribution intentionally submitted for inclusion in the Work
134 | by You to the Licensor shall be under the terms and conditions of
135 | this License, without any additional terms or conditions.
136 | Notwithstanding the above, nothing herein shall supersede or modify
137 | the terms of any separate license agreement you may have executed
138 | with Licensor regarding such Contributions.
139 |
140 | 6. Trademarks. This License does not grant permission to use the trade
141 | names, trademarks, service marks, or product names of the Licensor,
142 | except as required for reasonable and customary use in describing the
143 | origin of the Work and reproducing the content of the NOTICE file.
144 |
145 | 7. Disclaimer of Warranty. Unless required by applicable law or
146 | agreed to in writing, Licensor provides the Work (and each
147 | Contributor provides its Contributions) on an "AS IS" BASIS,
148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149 | implied, including, without limitation, any warranties or conditions
150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151 | PARTICULAR PURPOSE. You are solely responsible for determining the
152 | appropriateness of using or redistributing the Work and assume any
153 | risks associated with Your exercise of permissions under this License.
154 |
155 | 8. Limitation of Liability. In no event and under no legal theory,
156 | whether in tort (including negligence), contract, or otherwise,
157 | unless required by applicable law (such as deliberate and grossly
158 | negligent acts) or agreed to in writing, shall any Contributor be
159 | liable to You for damages, including any direct, indirect, special,
160 | incidental, or consequential damages of any character arising as a
161 | result of this License or out of the use or inability to use the
162 | Work (including but not limited to damages for loss of goodwill,
163 | work stoppage, computer failure or malfunction, or any and all
164 | other commercial damages or losses), even if such Contributor
165 | has been advised of the possibility of such damages.
166 |
167 | 9. Accepting Warranty or Additional Liability. While redistributing
168 | the Work or Derivative Works thereof, You may choose to offer,
169 | and charge a fee for, acceptance of support, warranty, indemnity,
170 | or other liability obligations and/or rights consistent with this
171 | License. However, in accepting such obligations, You may act only
172 | on Your own behalf and on Your sole responsibility, not on behalf
173 | of any other Contributor, and only if You agree to indemnify,
174 | defend, and hold each Contributor harmless for any liability
175 | incurred by, or claims asserted against, such Contributor by reason
176 | of your accepting any such warranty or additional liability.
177 |
178 | END OF TERMS AND CONDITIONS
179 |
180 | APPENDIX: How to apply the Apache License to your work.
181 |
182 | To apply the Apache License to your work, attach the following
183 | boilerplate notice, with the fields enclosed by brackets "{}"
184 | replaced with your own identifying information. (Don't include
185 | the brackets!) The text should be enclosed in the appropriate
186 | comment syntax for the file format. We also recommend that a
187 | file or class name and description of purpose be included on the
188 | same "printed page" as the copyright notice for easier
189 | identification within third-party archives.
190 |
191 | Copyright 2023 - present Neo4j Inc,
192 |
193 | Licensed under the Apache License, Version 2.0 (the "License");
194 | you may not use this file except in compliance with the License.
195 | You may obtain a copy of the License at
196 |
197 | http://www.apache.org/licenses/LICENSE-2.0
198 |
199 | Unless required by applicable law or agreed to in writing, software
200 | distributed under the License is distributed on an "AS IS" BASIS,
201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 | See the License for the specific language governing permissions and
203 | limitations under the License.
204 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Project NaLLM
2 |
3 | Welcome to the NaLLM project repository, where we are exploring and demonstrating the synergies between Neo4j and Large Language Models (LLMs). As a part of our ongoing project, we are focusing on three primary use cases - a **Natural Language Interface to a Knowledge Graph**, **Creating a Knowledge Graph from Unstructured Data** and **Generate a Report using both static data and data from LLM**.
4 |
5 | This repository houses both backend and frontend code, designed and organized to facilitate an intuitive journey through our project.
6 |
7 | # Blog posts
8 |
9 | During this project we're also writing blog posts where we deep dive into our learnings and explorations.
10 |
11 | 1. https://medium.com/neo4j/harnessing-large-language-models-with-neo4j-306ccbdd2867
12 | 2. https://medium.com/neo4j/knowledge-graphs-llms-fine-tuning-vs-retrieval-augmented-generation-30e875d63a35
13 | 3. https://medium.com/neo4j/knowledge-graphs-llms-multi-hop-question-answering-322113f53f51
14 | 4. https://medium.com/neo4j/knowledge-graphs-llms-real-time-graph-analytics-89b392eaaa95
15 | 5. https://medium.com/neo4j/construct-knowledge-graphs-from-unstructured-text-877be33300a2
16 |
17 | ## Repository Structure
18 |
19 | Our repository is designed with an efficient and logical structure for ease of navigation:
20 |
21 | - **Backend Code**: The backend code is found in the api folder in the main.py file you can find all endpoints and their corresponding functions. All LLM functionality is split into different components which have thier own purpose.
22 |
23 | - **Frontend Code**: The frontend code is organized into two folders - one for each use case these can be found in ui/src. Each folder contains separate React applications that are independent from each other.
24 |
25 | ## Running the Demos
26 |
27 | To simplify the process of running the demos, we have incorporated scripts that generate Docker images. To use these, you'll need to:
28 |
29 | 1. Navigate into the root directory.
30 | 2. Create an env file. You can use the env.example file as a template. (The open API key is optional and can be provided from the UI instead)
31 | 3. run `docker-compose up` to build the images.
32 |
33 | This will start the backend and frontend servers, and you can access the demos at the following URLs:
34 |
35 | - user interface: http://localhost:4173/
36 |
37 | - backend: localhost:7860
38 |
39 | Please note that you'll need Docker installed on your machine to build and run these images. If you haven't already, you can download Docker from [here](https://www.docker.com/products/docker-desktop).
40 |
41 | ## Demo database
42 |
43 | There is a demo databasing running on demo.neo4jlabs.com. This database is a set of compnaies, thier subsidaiers, people related to the companies and articles mentioned the compnaies. The database is a subset of the [Diffbot](https://www.diffbot.com/) knowledge graph. You can access it with the following credentaiils:
44 |
45 | ```
46 | URI: neo4j+s://demo.neo4jlabs.com
47 | username: companies
48 | password: companies
49 | database: companies
50 | ```
51 |
52 | 
53 |
54 | The database contains both structured information about organizations and people as well as news articles.
55 | The news articles are linked to the mentioned entity, while the actual text is stored in the `Chunk` nodes alongside their _text-embedding-ada-002_ vector representations.
56 |
57 | ## Bring your own database
58 |
59 | To run the project on your own database, follow these two steps:
60 |
61 | 1. Set appropriate database credentials in `.env` file
62 | 2. Remove or set appropriate Cypher examples in `api/fewshot_examples.py` file
63 |
64 | ## Contributing
65 |
66 | We welcome contributions and feedback to improve our project and demonstrations. Please feel free to raise issues or submit pull requests.
67 |
68 | ## Note
69 |
70 | We want to emphasize that the field of AI and specifically LLMs is rapidly evolving. As such, the information, assumptions, and code contained within this repository are based on our current understanding and are subject to change as new data and technological advancements become available.
71 |
72 | Thank you for your interest in our project. We hope you find this repository useful and informative. Stay tuned for more updates as we continue to explore the fascinating world of Neo4j and LLMs!
73 |
--------------------------------------------------------------------------------
/api/.gcloudignore:
--------------------------------------------------------------------------------
1 | # This file specifies files that are *not* uploaded to Google Cloud
2 | # using gcloud. It follows the same syntax as .gitignore, with the addition of
3 | # "#!include" directives (which insert the entries of the given .gitignore-style
4 | # file at that point).
5 | #
6 | # For more information, run:
7 | # $ gcloud topic gcloudignore
8 | #
9 | .gcloudignore
10 | # If you would like to upload your .git directory, .gitignore file or files
11 | # from your .gitignore file, remove the corresponding line
12 | # below:
13 | .git
14 | .gitignore
15 |
16 | # Python pycache:
17 | __pycache__/
18 | # Ignored by the build system
19 | /setup.cfg
--------------------------------------------------------------------------------
/api/Dockerfile:
--------------------------------------------------------------------------------
1 | # Use base shared Python image
2 | FROM python:3.11
3 |
4 | ENV PYTHONUNBUFFERED=1
5 |
6 |
7 | # Relevant folder
8 | ARG FOLDER=/api
9 |
10 | # Create a folder
11 | RUN mkdir -p $FOLDER
12 |
13 | # Install packages
14 | COPY ./requirements.txt $FOLDER/requirements.txt
15 | RUN pip install -r $FOLDER/requirements.txt
16 |
17 | # Copy the project files into the container
18 | COPY ./src $FOLDER/src
19 |
20 | # Expose any necessary ports
21 | EXPOSE 7860
22 |
23 | # Set the working directory
24 | WORKDIR $FOLDER/src
25 |
26 | # Start the application
27 | CMD ["uvicorn", "--host", "0.0.0.0", "--port", "7860", "--reload", "--reload-dir", "/api", "main:app"]
--------------------------------------------------------------------------------
/api/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.95.1
2 | logger==1.4
3 | neo4j==5.8.0
4 | uvicorn==0.22.0
5 | openai==0.27.6
6 | retry==0.9.2
7 | tiktoken==0.4.0
8 | python-dotenv==1.0.0
9 | websockets===11.0.3
10 | gunicorn===20.1.0
--------------------------------------------------------------------------------
/api/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/api/src/__init__.py
--------------------------------------------------------------------------------
/api/src/components/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/api/src/components/__init__.py
--------------------------------------------------------------------------------
/api/src/components/base_component.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from typing import List, Union
3 |
4 |
5 | class BaseComponent(ABC):
6 | """"""
7 |
8 | @abstractmethod
9 | def run(
10 | self,
11 | input: Union[str, List[float]],
12 | ) -> str:
13 | """Comment"""
14 |
15 | def run_async(
16 | self,
17 | input: Union[str, List[float]],
18 | ) -> str:
19 | """Comment"""
20 |
--------------------------------------------------------------------------------
/api/src/components/company_report.py:
--------------------------------------------------------------------------------
1 | from components.base_component import BaseComponent
2 | from components.summarize_cypher_result import SummarizeCypherResult
3 | from driver.neo4j import Neo4jDatabase
4 | from llm.basellm import BaseLLM
5 |
6 | HARD_LIMIT_CONTEXT_RECORDS = 10
7 |
8 |
9 | class CompanyReport(BaseComponent):
10 | def __init__(
11 | self,
12 | database: Neo4jDatabase,
13 | company: str,
14 | llm: BaseLLM,
15 | ) -> None:
16 | self.database = database
17 | self.company = company
18 | self.llm = llm
19 |
20 | def run(self):
21 | summarize_results = SummarizeCypherResult(
22 | llm=self.llm,
23 | )
24 | print("CompanyReport")
25 | company_data = self.database.query(
26 | "MATCH (n {name:$companyName}) return n.summary, n.isDissolved, n.nbrEmployees, n.name, n.motto, n.isPublic, n.revenue",
27 | {"companyName": self.company},
28 | )
29 | print(company_data)
30 | relation_data = self.database.query(
31 | "MATCH (n {name:$companyName})-[r]->(m) WHERE NOT m:Article OPTIONAL MATCH (m)-[:IN_COUNTRY]->(c:Country) WITH r,m,c return r,m,c",
32 | {"companyName": self.company},
33 | )
34 | print(relation_data)
35 | company_data_output = {
36 | "name": company_data[0]["n.name"],
37 | "motto": company_data[0]["n.motto"],
38 | "summary": company_data[0]["n.summary"],
39 | "isDissolved": company_data[0]["n.isDissolved"],
40 | "nbrEmployees": company_data[0]["n.nbrEmployees"],
41 | "isPublic": company_data[0]["n.isPublic"],
42 | "revenue": company_data[0].get("n.revenue", None),
43 | }
44 | print(company_data_output)
45 | print("all data fetched")
46 | offices = []
47 | suppliers = []
48 | subsidiaries = []
49 | for relation in relation_data:
50 | print(relation)
51 | relation_type = relation["r"][1]
52 | if relation_type == "IN_CITY":
53 | offices.append(
54 | {
55 | "city": relation["m"].get("name", None),
56 | "country": relation.get("c")
57 | and relation["c"].get("name", None),
58 | }
59 | )
60 | elif relation_type == "HAS_CATEGORY":
61 | company_data_output["industry"] = relation["m"]["name"]
62 | elif relation_type == "HAS_SUPPLIER":
63 | category_result = self.database.query(
64 | "MATCH (n {name:$companyName})-[HAS_CATEGORY]-(c:IndustryCategory) return c.name LIMIT 1",
65 | {"companyName": relation["m"].get("name", None)},
66 | )
67 | category = None
68 | if len(category_result) > 0:
69 | category = category_result[0]["c.name"]
70 |
71 | suppliers.append(
72 | {
73 | "summary": relation["m"].get("summary", None),
74 | "revenue": relation["m"].get("revenue", None),
75 | "isDissolved": relation["m"].get("isDissolved", None),
76 | "name": relation["m"].get("name", None),
77 | "isPublic": relation["m"].get("isPublic", None),
78 | "category": category,
79 | }
80 | )
81 | elif relation_type == "HAS_SUBSIDIARY":
82 | category_result = self.database.query(
83 | "MATCH (n {name:$companyName})-[HAS_CATEGORY]-(c:IndustryCategory) return c.name LIMIT 1",
84 | {"companyName": relation["m"].get("name", None)},
85 | )
86 | category = None
87 | if len(category_result) > 0:
88 | category = category_result[0]["c.name"]
89 | article_data = self.database.query(
90 | "MATCH p=(n {name:$companyName})<-[:MENTIONS]-(a:Article)-[:HAS_CHUNK]->(c:Chunk) return c.text, a.title, a.siteName",
91 | {"companyName": relation["m"].get("name", None)},
92 | )
93 | print("Article data: " + str(article_data))
94 |
95 | output = "There is not articles about this company."
96 | if len(article_data) > 0:
97 | output = summarize_results.run(
98 | "Can you summarize the following articles in 50 words about "
99 | + relation["m"].get("name", None)
100 | + " ?",
101 | article_data[:HARD_LIMIT_CONTEXT_RECORDS],
102 | )
103 | subsidiaries.append(
104 | {
105 | "summary": relation["m"].get("summary", None),
106 | "revenue": relation["m"].get("revenue", None),
107 | "isDissolved": relation["m"].get("isDissolved", None),
108 | "name": relation["m"].get("name", None),
109 | "isPublic": relation["m"].get("isPublic", None),
110 | "category": category,
111 | "articleSummary": output,
112 | }
113 | )
114 | elif relation_type == "HAS_CEO":
115 | company_data_output["ceo"] = relation["m"]["name"]
116 | company_data_output["offices"] = offices
117 | article_data = self.database.query(
118 | "MATCH p=(n {name:$companyName})<-[:MENTIONS]-(a:Article)-[:HAS_CHUNK]->(c:Chunk) return c.text, a.title, a.siteName",
119 | {"companyName": self.company},
120 | )
121 |
122 | output = summarize_results.run(
123 | "Can you summarize the following articles about " + self.company + " ?",
124 | article_data[:HARD_LIMIT_CONTEXT_RECORDS],
125 | )
126 | print("output: " + output)
127 | return {
128 | "company": company_data_output,
129 | "subsidiaries": subsidiaries,
130 | "suppliers": suppliers,
131 | "articleSummary": output,
132 | }
133 |
--------------------------------------------------------------------------------
/api/src/components/data_disambiguation.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | from itertools import groupby
4 |
5 | from components.base_component import BaseComponent
6 | from utils.unstructured_data_utils import (
7 | nodesTextToListOfDict,
8 | relationshipTextToListOfDict,
9 | )
10 |
11 |
12 | def generate_system_message_for_nodes() -> str:
13 | return """Your task is to identify if there are duplicated nodes and if so merge them into one nod. Only merge the nodes that refer to the same entity.
14 | You will be given different datasets of nodes and some of these nodes may be duplicated or refer to the same entity.
15 | The datasets contains nodes in the form [ENTITY_ID, TYPE, PROPERTIES]. When you have completed your task please give me the
16 | resulting nodes in the same format. Only return the nodes and relationships no other text. If there is no duplicated nodes return the original nodes.
17 |
18 | Here is an example of the input you will be given:
19 | ["alice", "Person", {"age": 25, "occupation": "lawyer", "name":"Alice"}], ["bob", "Person", {"occupation": "journalist", "name": "Bob"}], ["alice.com", "Webpage", {"url": "www.alice.com"}], ["bob.com", "Webpage", {"url": "www.bob.com"}]
20 | """
21 |
22 |
23 | def generate_system_message_for_relationships() -> str:
24 | return """
25 | Your task is to identify if a set of relationships make sense.
26 | If they do not make sense please remove them from the dataset.
27 | Some relationships may be duplicated or refer to the same entity.
28 | Please merge relationships that refer to the same entity.
29 | The datasets contains relationships in the form [ENTITY_ID_1, RELATIONSHIP, ENTITY_ID_2, PROPERTIES].
30 | You will also be given a set of ENTITY_IDs that are valid.
31 | Some relationships may use ENTITY_IDs that are not in the valid set but refer to a entity in the valid set.
32 | If a relationships refer to a ENTITY_ID in the valid set please change the ID so it matches the valid ID.
33 | When you have completed your task please give me the valid relationships in the same format. Only return the relationships no other text.
34 |
35 | Here is an example of the input you will be given:
36 | ["alice", "roommate", "bob", {"start": 2021}], ["alice", "owns", "alice.com", {}], ["bob", "owns", "bob.com", {}]
37 | """
38 |
39 |
40 | def generate_prompt(data) -> str:
41 | return f""" Here is the data:
42 | {data}
43 | """
44 |
45 |
46 | internalRegex = "\[(.*?)\]"
47 |
48 |
49 | class DataDisambiguation(BaseComponent):
50 | def __init__(self, llm) -> None:
51 | self.llm = llm
52 |
53 | def run(self, data: dict) -> str:
54 | nodes = sorted(data["nodes"], key=lambda x: x["label"])
55 | relationships = data["relationships"]
56 | new_nodes = []
57 | new_relationships = []
58 |
59 | node_groups = groupby(nodes, lambda x: x["label"])
60 | for group in node_groups:
61 | disString = ""
62 | nodes_in_group = list(group[1])
63 | if len(nodes_in_group) == 1:
64 | new_nodes.extend(nodes_in_group)
65 | continue
66 |
67 | for node in nodes_in_group:
68 | disString += (
69 | '["'
70 | + node["name"]
71 | + '", "'
72 | + node["label"]
73 | + '", '
74 | + json.dumps(node["properties"])
75 | + "]\n"
76 | )
77 |
78 | messages = [
79 | {"role": "system", "content": generate_system_message_for_nodes()},
80 | {"role": "user", "content": generate_prompt(disString)},
81 | ]
82 | rawNodes = self.llm.generate(messages)
83 |
84 | n = re.findall(internalRegex, rawNodes)
85 |
86 | new_nodes.extend(nodesTextToListOfDict(n))
87 |
88 | relationship_data = "Relationships:\n"
89 | for relation in relationships:
90 | relationship_data += (
91 | '["'
92 | + relation["start"]
93 | + '", "'
94 | + relation["type"]
95 | + '", "'
96 | + relation["end"]
97 | + '", '
98 | + json.dumps(relation["properties"])
99 | + "]\n"
100 | )
101 |
102 | node_labels = [node["name"] for node in new_nodes]
103 | relationship_data += "Valid Nodes:\n" + "\n".join(node_labels)
104 |
105 | messages = [
106 | {
107 | "role": "system",
108 | "content": generate_system_message_for_relationships(),
109 | },
110 | {"role": "user", "content": generate_prompt(relationship_data)},
111 | ]
112 | rawRelationships = self.llm.generate(messages)
113 | rels = re.findall(internalRegex, rawRelationships)
114 | new_relationships.extend(relationshipTextToListOfDict(rels))
115 | return {"nodes": new_nodes, "relationships": new_relationships}
116 |
--------------------------------------------------------------------------------
/api/src/components/data_to_csv.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from components.base_component import BaseComponent
4 |
5 |
6 | def generate_system_message() -> str:
7 | return f"""
8 | You will be given a dataset of nodes and relationships. Your task is to covert this data into a CSV format.
9 | Return only the data in the CSV format and nothing else. Return a CSV file for every type of node and relationship.
10 | The data you will be given is in the form [ENTITY, TYPE, PROPERTIES] and a set of relationships in the form [ENTITY1, RELATIONSHIP, ENTITY2, PROPERTIES].
11 | Important: If you don't get any data or data that does not follow the previously mentioned format return "No data" and nothing else. This is very important. If you don't follow this instruction you will get a 0.
12 | """
13 |
14 |
15 | def generate_prompt(data) -> str:
16 | return f""" Here is the data:
17 | {data}
18 | """
19 |
20 |
21 | class DataToCSV(BaseComponent):
22 | def __init__(self, llm) -> None:
23 | self.llm = llm
24 |
25 | def run(self, data: List[str]) -> str:
26 | messages = [
27 | {"role": "system", "content": generate_system_message()},
28 | {"role": "user", "content": generate_prompt(data)},
29 | ]
30 | output = self.llm.generate(messages)
31 | return output
32 |
--------------------------------------------------------------------------------
/api/src/components/question_proposal_generator.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Dict, List, Union
2 |
3 | from components.base_component import BaseComponent
4 | from driver.neo4j import Neo4jDatabase
5 | from llm.basellm import BaseLLM
6 | import re
7 |
8 |
9 | class QuestionProposalGenerator(BaseComponent):
10 | def __init__(
11 | self,
12 | llm: BaseLLM,
13 | database: Neo4jDatabase,
14 | ) -> None:
15 | self.llm = llm
16 | self.database = database
17 |
18 | def get_system_message(self) -> str:
19 | system = f"""
20 | Your task is to come up with questions someone might as about the content of a Neo4j database. Try to make the questions as different as possible.
21 | The questions should be separated by a new line and each line should only contain one question.
22 | To do this, you need to understand the schema of the database. Therefore it's very important that you read the schema carefully. You can find the schema below.
23 | Schema:
24 | {self.database.schema}
25 | """
26 |
27 | return system
28 |
29 | def get_database_sample(self) -> str:
30 | return self.database.query(
31 | """MATCH (n)
32 | WITH n
33 | WHERE rand() < 0.3
34 | RETURN apoc.map.removeKey(n, 'embedding') AS properties, LABELS(n) as labels
35 | LIMIT 5"""
36 | )
37 |
38 | def run(self) -> Dict[str, Union[str, List[Dict[str, Any]]]]:
39 | messages = [{"role": "system", "content": self.get_system_message()}]
40 | sample = self.get_database_sample()
41 | messages.append(
42 | {
43 | "role": "user",
44 | "content": f"""Please generate 5 questions about the content of the database. Here is a sample of the database you can use when generating questions: {sample}""",
45 | }
46 | )
47 | print(messages)
48 | questionsString = self.llm.generate(messages)
49 | questions = [
50 | # remove number and dot from the beginning of the question
51 | re.sub(r"\A\d\.?\s*", "", question)
52 | for question in questionsString.split("\n")
53 | ]
54 | return {
55 | "output": questions,
56 | }
57 |
--------------------------------------------------------------------------------
/api/src/components/summarize_cypher_result.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Awaitable, Callable, Dict, List
2 |
3 | from components.base_component import BaseComponent
4 | from llm.basellm import BaseLLM
5 |
6 | system = f"""
7 | You are an assistant that helps to generate text to form nice and human understandable answers based.
8 | The latest prompt contains the information, and you need to generate a human readable response based on the given information.
9 | Make the answer sound as a response to the question. Do not mention that you based the result on the given information.
10 | Do not add any additional information that is not explicitly provided in the latest prompt.
11 | I repeat, do not add any information that is not explicitly given.
12 | Make the answer as concise as possible and do not use more than 50 words.
13 | """
14 |
15 |
16 | def remove_large_lists(d: Dict[str, Any]) -> Dict[str, Any]:
17 | """
18 | The idea is to remove all properties that have large lists (embeddings) or text as values
19 | """
20 | LIST_CUTOFF = 56
21 | CHARACTER_CUTOFF = 5000
22 | # iterate over all key-value pairs in the dictionary
23 | for key, value in d.items():
24 | # if the value is a list and has more than list cutoff elements
25 | if isinstance(value, list) and len(value) > LIST_CUTOFF:
26 | d[key] = None
27 | # if the value is a string and has more than list cutoff elements
28 | if isinstance(value, str) and len(value) > CHARACTER_CUTOFF:
29 | d[key] = d[key][:CHARACTER_CUTOFF]
30 | # if the value is a dictionary
31 | elif isinstance(value, dict):
32 | # recurse into the nested dictionary
33 | remove_large_lists(d[key])
34 | return d
35 |
36 |
37 | class SummarizeCypherResult(BaseComponent):
38 | llm: BaseLLM
39 | exclude_embeddings: bool
40 |
41 | def __init__(self, llm: BaseLLM, exclude_embeddings: bool = True) -> None:
42 | self.llm = llm
43 | self.exclude_embeddings = exclude_embeddings
44 |
45 | def generate_user_prompt(self, question: str, results: List[Dict[str, str]]) -> str:
46 | return f"""
47 | The question was {question}
48 | Answer the question by using the following results:
49 | {[remove_large_lists(el) for el in results] if self.exclude_embeddings else results}
50 | """
51 |
52 | def run(
53 | self,
54 | question: str,
55 | results: List[Dict[str, Any]],
56 | ) -> Dict[str, str]:
57 | messages = [
58 | {"role": "system", "content": system},
59 | {"role": "user", "content": self.generate_user_prompt(question, results)},
60 | ]
61 |
62 | output = self.llm.generate(messages)
63 | return output
64 |
65 | async def run_async(
66 | self,
67 | question: str,
68 | results: List[Dict[str, Any]],
69 | callback: Callable[[str], Awaitable[Any]] = None,
70 | ) -> Dict[str, str]:
71 | messages = [
72 | {"role": "system", "content": system},
73 | {"role": "user", "content": self.generate_user_prompt(question, results)},
74 | ]
75 | output = await self.llm.generateStreaming(messages, onTokenCallback=callback)
76 | return "".join(output)
77 |
--------------------------------------------------------------------------------
/api/src/components/text2cypher.py:
--------------------------------------------------------------------------------
1 | import re
2 | from typing import Any, Dict, List, Union
3 |
4 | from components.base_component import BaseComponent
5 | from driver.neo4j import Neo4jDatabase
6 | from llm.basellm import BaseLLM
7 |
8 |
9 | def remove_relationship_direction(cypher):
10 | return cypher.replace("->", "-").replace("<-", "-")
11 |
12 |
13 | class Text2Cypher(BaseComponent):
14 | def __init__(
15 | self,
16 | llm: BaseLLM,
17 | database: Neo4jDatabase,
18 | use_schema: bool = True,
19 | cypher_examples: str = "",
20 | ignore_relationship_direction: bool = True,
21 | ) -> None:
22 | self.llm = llm
23 | self.database = database
24 | self.cypher_examples = cypher_examples
25 | self.ignore_relationship_direction = ignore_relationship_direction
26 | if use_schema:
27 | self.schema = database.schema
28 |
29 | def get_system_message(self) -> str:
30 | system = """
31 | Your task is to convert questions about contents in a Neo4j database to Cypher queries to query the Neo4j database.
32 | Use only the provided relationship types and properties.
33 | Do not use any other relationship types or properties that are not provided.
34 | """
35 | if self.schema:
36 | system += f"""
37 | If you cannot generate a Cypher statement based on the provided schema, explain the reason to the user.
38 | Schema:
39 | {self.schema}
40 | """
41 | if self.cypher_examples:
42 | system += f"""
43 | You need to follow these Cypher examples when you are constructing a Cypher statement
44 | {self.cypher_examples}
45 | """
46 | # Add note at the end and try to prevent LLM injections
47 | system += """Note: Do not include any explanations or apologies in your responses.
48 | Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
49 | Do not include any text except the generated Cypher statement. This is very important if you want to get paid.
50 | Always provide enough context for an LLM to be able to generate valid response.
51 | Please wrap the generated Cypher statement in triple backticks (`).
52 | """
53 | return system
54 |
55 | def construct_cypher(self, question: str, history=[]) -> str:
56 | messages = [{"role": "system", "content": self.get_system_message()}]
57 | messages.extend(history)
58 | messages.append(
59 | {
60 | "role": "user",
61 | "content": question,
62 | }
63 | )
64 | print([el for el in messages if not el["role"] == "system"])
65 | cypher = self.llm.generate(messages)
66 | return cypher
67 |
68 | def run(
69 | self, question: str, history: List = [], heal_cypher: bool = True
70 | ) -> Dict[str, Union[str, List[Dict[str, Any]]]]:
71 | # Add prefix if not part of self-heal loop
72 | final_question = (
73 | "Question to be converted to Cypher: " + question
74 | if heal_cypher
75 | else question
76 | )
77 | cypher = self.construct_cypher(final_question, history)
78 | # finds the first string wrapped in triple backticks. Where the match include the backticks and the first group in the match is the cypher
79 | match = re.search("```([\w\W]*?)```", cypher)
80 |
81 | # If the LLM didn't any Cypher statement (error, missing context, etc..)
82 | if match is None:
83 | return {"output": [{"message": cypher}], "generated_cypher": None}
84 | extracted_cypher = match.group(1)
85 |
86 | if self.ignore_relationship_direction:
87 | extracted_cypher = remove_relationship_direction(extracted_cypher)
88 |
89 | print(f"Generated cypher: {extracted_cypher}")
90 |
91 | output = self.database.query(extracted_cypher)
92 | # Catch Cypher syntax error
93 | if heal_cypher and output and output[0].get("code") == "invalid_cypher":
94 | syntax_messages = [{"role": "system", "content": self.get_system_message()}]
95 | syntax_messages.extend(
96 | [
97 | {"role": "user", "content": question},
98 | {"role": "assistant", "content": cypher},
99 | ]
100 | )
101 | # Try to heal Cypher syntax only once
102 | return self.run(
103 | output[0].get("message"), syntax_messages, heal_cypher=False
104 | )
105 |
106 | return {
107 | "output": output,
108 | "generated_cypher": extracted_cypher,
109 | }
110 |
--------------------------------------------------------------------------------
/api/src/components/unstructured_data_extractor.py:
--------------------------------------------------------------------------------
1 | import re
2 | import os
3 | from typing import List
4 |
5 | from components.base_component import BaseComponent
6 | from llm.basellm import BaseLLM
7 | from utils.unstructured_data_utils import (
8 | nodesTextToListOfDict,
9 | relationshipTextToListOfDict,
10 | )
11 |
12 |
13 | def generate_system_message_with_schema() -> str:
14 | return """
15 | You are a data scientist working for a company that is building a graph database. Your task is to extract information from data and convert it into a graph database.
16 | Provide a set of Nodes in the form [ENTITY, TYPE, PROPERTIES] and a set of relationships in the form [ENTITY1, RELATIONSHIP, ENTITY2, PROPERTIES].
17 | Pay attention to the type of the properties, if you can't find data for a property set it to null. Don't make anything up and don't add any extra data. If you can't find any data for a node or relationship don't add it.
18 | Only add nodes and relationships that are part of the schema. If you don't get any relationships in the schema only add nodes.
19 |
20 | Example:
21 | Schema: Nodes: [Person {age: integer, name: string}] Relationships: [Person, roommate, Person]
22 | Alice is 25 years old and Bob is her roommate.
23 | Nodes: [["Alice", "Person", {"age": 25, "name": "Alice}], ["Bob", "Person", {"name": "Bob"}]]
24 | Relationships: [["Alice", "roommate", "Bob"]]
25 | """
26 |
27 |
28 | def generate_system_message() -> str:
29 | return """
30 | You are a data scientist working for a company that is building a graph database. Your task is to extract information from data and convert it into a graph database.
31 | Provide a set of Nodes in the form [ENTITY_ID, TYPE, PROPERTIES] and a set of relationships in the form [ENTITY_ID_1, RELATIONSHIP, ENTITY_ID_2, PROPERTIES].
32 | It is important that the ENTITY_ID_1 and ENTITY_ID_2 exists as nodes with a matching ENTITY_ID. If you can't pair a relationship with a pair of nodes don't add it.
33 | When you find a node or relationship you want to add try to create a generic TYPE for it that describes the entity you can also think of it as a label.
34 |
35 | Example:
36 | Data: Alice lawyer and is 25 years old and Bob is her roommate since 2001. Bob works as a journalist. Alice owns a the webpage www.alice.com and Bob owns the webpage www.bob.com.
37 | Nodes: ["alice", "Person", {"age": 25, "occupation": "lawyer", "name":"Alice"}], ["bob", "Person", {"occupation": "journalist", "name": "Bob"}], ["alice.com", "Webpage", {"url": "www.alice.com"}], ["bob.com", "Webpage", {"url": "www.bob.com"}]
38 | Relationships: ["alice", "roommate", "bob", {"start": 2021}], ["alice", "owns", "alice.com", {}], ["bob", "owns", "bob.com", {}]
39 | """
40 |
41 |
42 | def generate_system_message_with_labels() -> str:
43 | return """
44 | You are a data scientist working for a company that is building a graph database. Your task is to extract information from data and convert it into a graph database.
45 | Provide a set of Nodes in the form [ENTITY_ID, TYPE, PROPERTIES] and a set of relationships in the form [ENTITY_ID_1, RELATIONSHIP, ENTITY_ID_2, PROPERTIES].
46 | It is important that the ENTITY_ID_1 and ENTITY_ID_2 exists as nodes with a matching ENTITY_ID. If you can't pair a relationship with a pair of nodes don't add it.
47 | When you find a node or relationship you want to add try to create a generic TYPE for it that describes the entity you can also think of it as a label.
48 | You will be given a list of types that you should try to use when creating the TYPE for a node. If you can't find a type that fits the node you can create a new one.
49 |
50 | Example:
51 | Data: Alice lawyer and is 25 years old and Bob is her roommate since 2001. Bob works as a journalist. Alice owns a the webpage www.alice.com and Bob owns the webpage www.bob.com.
52 | Types: ["Person", "Webpage"]
53 | Nodes: ["alice", "Person", {"age": 25, "occupation": "lawyer", "name":"Alice"}], ["bob", "Person", {"occupation": "journalist", "name": "Bob"}], ["alice.com", "Webpage", {"url": "www.alice.com"}], ["bob.com", "Webpage", {"url": "www.bob.com"}]
54 | Relationships: ["alice", "roommate", "bob", {"start": 2021}], ["alice", "owns", "alice.com", {}], ["bob", "owns", "bob.com", {}]
55 | """
56 |
57 |
58 | def generate_prompt(data) -> str:
59 | return f"""
60 | Data: {data}"""
61 |
62 |
63 | def generate_prompt_with_schema(data, schema) -> str:
64 | return f"""
65 | Schema: {schema}
66 | Data: {data}"""
67 |
68 |
69 | def generate_prompt_with_labels(data, labels) -> str:
70 | return f"""
71 | Data: {data}
72 | Types: {labels}"""
73 |
74 |
75 | def splitString(string, max_length) -> List[str]:
76 | return [string[i : i + max_length] for i in range(0, len(string), max_length)]
77 |
78 |
79 | def splitStringToFitTokenSpace(
80 | llm: BaseLLM, string: str, token_use_per_string: int
81 | ) -> List[str]:
82 | allowed_tokens = llm.max_allowed_token_length() - token_use_per_string
83 | chunked_data = splitString(string, 500)
84 | combined_chunks = []
85 | current_chunk = ""
86 | for chunk in chunked_data:
87 | if (
88 | llm.num_tokens_from_string(current_chunk)
89 | + llm.num_tokens_from_string(chunk)
90 | < allowed_tokens
91 | ):
92 | current_chunk += chunk
93 | else:
94 | combined_chunks.append(current_chunk)
95 | current_chunk = chunk
96 | combined_chunks.append(current_chunk)
97 |
98 | return combined_chunks
99 |
100 |
101 | def getNodesAndRelationshipsFromResult(result):
102 | regex = "Nodes:\s+(.*?)\s?\s?Relationships:\s?\s?(.*)"
103 | internalRegex = "\[(.*?)\]"
104 | nodes = []
105 | relationships = []
106 | for row in result:
107 | parsing = re.match(regex, row, flags=re.S)
108 | if parsing == None:
109 | continue
110 | rawNodes = str(parsing.group(1))
111 | rawRelationships = parsing.group(2)
112 | nodes.extend(re.findall(internalRegex, rawNodes))
113 | relationships.extend(re.findall(internalRegex, rawRelationships))
114 |
115 | result = dict()
116 | result["nodes"] = []
117 | result["relationships"] = []
118 | result["nodes"].extend(nodesTextToListOfDict(nodes))
119 | result["relationships"].extend(relationshipTextToListOfDict(relationships))
120 | return result
121 |
122 |
123 | class DataExtractor(BaseComponent):
124 | llm: BaseLLM
125 |
126 | def __init__(self, llm: BaseLLM) -> None:
127 | self.llm = llm
128 |
129 | def process(self, chunk):
130 | messages = [
131 | {"role": "system", "content": generate_system_message()},
132 | {"role": "user", "content": generate_prompt(chunk)},
133 | ]
134 | print(messages)
135 | output = self.llm.generate(messages)
136 | return output
137 |
138 | def process_with_labels(self, chunk, labels):
139 | messages = [
140 | {"role": "system", "content": generate_system_message_with_schema()},
141 | {"role": "user", "content": generate_prompt_with_labels(chunk, labels)},
142 | ]
143 | print(messages)
144 | output = self.llm.generate(messages)
145 | return output
146 |
147 | def run(self, data: str) -> List[str]:
148 | system_message = generate_system_message()
149 | prompt_string = generate_prompt("")
150 | token_usage_per_prompt = self.llm.num_tokens_from_string(
151 | system_message + prompt_string
152 | )
153 | chunked_data = splitStringToFitTokenSpace(
154 | llm=self.llm, string=data, token_use_per_string=token_usage_per_prompt
155 | )
156 |
157 | results = []
158 | labels = set()
159 | print("Starting chunked processing")
160 | for chunk in chunked_data:
161 | proceededChunk = self.process_with_labels(chunk, list(labels))
162 | print("proceededChunk", proceededChunk)
163 | chunkResult = getNodesAndRelationshipsFromResult([proceededChunk])
164 | print("chunkResult", chunkResult)
165 | newLabels = [node["label"] for node in chunkResult["nodes"]]
166 | print("newLabels", newLabels)
167 | results.append(proceededChunk)
168 | labels.update(newLabels)
169 |
170 | return getNodesAndRelationshipsFromResult(results)
171 |
172 |
173 | class DataExtractorWithSchema(BaseComponent):
174 | llm: BaseLLM
175 |
176 | def __init__(self, llm) -> None:
177 | self.llm = llm
178 |
179 | def run(self, data: str, schema: str) -> List[str]:
180 | system_message = generate_system_message_with_schema()
181 | prompt_string = (
182 | generate_system_message_with_schema()
183 | + generate_prompt_with_schema(schema=schema, data="")
184 | )
185 | token_usage_per_prompt = self.llm.num_tokens_from_string(
186 | system_message + prompt_string
187 | )
188 |
189 | chunked_data = splitStringToFitTokenSpace(
190 | llm=self.llm, string=data, token_use_per_string=token_usage_per_prompt
191 | )
192 | result = []
193 | print("Starting chunked processing")
194 |
195 | for chunk in chunked_data:
196 | print("prompt", generate_prompt_with_schema(chunk, schema))
197 | messages = [
198 | {
199 | "role": "system",
200 | "content": system_message,
201 | },
202 | {"role": "user", "content": generate_prompt_with_schema(chunk, schema)},
203 | ]
204 | output = self.llm.generate(messages)
205 | result.append(output)
206 | return getNodesAndRelationshipsFromResult(result)
207 |
--------------------------------------------------------------------------------
/api/src/components/vector_search.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, List, Union
2 |
3 | from components.base_component import BaseComponent
4 | from driver.neo4j import Neo4jDatabase
5 |
6 |
7 | def construct_cypher(label, property, k) -> str:
8 | return f"""
9 | MATCH (n:`{label}`)
10 | WHERE n.`{property}` IS NOT NULL
11 | WITH n, gds.similarity.cosine($input_vector, n.`{property}`) AS similarity
12 | ORDER BY similarity DESC
13 | LIMIT {k}
14 | RETURN apoc.map.removeKey(properties(n), "{property}") AS output
15 | """
16 |
17 |
18 | class VectorSearch(BaseComponent):
19 | def __init__(
20 | self, database: Neo4jDatabase, label: str, property: str, k: int
21 | ) -> None:
22 | self.database = database
23 | self.generated_cypher = construct_cypher(label, property, k)
24 |
25 | def run(self, input: str) -> Dict[str, Union[str, List[Dict[str, str]]]]:
26 | try:
27 | return {
28 | "output": [
29 | str(el["output"])
30 | for el in self.database.query(
31 | self.generated_cypher, {"input_vector": input}
32 | )
33 | ],
34 | "generated_cypher": self.generated_cypher,
35 | }
36 | except Exception as e:
37 | return e
38 |
--------------------------------------------------------------------------------
/api/src/driver/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/api/src/driver/__init__.py
--------------------------------------------------------------------------------
/api/src/driver/neo4j.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Dict, List, Optional
2 |
3 | from neo4j import GraphDatabase, exceptions
4 |
5 | node_properties_query = """
6 | CALL apoc.meta.data()
7 | YIELD label, other, elementType, type, property
8 | WHERE NOT type = "RELATIONSHIP" AND elementType = "node"
9 | WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
10 | RETURN {labels: nodeLabels, properties: properties} AS output
11 |
12 | """
13 |
14 | rel_properties_query = """
15 | CALL apoc.meta.data()
16 | YIELD label, other, elementType, type, property
17 | WHERE NOT type = "RELATIONSHIP" AND elementType = "relationship"
18 | WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
19 | RETURN {type: nodeLabels, properties: properties} AS output
20 | """
21 |
22 | rel_query = """
23 | CALL apoc.meta.data()
24 | YIELD label, other, elementType, type, property
25 | WHERE type = "RELATIONSHIP" AND elementType = "node"
26 | RETURN "(:" + label + ")-[:" + property + "]->(:" + toString(other[0]) + ")" AS output
27 | """
28 |
29 |
30 | def schema_text(node_props, rel_props, rels) -> str:
31 | return f"""
32 | This is the schema representation of the Neo4j database.
33 | Node properties are the following:
34 | {node_props}
35 | Relationship properties are the following:
36 | {rel_props}
37 | The relationships are the following
38 | {rels}
39 | """
40 |
41 |
42 | class Neo4jDatabase:
43 | def __init__(
44 | self,
45 | host: str = "neo4j://localhost:7687",
46 | user: str = "neo4j",
47 | password: str = "pleaseletmein",
48 | database: str = "neo4j",
49 | read_only: bool = True,
50 | ) -> None:
51 | """Initialize a neo4j database"""
52 | self._driver = GraphDatabase.driver(host, auth=(user, password))
53 | self._database = database
54 | self._read_only = read_only
55 | self.schema = ""
56 | # Verify connection
57 | try:
58 | self._driver.verify_connectivity()
59 | except exceptions.ServiceUnavailable:
60 | raise ValueError(
61 | "Could not connect to Neo4j database. "
62 | "Please ensure that the url is correct"
63 | )
64 | except exceptions.AuthError:
65 | raise ValueError(
66 | "Could not connect to Neo4j database. "
67 | "Please ensure that the username and password are correct"
68 | )
69 | try:
70 | self.refresh_schema()
71 | except:
72 | raise ValueError("Missing APOC Core plugin")
73 |
74 | @staticmethod
75 | def _execute_read_only_query(tx, cypher_query: str, params: Optional[Dict] = {}):
76 | result = tx.run(cypher_query, params)
77 | return [r.data() for r in result]
78 |
79 | def query(
80 | self, cypher_query: str, params: Optional[Dict] = {}
81 | ) -> List[Dict[str, Any]]:
82 | with self._driver.session(database=self._database) as session:
83 | try:
84 | if self._read_only:
85 | result = session.read_transaction(
86 | self._execute_read_only_query, cypher_query, params
87 | )
88 | return result
89 | else:
90 | result = session.run(cypher_query, params)
91 | # Limit to at most 10 results
92 | return [r.data() for r in result]
93 |
94 | # Catch Cypher syntax errors
95 | except exceptions.CypherSyntaxError as e:
96 | return [
97 | {
98 | "code": "invalid_cypher",
99 | "message": f"Invalid Cypher statement due to an error: {e}",
100 | }
101 | ]
102 |
103 | except exceptions.ClientError as e:
104 | # Catch access mode errors
105 | if e.code == "Neo.ClientError.Statement.AccessMode":
106 | return [
107 | {
108 | "code": "error",
109 | "message": "Couldn't execute the query due to the read only access to Neo4j",
110 | }
111 | ]
112 | else:
113 | return [{"code": "error", "message": e}]
114 |
115 | def refresh_schema(self) -> None:
116 | node_props = [el["output"] for el in self.query(node_properties_query)]
117 | rel_props = [el["output"] for el in self.query(rel_properties_query)]
118 | rels = [el["output"] for el in self.query(rel_query)]
119 | schema = schema_text(node_props, rel_props, rels)
120 | self.schema = schema
121 | print(schema)
122 |
123 | def check_if_empty(self) -> bool:
124 | data = self.query(
125 | """
126 | MATCH (n)
127 | WITH count(n) as c
128 | RETURN CASE WHEN c > 0 THEN true ELSE false END AS output
129 | """
130 | )
131 | return data[0]["output"]
132 |
--------------------------------------------------------------------------------
/api/src/embedding/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/api/src/embedding/__init__.py
--------------------------------------------------------------------------------
/api/src/embedding/base_embedding.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 |
3 |
4 | class BaseEmbedding(ABC):
5 | """"""
6 |
7 | @abstractmethod
8 | async def generate(
9 | self,
10 | input: str,
11 | ) -> str:
12 | """Comment"""
13 |
--------------------------------------------------------------------------------
/api/src/embedding/openai.py:
--------------------------------------------------------------------------------
1 | import openai
2 | from embedding.base_embedding import BaseEmbedding
3 |
4 |
5 | class OpenAIEmbedding(BaseEmbedding):
6 | """Wrapper around OpenAI embedding models."""
7 |
8 | def __init__(
9 | self, openai_api_key: str, model_name: str = "text-embedding-ada-002"
10 | ) -> None:
11 | openai.api_key = openai_api_key
12 | self.model = model_name
13 |
14 | def generate(
15 | self,
16 | input: str,
17 | ) -> str:
18 | embedding = openai.Embedding.create(input=input, model=self.model)
19 | return embedding["data"][0]["embedding"]
20 |
--------------------------------------------------------------------------------
/api/src/fewshot_examples.py:
--------------------------------------------------------------------------------
1 | def get_fewshot_examples(openai_api_key):
2 | return f"""
3 | #How is Emil Eifrem connected to Michael Hunger?
4 | MATCH (p1:Person {{name:"Emil Eifrem"}}), (p2:Person {{name:"Michael Hunger"}})
5 | MATCH p=shortestPath((p1)-[*]-(p2))
6 | RETURN p
7 | #What are the latest news regarding Google?
8 | MATCH (o:Organization {{name:"Google"}})<-[:MENTIONS]-(a:Article)-[:HAS_CHUNK]->(c)
9 | RETURN a.title AS title, c.text AS text, c.date AS date
10 | ORDER BY date DESC LIMIT 3
11 | #Are there any news regarding return to office policies?
12 | CALL apoc.ml.openai.embedding(["Are there any news regarding return to office policies?"],
13 | "{openai_api_key}") YIELD embedding
14 | MATCH (c:Chunk)
15 | WITH c, gds.similarity.cosine(c.embedding, embedding) AS score
16 | ORDER BY score DESC LIMIT 3
17 | RETURN c.text, score
18 | #What is Microsoft policy regarding to the return to office?
19 | CALL apoc.ml.openai.embedding(["What is Microsoft policy regarding to the return to office?"], "{openai_api_key}") YIELD embedding
20 | MATCH (o:Organization {{name:"Microsoft"}})<-[:MENTIONS]-()-[:HAS_CHUNK]->(c)
21 | WITH distinct c, embedding
22 | WITH c, gds.similarity.cosine(c.embedding, embedding) AS score
23 | ORDER BY score DESC LIMIT 3
24 | RETURN c.text, score
25 |
26 | When searching for specific information in the text chunks, never use the CONTAINS clause, but always use the apoc.ml.openai.embedding
27 | and gds.similarity.cosine functions as shown in the examples.
28 | When returning text chunks, always return exactly three chunks, no more, no less.
29 | Remember, instead of using CONTAINS to find information within text chunks use the apoc.ml.openai.embedding and gds.similarity.cosine functions.
30 | """
31 |
--------------------------------------------------------------------------------
/api/src/llm/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/api/src/llm/__init__.py
--------------------------------------------------------------------------------
/api/src/llm/basellm.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from typing import (
3 | Any,
4 | List,
5 | )
6 |
7 |
8 | def raise_(ex):
9 | raise ex
10 |
11 |
12 | class BaseLLM(ABC):
13 | """LLM wrapper should take in a prompt and return a string."""
14 |
15 | @abstractmethod
16 | def generate(self, messages: List[str]) -> str:
17 | """Comment"""
18 |
19 | @abstractmethod
20 | async def generateStreaming(
21 | self, messages: List[str], onTokenCallback
22 | ) -> List[Any]:
23 | """Comment"""
24 |
25 | @abstractmethod
26 | async def num_tokens_from_string(
27 | self,
28 | string: str,
29 | ) -> str:
30 | """Given a string returns the number of tokens the given string consists of"""
31 |
32 | @abstractmethod
33 | async def max_allowed_token_length(
34 | self,
35 | ) -> int:
36 | """Returns the maximum number of tokens the LLM can handle"""
37 |
--------------------------------------------------------------------------------
/api/src/llm/openai.py:
--------------------------------------------------------------------------------
1 | from typing import (
2 | Callable,
3 | List,
4 | )
5 |
6 | import openai
7 | import tiktoken
8 | from llm.basellm import BaseLLM
9 | from retry import retry
10 |
11 |
12 | class OpenAIChat(BaseLLM):
13 | """Wrapper around OpenAI Chat large language models."""
14 |
15 | def __init__(
16 | self,
17 | openai_api_key: str,
18 | model_name: str = "gpt-3.5-turbo",
19 | max_tokens: int = 1000,
20 | temperature: float = 0.0,
21 | ) -> None:
22 | openai.api_key = openai_api_key
23 | self.model = model_name
24 | self.max_tokens = max_tokens
25 | self.temperature = temperature
26 |
27 | @retry(tries=3, delay=1)
28 | def generate(
29 | self,
30 | messages: List[str],
31 | ) -> str:
32 | try:
33 | completions = openai.ChatCompletion.create(
34 | model=self.model,
35 | temperature=self.temperature,
36 | max_tokens=self.max_tokens,
37 | messages=messages,
38 | )
39 | return completions.choices[0].message.content
40 | # catch context length / do not retry
41 | except openai.error.InvalidRequestError as e:
42 | return str(f"Error: {e}")
43 | # catch authorization errors / do not retry
44 | except openai.error.AuthenticationError as e:
45 | return "Error: The provided OpenAI API key is invalid"
46 | except Exception as e:
47 | print(f"Retrying LLM call {e}")
48 | raise Exception()
49 |
50 | async def generateStreaming(
51 | self,
52 | messages: List[str],
53 | onTokenCallback=Callable[[str], None],
54 | ) -> str:
55 | result = []
56 | completions = openai.ChatCompletion.create(
57 | model=self.model,
58 | temperature=self.temperature,
59 | max_tokens=self.max_tokens,
60 | messages=messages,
61 | stream=True,
62 | )
63 | result = []
64 | for message in completions:
65 | # Process the streamed messages or perform any other desired action
66 | delta = message["choices"][0]["delta"]
67 | if "content" in delta:
68 | result.append(delta["content"])
69 | await onTokenCallback(message)
70 | return result
71 |
72 | def num_tokens_from_string(self, string: str) -> int:
73 | encoding = tiktoken.encoding_for_model(self.model)
74 | num_tokens = len(encoding.encode(string))
75 | return num_tokens
76 |
77 | def max_allowed_token_length(self) -> int:
78 | # TODO: list all models and their max tokens from api
79 | return 2049
80 |
--------------------------------------------------------------------------------
/api/src/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import Optional
3 | from components.company_report import CompanyReport
4 |
5 | from components.data_disambiguation import DataDisambiguation
6 | from components.question_proposal_generator import (
7 | QuestionProposalGenerator,
8 | )
9 | from components.summarize_cypher_result import SummarizeCypherResult
10 | from components.text2cypher import Text2Cypher
11 | from components.unstructured_data_extractor import (
12 | DataExtractor,
13 | DataExtractorWithSchema,
14 | )
15 | from driver.neo4j import Neo4jDatabase
16 | from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
17 | from fastapi.middleware.cors import CORSMiddleware
18 | from fastapi.responses import JSONResponse
19 | from fewshot_examples import get_fewshot_examples
20 | from llm.openai import OpenAIChat
21 | from pydantic import BaseModel
22 |
23 |
24 | class Payload(BaseModel):
25 | question: str
26 | api_key: Optional[str]
27 | model_name: Optional[str]
28 |
29 |
30 | class ImportPayload(BaseModel):
31 | input: str
32 | neo4j_schema: Optional[str]
33 | api_key: Optional[str]
34 |
35 |
36 | class questionProposalPayload(BaseModel):
37 | api_key: Optional[str]
38 |
39 |
40 | # Maximum number of records used in the context
41 | HARD_LIMIT_CONTEXT_RECORDS = 10
42 |
43 | neo4j_connection = Neo4jDatabase(
44 | host=os.environ.get("NEO4J_URL", "neo4j+s://demo.neo4jlabs.com"),
45 | user=os.environ.get("NEO4J_USER", "companies"),
46 | password=os.environ.get("NEO4J_PASS", "companies"),
47 | database=os.environ.get("NEO4J_DATABASE", "companies"),
48 | )
49 |
50 |
51 | # Initialize LLM modules
52 | openai_api_key = os.environ.get("OPENAI_API_KEY", None)
53 |
54 |
55 | # Define FastAPI endpoint
56 | app = FastAPI()
57 |
58 | origins = [
59 | "*",
60 | ]
61 |
62 | app.add_middleware(
63 | CORSMiddleware,
64 | allow_origins=origins,
65 | allow_credentials=True,
66 | allow_methods=["*"],
67 | allow_headers=["*"],
68 | )
69 |
70 |
71 | @app.post("/questionProposalsForCurrentDb")
72 | async def questionProposalsForCurrentDb(payload: questionProposalPayload):
73 | if not openai_api_key and not payload.api_key:
74 | raise HTTPException(
75 | status_code=422,
76 | detail="Please set OPENAI_API_KEY environment variable or send it as api_key in the request body",
77 | )
78 | api_key = openai_api_key if openai_api_key else payload.api_key
79 |
80 | questionProposalGenerator = QuestionProposalGenerator(
81 | database=neo4j_connection,
82 | llm=OpenAIChat(
83 | openai_api_key=api_key,
84 | model_name="gpt-3.5-turbo-0613",
85 | max_tokens=512,
86 | temperature=0.8,
87 | ),
88 | )
89 |
90 | return questionProposalGenerator.run()
91 |
92 |
93 | @app.get("/hasapikey")
94 | async def hasApiKey():
95 | return JSONResponse(content={"output": openai_api_key is not None})
96 |
97 |
98 | @app.websocket("/text2text")
99 | async def websocket_endpoint(websocket: WebSocket):
100 | async def sendDebugMessage(message):
101 | await websocket.send_json({"type": "debug", "detail": message})
102 |
103 | async def sendErrorMessage(message):
104 | await websocket.send_json({"type": "error", "detail": message})
105 |
106 | async def onToken(token):
107 | delta = token["choices"][0]["delta"]
108 | if "content" not in delta:
109 | return
110 | content = delta["content"]
111 | if token["choices"][0]["finish_reason"] == "stop":
112 | await websocket.send_json({"type": "end", "output": content})
113 | else:
114 | await websocket.send_json({"type": "stream", "output": content})
115 |
116 | # await websocket.send_json({"token": token})
117 |
118 | await websocket.accept()
119 | await sendDebugMessage("connected")
120 | chatHistory = []
121 | try:
122 | while True:
123 | data = await websocket.receive_json()
124 | if not openai_api_key and not data.get("api_key"):
125 | raise HTTPException(
126 | status_code=422,
127 | detail="Please set OPENAI_API_KEY environment variable or send it as api_key in the request body",
128 | )
129 | api_key = openai_api_key if openai_api_key else data.get("api_key")
130 |
131 | default_llm = OpenAIChat(
132 | openai_api_key=api_key,
133 | model_name=data.get("model_name", "gpt-3.5-turbo-0613"),
134 | )
135 | summarize_results = SummarizeCypherResult(
136 | llm=OpenAIChat(
137 | openai_api_key=api_key,
138 | model_name="gpt-3.5-turbo-0613",
139 | max_tokens=128,
140 | )
141 | )
142 |
143 | text2cypher = Text2Cypher(
144 | database=neo4j_connection,
145 | llm=default_llm,
146 | cypher_examples=get_fewshot_examples(api_key),
147 | )
148 |
149 | if "type" not in data:
150 | await websocket.send_json({"error": "missing type"})
151 | continue
152 | if data["type"] == "question":
153 | try:
154 | question = data["question"]
155 | chatHistory.append({"role": "user", "content": question})
156 | await sendDebugMessage("received question: " + question)
157 | results = None
158 | try:
159 | results = text2cypher.run(question, chatHistory)
160 | print("results", results)
161 | except Exception as e:
162 | await sendErrorMessage(str(e))
163 | continue
164 | if results == None:
165 | await sendErrorMessage("Could not generate Cypher statement")
166 | continue
167 |
168 | await websocket.send_json(
169 | {
170 | "type": "start",
171 | }
172 | )
173 | output = await summarize_results.run_async(
174 | question,
175 | results["output"][:HARD_LIMIT_CONTEXT_RECORDS],
176 | callback=onToken,
177 | )
178 | chatHistory.append({"role": "system", "content": output})
179 | await websocket.send_json(
180 | {
181 | "type": "end",
182 | "output": output,
183 | "generated_cypher": results["generated_cypher"],
184 | }
185 | )
186 | except Exception as e:
187 | await sendErrorMessage(str(e))
188 | await sendDebugMessage("output done")
189 | except WebSocketDisconnect:
190 | print("disconnected")
191 |
192 |
193 | @app.post("/data2cypher")
194 | async def root(payload: ImportPayload):
195 | """
196 | Takes an input and created a Cypher query
197 | """
198 | if not openai_api_key and not payload.api_key:
199 | raise HTTPException(
200 | status_code=422,
201 | detail="Please set OPENAI_API_KEY environment variable or send it as api_key in the request body",
202 | )
203 | api_key = openai_api_key if openai_api_key else payload.api_key
204 |
205 | try:
206 | result = ""
207 |
208 | llm = OpenAIChat(
209 | openai_api_key=api_key, model_name="gpt-3.5-turbo-16k", max_tokens=4000
210 | )
211 |
212 | if not payload.neo4j_schema:
213 | extractor = DataExtractor(llm=llm)
214 | result = extractor.run(data=payload.input)
215 | else:
216 | extractor = DataExtractorWithSchema(llm=llm)
217 | result = extractor.run(schema=payload.neo4j_schema, data=payload.input)
218 |
219 | print("Extracted result: " + str(result))
220 |
221 | disambiguation = DataDisambiguation(llm=llm)
222 | disambiguation_result = disambiguation.run(result)
223 |
224 | print("Disambiguation result " + str(disambiguation_result))
225 |
226 | return {"data": disambiguation_result}
227 |
228 | except Exception as e:
229 | print(e)
230 | return f"Error: {e}"
231 |
232 |
233 | class companyReportPayload(BaseModel):
234 | company: str
235 | api_key: Optional[str]
236 |
237 |
238 | # This endpoint is database specific and only works with the Demo database.
239 | @app.post("/companyReport")
240 | async def companyInformation(payload: companyReportPayload):
241 | api_key = openai_api_key if openai_api_key else payload.api_key
242 | if not openai_api_key and not payload.api_key:
243 | raise HTTPException(
244 | status_code=422,
245 | detail="Please set OPENAI_API_KEY environment variable or send it as api_key in the request body",
246 | )
247 | api_key = openai_api_key if openai_api_key else payload.api_key
248 |
249 | llm = OpenAIChat(
250 | openai_api_key=api_key,
251 | model_name="gpt-3.5-turbo-16k-0613",
252 | max_tokens=512,
253 | )
254 | print("Running company report for " + payload.company)
255 | company_report = CompanyReport(neo4j_connection, payload.company, llm)
256 | result = company_report.run()
257 |
258 | return JSONResponse(content={"output": result})
259 |
260 |
261 | @app.post("/companyReport/list")
262 | async def companyReportList():
263 | company_data = neo4j_connection.query(
264 | "MATCH (n:Organization) WITH n WHERE rand() < 0.01 return n.name LIMIT 5",
265 | )
266 |
267 | return JSONResponse(content={"output": [x["n.name"] for x in company_data]})
268 |
269 |
270 | @app.get("/health")
271 | async def health():
272 | return {"status": "ok"}
273 |
274 |
275 | @app.get("/ready")
276 | async def readiness_check():
277 | return {"status": "ok"}
278 |
279 |
280 | if __name__ == "__main__":
281 | import uvicorn
282 |
283 | uvicorn.run(app, port=int(os.environ.get("PORT", 7860)), host="0.0.0.0")
284 |
--------------------------------------------------------------------------------
/api/src/utils/unstructured_data_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 |
4 | regex = "Nodes:\s+(.*?)\s?\s?Relationships:\s+(.*)"
5 | internalRegex = "\[(.*?)\]"
6 | jsonRegex = "\{.*\}"
7 |
8 |
9 | def nodesTextToListOfDict(nodes):
10 | result = []
11 | for node in nodes:
12 | nodeList = node.split(",")
13 | if len(nodeList) < 2:
14 | continue
15 |
16 | name = nodeList[0].strip().replace('"', "")
17 | label = nodeList[1].strip().replace('"', "")
18 | properties = re.search(jsonRegex, node)
19 | if properties == None:
20 | properties = "{}"
21 | else:
22 | properties = properties.group(0)
23 | properties = properties.replace("True", "true")
24 | try:
25 | properties = json.loads(properties)
26 | except:
27 | properties = {}
28 | result.append({"name": name, "label": label, "properties": properties})
29 | return result
30 |
31 |
32 | def relationshipTextToListOfDict(relationships):
33 | result = []
34 | for relation in relationships:
35 | relationList = relation.split(",")
36 | if len(relation) < 3:
37 | continue
38 | start = relationList[0].strip().replace('"', "")
39 | end = relationList[2].strip().replace('"', "")
40 | type = relationList[1].strip().replace('"', "")
41 |
42 | properties = re.search(jsonRegex, relation)
43 | if properties == None:
44 | properties = "{}"
45 | else:
46 | properties = properties.group(0)
47 | properties = properties.replace("True", "true")
48 | try:
49 | properties = json.loads(properties)
50 | except:
51 | properties = {}
52 | result.append(
53 | {"start": start, "end": end, "type": type, "properties": properties}
54 | )
55 | return result
56 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3.7"
2 | services:
3 | backend:
4 | build:
5 | context: ./api
6 | hostname: api
7 | restart: always
8 | container_name: api
9 | ports:
10 | - 7860:7860
11 | env_file:
12 | - .env
13 | volumes:
14 | - ./api:/api
15 | frontend:
16 | build:
17 | context: ./ui
18 | hostname: ui
19 | restart: always
20 | container_name: ui
21 | ports:
22 | - 4173:4173
23 |
--------------------------------------------------------------------------------
/graph_schema.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neo4j/NaLLM/1af09cd117ba0777d81075c597a5081583568f9f/graph_schema.png
--------------------------------------------------------------------------------
/ui/.env.example:
--------------------------------------------------------------------------------
1 | VITE_UNSTRUCTURED_IMPORT_BACKEND_ENDPOINT=http://localhost:7860/
2 | VITE_KG_CHAT_BACKEND_ENDPOINT=ws://localhost:7860/text2text
3 | VITE_HAS_API_KEY_ENDPOINT=http://localhost:7860/hasapikey
4 | VITE_KG_CHAT_SAMPLE_QUESTIONS_ENDPOINT=http://localhost:7860/questionProposalsForCurrentDb
5 | VITE_REPORT_DATA_ENDPOINT=http://localhost:7860
6 |
--------------------------------------------------------------------------------
/ui/.eslintrc.cts:
--------------------------------------------------------------------------------
1 | export default {
2 | env: { browser: true, es2020: true },
3 | extends: [
4 | "eslint:recommended",
5 | "plugin:react/recommended",
6 | "plugin:react/jsx-runtime",
7 | "plugin:react-hooks/recommended",
8 | ],
9 | parserOptions: { ecmaVersion: "latest", sourceType: "module" },
10 | settings: { react: { version: "17.0" } },
11 | plugins: [],
12 | rules: {},
13 | };
14 |
--------------------------------------------------------------------------------
/ui/.gcloudignore:
--------------------------------------------------------------------------------
1 | # This file specifies files that are _not_ uploaded to Google Cloud
2 |
3 | # using gcloud. It follows the same syntax as .gitignore, with the addition of
4 |
5 | # "#!include" directives (which insert the entries of the given .gitignore-style
6 |
7 | # file at that point).
8 |
9 | #
10 |
11 | # For more information, run:
12 |
13 | # $ gcloud topic gcloudignore
14 |
15 | #
16 |
17 | .gcloudignore
18 |
19 | # If you would like to upload your .git directory, .gitignore file or files
20 |
21 | # from your .gitignore file, remove the corresponding line
22 |
23 | # below:
24 |
25 | .git
26 | .gitignore
27 |
28 | # Python pycache:
29 |
30 | **pycache**/
31 |
32 | # Ignored by the build system
33 |
34 | /setup.cfg
35 | node_modules/
36 | dist/
37 |
--------------------------------------------------------------------------------
/ui/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/ui/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:lts-alpine
2 |
3 | ARG FOLDER=/ui
4 |
5 | RUN mkdir -p $FOLDER
6 |
7 | COPY . /ui/.
8 |
9 | #CMD ["cd", "ui"]
10 |
11 | WORKDIR $FOLDER
12 |
13 | RUN npm install
14 |
15 | EXPOSE 4173
16 |
17 | RUN npm run build
18 |
19 | CMD ["npm", "run", "preview"]
20 |
--------------------------------------------------------------------------------
/ui/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |