Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 9.4 KiBRenderedRawPermalink
1[![Dockerhub](https://img.shields.io/docker/pulls/falkordb/falkordb?label=Docker)](https://hub.docker.com/r/falkordb/falkordb/)
2[![pypi](https://badge.fury.io/py/graphrag_sdk.svg)](https://pypi.org/project/graphrag_sdk/)
3[![Discord](https://img.shields.io/discord/1146782921294884966?style=flat-square)](https://discord.gg/6M4QwDXn2w)
4[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md)
5
6# GraphRAG-SDK
7
8[![Try Free](https://img.shields.io/badge/Try%20Free-FalkorDB%20Cloud-FF8101?labelColor=FDE900&style=for-the-badge&link=https://app.falkordb.cloud)](https://app.falkordb.cloud)
9
10GraphRAG-SDK is a comprehensive solution for building Graph Retrieval-Augmented Generation (GraphRAG) applications, leveraging [FalkorDB](https://www.falkordb.com/) for optimal performance.
11
12## Features
13
14* Ontology Management: Manage ontologies either manually or automatically from unstructured data.
15* Knowledge Graph (KG): Construct and query knowledge graphs for efficient data retrieval.
16* LLMs Integration: Support for OpenAI and Google Gemini models.
17* Multi-Agent System: Multi-agent orchestrators using KG-based agents.
18
19## Get Started
20
21### Install
22
23```sh
24pip install graphrag_sdk
25```
26
27### Prerequisites
28
29#### Graph Database
30
31GraphRAG-SDK relies on [FalkorDB](http://falkordb.com) as its graph engine and works with OpenAI/Gemini.
32
33Use [FalkorDB Cloud](https://app.falkordb.cloud/) to get credentials or start FalkorDB locally:
34
35```sh
36docker run -p 6379:6379 -p 3000:3000 -it --rm -v ./data:/data falkordb/falkordb:latest
37```
38
39#### LLM Models
40
41Currently, this SDK supports the following LLMs API:
42
43* [OpenAI](https://openai.com/index/openai-api) Recommended model:`gpt-4o`
44* [google](https://makersuite.google.com/app/apikey) Recommended model:`gemini-1.5-flash-001`
45
46Make sure that a `.env` file is present with all required credentials.
47
48 <details>
49 <summary>.env</summary>
50
51 ```
52 OPENAI_API_KEY="OPENAI_API_KEY"
53 GOOGLE_API_KEY="GOOGLE_API_KEY"
54 ```
55
56 </details>
57
58## Basic Usage
59
60[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/FalkorDB/GraphRAG-SDK/blob/main/examples/movies/demo-movies.ipynb)
61
62The following example demonstrates the basic usage of this SDK to create a GraphRAG using URLs with auto-detected ontology.
63
64```python
65from dotenv import load_dotenv
66
67from graphrag_sdk.source import URL
68from graphrag_sdk import KnowledgeGraph, Ontology
69from graphrag_sdk.models.openai import OpenAiGenerativeModel
70from graphrag_sdk.model_config import KnowledgeGraphModelConfig
71load_dotenv()
72
73# Import Data
74urls = ["https://www.rottentomatoes.com/m/side_by_side_2012",
75"https://www.rottentomatoes.com/m/matrix",
76"https://www.rottentomatoes.com/m/matrix_revolutions",
77"https://www.rottentomatoes.com/m/matrix_reloaded",
78"https://www.rottentomatoes.com/m/speed_1994",
79"https://www.rottentomatoes.com/m/john_wick_chapter_4"]
80
81sources = [URL(url) for url in urls]
82
83# Model
84model = OpenAiGenerativeModel(model_name="gpt-4o")
85
86# Ontology Auto-Detection
87ontology = Ontology.from_sources(
88 sources=sources,
89 model=model,
90)
91
92# Knowledge Graph
93kg = KnowledgeGraph(
94 name="movies",
95 model_config=KnowledgeGraphModelConfig.with_model(model),
96 ontology=ontology,
97)
98
99# GraphRAG System and Questioning
100kg.process_sources(sources)
101
102chat = kg.chat_session()
103
104print(chat.send_message("Who is the director of the movie The Matrix?"))
105print(chat.send_message("How this director connected to Keanu Reeves?"))
106
107```
108
109## Tools
110
111[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/FalkorDB/GraphRAG-SDK/blob/main/examples/ufc/demo-ufc.ipynb)
112
113### Import source data
114
115The SDK supports the following file formats:
116
117* PDF
118* TEXT
119* JSONL
120* URL
121* HTML
122* CSV
123
124```python
125import os
126from graphrag_sdk.source import Source
127
128src_files = "data_folder"
129sources = []
130
131# Create a Source object.
132for file in os.listdir(src_files):
133 sources.append(Source(os.path.join(src_files, file)))
134```
135
136### Ontology
137
138You can either auto-detect the ontology from your data or define it manually. Additionally, you can set `Boundaries` for ontology auto-detection.
139
140Once the ontology is created, you can review, modify, and update it as needed before using it to build the Knowledge Graph (KG).
141
142```python
143import random
144from falkordb import FalkorDB
145from graphrag_sdk import KnowledgeGraph, Ontology
146from graphrag_sdk.models.openai import OpenAiGenerativeModel
147
148# Define the percentage of files that will be used to auto-create the ontology.
149percent = 0.1 # This represents 10%. You can adjust this value (e.g., 0.2 for 20%).
150
151boundaries = """
152 Extract only the most relevant information about UFC fighters, fights, and events.
153 Avoid creating entities for details that can be expressed as attributes.
154"""
155
156# Define the model to be used for the ontology
157model = OpenAiGenerativeModel(model_name="gpt-4o")
158
159# Randomly select a percentage of files from sources.
160sampled_sources = random.sample(sources, round(len(sources) * percent))
161
162ontology = Ontology.from_sources(
163 sources=sampled_sources,
164 boundaries=boundaries,
165 model=model,
166)
167
168# Save the ontology to the disk as a json file.
169with open("ontology.json", "w", encoding="utf-8") as file:
170 file.write(json.dumps(ontology.to_json(), indent=2))
171```
172
173After generating the initial ontology, you can review it and make any necessary modifications to better fit your data and requirements. This might include refining entity types or adjusting relationships.
174
175Once you are satisfied with the ontology, you can proceed to use it for creating and managing your Knowledge Graph (KG).
176
177### Knowledge Graph
178
179Now, you can use the SDK to create a Knowledge Graph (KG) from your sources and ontology.
180
181```python
182# After approving the ontology, load it from disk.
183ontology_file = "ontology.json"
184with open(ontology_file, "r", encoding="utf-8") as file:
185 ontology = Ontology.from_json(json.loads(file.read()))
186
187kg = KnowledgeGraph(
188 name="kg_name",
189 model_config=KnowledgeGraphModelConfig.with_model(model),
190 ontology=ontology,
191)
192
193kg.process_sources(sources)
194```
195
196You can update the KG at any time by processing more sources with the `process_sources` method.
197
198### Graph RAG
199
200At this point, you have a Knowledge Graph that can be queried using this SDK. You can use the `ask` method for single questions or `chat_session` for conversations.
201
202```python
203# Single question.
204response = kg.ask("What were the last five fights? When were they? How many rounds did they have?")
205print(response)
206
207# Conversation.
208chat = kg.chat_session()
209response = chat.send_message("Who is Salsa Boy?")
210print(response)
211response = chat.send_message("Tell me about one of his fights?")
212print(response)
213```
214
215## Multi Agent - Orchestrator
216
217[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/FalkorDB/GraphRAG-SDK/blob/main/examples/trip/demo_orchestrator_trip.ipynb)
218
219The GraphRAG-SDK supports KG agents. Each agent is an expert in the data it has learned, and the orchestrator orchestrates the agents.
220
221### Agents
222
223See the [Basic Usage](#basic-usage) section to understand how to create KG objects for the agents.
224
225```python
226# Define the model
227model = OpenAiGenerativeModel("gpt-4o")
228
229# Create the KG from the predefined ontology.
230# In this example, we will use the restaurants agent and the attractions agent.
231restaurants_kg = KnowledgeGraph(
232 name="restaurants",
233 ontology=restaurants_ontology,
234 model_config=KnowledgeGraphModelConfig.with_model(model),
235)
236attractions_kg = KnowledgeGraph(
237 name="attractions",
238 ontology=attractions_ontology,
239 model_config=KnowledgeGraphModelConfig.with_model(model),
240)
241
242
243# The following agent is specialized in finding restaurants.
244restaurants_agent = KGAgent(
245 agent_id="restaurants_agent",
246 kg=restaurants_kg,
247 introduction="I'm a restaurant agent, specialized in finding the best restaurants for you.",
248)
249
250# The following agent is specialized in finding tourist attractions.
251attractions_agent = KGAgent(
252 agent_id="attractions_agent",
253 kg=attractions_kg,
254 introduction="I'm an attractions agent, specialized in finding the best tourist attractions for you.",
255)
256```
257
258### Orchestrator - Multi-Agent System
259
260The orchestrator manages the usage of agents and handles questioning.
261
262```python
263# Initialize the orchestrator while giving it the backstory.
264orchestrator = Orchestrator(
265 model,
266 backstory="You are a trip planner, and you want to provide the best possible itinerary for your clients.",
267)
268
269# Register the agents that we created above.
270orchestrator.register_agent(restaurants_agent)
271orchestrator.register_agent(attractions_agent)
272
273# Query the orchestrator.
274runner = orchestrator.ask("Create a two-day itinerary for a trip to Rome. Please don't ask me any questions; just provide the best itinerary you can.")
275print(runner.output)
276```
277
278## Support
279
280Connect with our community for support and discussions. If you have any questions, don’t hesitate to contact us through one of the methods below:
281
282* [Discord](https://discord.com/invite/6M4QwDXn2w)
283* [Email](support@falkordb.com)
284* [Discussions](https://github.com/orgs/FalkorDB/discussions)
285