Elffuss BraidHub

kikocis/GraphRAG-SDK public

include examples in README
Changeset1c7c3c43d367beea11162a0a0ce8a96066c7af767193124b4ad98994da8f0169
AuthorRoi Lipman <roilipman@gmail.com> · 2024-05-28 12:44 +03:00
CommitterRoi Lipman <roilipman@gmail.com> · 2024-05-28 13:33 +03:00
Parentsdb62d1677f39

Browse the files at this changeset

4 files changed

modified README.md +110 −12
@@ -1,6 +1,62 @@
1-## Usage
1+# RAG-SDK
22
3-### Manual schema creation
3+## Example
4+
5+### Prerequisites
6+RAG-SDK relies on [FalkorDB](http://falkordb.com) as its graph engine and works with OpenAI.
7+
8+Start FalkorDB locally:
9+```sh
10+docker run -p 6379:6379 -p 3000:3000 -it --rm falkordb/falkordb:latest
11+```
12+
13+Export your OpenAI API KEY:
14+```sh
15+export OPENAI_API_KEY=<YOUR_OPENAI_KEY>
16+```
17+
18+```python
19+from rag_sdk.Schema import Schema
20+from rag_sdk import KnowledgeGraph, Source
21+
22+# Auto generate graph schema from unstructured data
23+sources = [Source("./data/the_matrix.txt")]
24+s = Schema.auto_detect(sources)
25+
26+# Create a knowledge graph based on schema
27+g = KnowledgeGraph("IMDB", schema=s)
28+g.process_sources(sources)
29+
30+# Query your data
31+question = "Name a few actors who've played in 'The Matrix'"
32+answer, messages = g.ask(question)
33+print(f"Answer: {answer}")
34+
35+# Output:
36+# Answer: A few actors who've played in 'The Matrix' are:
37+# - Keanu Reeves
38+# - Laurence Fishburne
39+# - Carrie-Anne Moss
40+# - Hugo Weaving
41+```
42+
43+## Introduction
44+RAG-SDK provides easy-to-use tooling to get you up and running with your own
45+Graph-RAG solution.
46+
47+There are two main components:
48+### Schema
49+A `schema` represents the types of entities and relationships within your data.
50+For example, the main entities in your data are: Movies, Actors, and Directors.
51+These are interconnected via `ACT` and `DIRECTED` edges.
52+
53+Although not mandatory, the specification of a knowledge graph schema helps with
54+the extraction of knowledge from unstructured data.
55+
56+We provide two approaches to schema creation:
57+
58+#### Manual schema creation
59+Use this method when you know exactly what your data looks like.
460
561 ```python
662 s = Schema()
@@ -8,24 +64,66 @@
864 s.add_entity('Movie').add_attribute('title', str, unique=True)
965 s.add_relation("ACTED", 'Actor', 'Movie')
1066
11-g = KG("IMDB", schema=s)
12-g.add_source("./data/madoff.txt")
67+print(f"Schema: {s.to_JSON()}")
1368
14-g.create()
15-
16-answer, messages = g.ask("List a few actors")
69+# Output:
70+# Schema: {"entities": [
71+# {"name": "Actor",
72+# "attributes": [
73+# {"name": "name", "type": "str", "desc": "Actor's name", "unique": true, "mandatory": false}]},
74+# {"name": "Movie",
75+# "attributes": [
76+# {"name": "title", "type": "str", "desc": "Movie's title", "unique": true, "mandatory": false}]}],
77+# "relations": [{"name": "ACTED", "src": "Actor", "dest": "Movie"}]}
1778 ```
1879
19-### Automatic schema creation
80+#### Automatic schema creation
81+Use this method to discover the main entities and relationships within your data.
82+Once the schema is discovered, you can adjust it to your liking.
2083
2184 ```python
2285 sources = [Source("./data/madoff.txt")]
2386 s = Schema.auto_detect(sources)
87+print(f"Schema: {s.to_JSON()}")
88+
89+# Output:
90+# Schema: {"entities": [
91+# {"name": "Actor", "attributes": [
92+# {"name": "Name", "type": "str", "desc": "Actor's Name", "unique": true, "mandatory": true}]},
93+# {"name": "Critic", "attributes": [
94+# {"name": "TopCritic", "type": "bool", "desc": "Critic's TopCritic", "unique": false, "mandatory": false},
95+# {"name": "Name", "type": "str", "desc": "Critic's Name", "unique": true, "mandatory": true},
96+# {"name": "Publication", "type": "str", "desc": "Critic's Publication", "unique": false, "mandatory": false}]}...
97+```
98+
99+### KnowledgeGraph
100+A `KnowledgeGraph` holds the actual entities and relationships within your data.
101+Once constructed, it serves as the backbone of your RAG solution. A Large Language Model will query your knowledge-graph to build a precise context on which its answer will be based.
102+
103+```python
104+# Create a knowledge graph based on a schema.
105+g = KnowledgeGraph("IMDB", host="127.0.0.1", port=6379, schema=s)
106+g.process_sources([Source("./data/the_matrix.txt"), Source("./data/wework.txt")])
24107
25-g = KG("IMDB", schema=s)
26-g.add_source("./data/madoff.txt")
108+# Query your data
109+question = "Name a few actors who've played in 'The Matrix'"
110+answer, messages = g.ask(question)
111+print(f"Answer: {answer}")
27112
28-g.create()
113+question = "List additional actors"
114+answer, messages = g.ask(question, messages)
115+print(f"Answer: {answer}")
29116
30-answer, messages = g.ask("List a few actors")
117+# Outputs:
118+# Answer: A few actors who've played in 'The Matrix' are:
119+# - Keanu Reeves
120+# - Laurence Fishburne
121+# - Carrie-Anne Moss
122+# - Hugo Weaving
123+#
124+# Answer: A few additional actors who've played in 'The Matrix' are:
125+# - Joe Pantoliano
126+# - Marcus Chong
127+# - Paul Goddard
128+# - Gloria Foster
31129 ```
modified rag_sdk/Schema/schema.py +0 −1
@@ -8,7 +8,6 @@
88 from .from_graph import schema_from_graph
99 from .auto_detect import schema_auto_detect
1010
11-
1211 class Schema(object):
1312 """
1413 Knowledge Graph schema (ontology)
modified rag_sdk/kg.py +19 −40
@@ -44,57 +44,39 @@
4444 self.sources = set([])
4545 self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection
4646
47- def add_source(self, source:str) -> AbstractSource:
47+ def list_sources(self) -> list[AbstractSource]:
4848 """
49- Add source from which knowledge will be extracted
50-
51- Parameters:
52- source (src): path to source
49+ List of sources associated with knowledge graph
5350
5451 Returns:
55- AbstractSource: A source object
52+ list[AbstractSource]: sources
5653 """
5754
58- if not isinstance(source, str) or source == "":
59- raise Exception("Invalid argument, source should be a none empty string.")
60-
61- s = Source(source)
62- self.sources.add(s)
63-
64- return s
55+ return [s.source for s in self.sources]
6556
66- def remove_source(self, source:str|AbstractSource) -> None:
57+ def process_sources(self, sources: list[AbstractSource]) -> None:
6758 """
68- Remove source from sources
59+ Add entities and relations found in sources into the knowledge-graph
6960
70- Parameters:
71- source (str|AbstractSource): source to remove
61+ Parameters:
62+ sources (list[AbstractSource]): list of sources to extract knowledge from
7263 """
7364
74- if not isinstance(source, str) and not isinstance(source, AbstractSource):
75- raise Exception("Invalid argument, source should be a string or a Source")
76-
77- if isinstance(source, str):
78- for s in self.sources:
79- if s.source == source:
80- self.sources.remove(s)
81- break
82- else:
83- self.sources.remove(source)
65+ # Make sure knowledge graph is created.
66+ if not 'build_graph_from_sources' in globals() or self.client is None:
67+ self._create()
8468
85- def list_sources(self) -> list[AbstractSource]:
86- """
87- List of sources associated with knowledge graph
88-
89- Returns:
90- list[AbstractSource]: sources
91- """
69+ # Run assistant
70+ result = build_graph_from_sources(self, self.client, sources)
9271
93- return [s.source for s in self.sources]
72+ # Add processed sources
73+ for src in sources:
74+ self.sources.add(src)
9475
9576 def _createKGWithSchema(self):
9677 # Save schema as an ontology graph
97- self.schema.save_graph(self.graph)
78+ schema_graph = self.db.select_graph(f"{self.name}_schema")
79+ self.schema.save_graph(schema_graph)
9880
9981 # Create Knowledge Graph construction assistant
10082
@@ -119,13 +101,10 @@
119101 # TODO: note multiple calls to _createKGWithSchema will overide one another.
120102 exec(code, globals())
121103
122- # Run assistant
123- result = build_graph_from_sources(self, self.client, self.sources)
124-
125104 def _createKGWithoutSchema(self):
126105 pass
127106
128- def create(self) -> None:
107+ def _create(self) -> None:
129108 """
130109 Create knowledge graph
131110 Extract entities and relations from sources
modified tests/test_kg.py +9 −31
@@ -1,43 +1,21 @@
11 import unittest
2-from rag_sdk.kg import KnowledgeGraph
2+from rag_sdk import KnowledgeGraph, Source
33 from rag_sdk.Schema import Schema
44
55 class TestKG(unittest.TestCase):
6- def test_kg_sources(self):
7- g = KnowledgeGraph("UFC")
8-
9- data_0 = g.add_source("data_0.pdf")
10- data_1 = g.add_source("data_1.PDF")
11- data_2 = g.add_source("data_2.txt")
12- data_3 = g.add_source("data_3")
13-
14- sources = g.list_sources()
15- self.assertEqual(len(sources), 4)
16-
17- g.remove_source("data_0.pdf")
18- g.remove_source("data_0.pdf")
19-
20- sources = g.list_sources()
21- self.assertEqual(len(sources), 3)
22-
23- g.remove_source(data_2)
24- g.remove_source("data_1.PDF")
25- g.remove_source("data_3")
26-
27- sources = g.list_sources()
28- self.assertEqual(len(sources), 0)
29-
306 def test_kg_creation(self):
317 # Create schema
328 s = Schema()
33- s.add_entity('Actor').add_attribute('name', str, unique=True)
34- s.add_entity('Movie').add_attribute('title', str, unique=True)
35- s.add_relation("ACTED", 'Actor', 'Movie')
9+ actor = s.add_entity('Actor')
10+ actor.add_attribute('name', str, unique=True)
3611
37- g = KnowledgeGraph("IMDB", schema=s)
38- g.add_source("./data/madoff.txt")
12+ movie = s.add_entity('Movie')
13+ movie.add_attribute('title', str, unique=True)
3914
40- g.create()
15+ s.add_relation("ACTED", actor, movie)
16+
17+ g = KnowledgeGraph("IMDB", schema=s)
18+ g.process_sources([Source("./data/madoff.txt")])
4119
4220 answer, messages = g.ask("List a few actors")
4321 print(f"answer: {answer}")