Elffuss BraidHub

kikocis/GraphRAG-SDK public

improved docs
Changesetdb62d1677f39776c63b5f21288247b3bd043f51c35eeae1790bfd5162de4c72e
AuthorRoi Lipman <roilipman@gmail.com> · 2024-05-28 09:56 +03:00
CommitterRoi Lipman <roilipman@gmail.com> · 2024-05-28 09:56 +03:00
Parentsffd3815000e1

Browse the files at this changeset

7 files changed

modified rag_sdk/Schema/entity.py +50 −8
@@ -22,9 +22,19 @@
2222 def __hash__(self) -> int:
2323 return hash(self.name)
2424
25-# Represents an ontolegy entity
2625 class Entity(object):
26+ """
27+ Represents an ontolegy entity
28+ """
29+
2730 def __init__(self, name:str):
31+ """
32+ Initialize Entity
33+
34+ Parameters:
35+ name (str): name of entity
36+ """
37+
2838 if not isinstance(name, str) or name == "":
2939 raise Exception("Entity name must be a none empty string")
3040
@@ -37,8 +47,18 @@
3747
3848 return (self.name == other.name and self.attributes == other.attributes)
3949
40- # Add attribute to entity
41- def add_attribute(self, name:str, type:type, desc=None, unique=False, mandatory=False):
50+ def add_attribute(self, name:str, type:type, desc:str|None=None, unique:bool=False, mandatory:bool=False) -> None:
51+ """
52+ Add attribute to entity
53+
54+ Parameters:
55+ name (str): attribute name
56+ type (type): attribute type
57+ desc (str): short description for attribute
58+ unique (bool): is the attribute value unique
59+ mandatory (bool): is the attribute mandatory
60+ """
61+
4262 # Validate arguments
4363 if not isinstance(name, str) or name == "":
4464 raise Exception("Attribute name must be a none empty string")
@@ -55,8 +75,14 @@
5575 desc = f"{self.name}'s {name}" if desc is None else desc
5676 self.attributes.add(Attribute(name, type, desc, unique, mandatory))
5777
58- # Remove attribute from entity
59- def remove_attribute(self, name:str):
78+ def remove_attribute(self, name:str) ->None:
79+ """
80+ Remove attribute from entity
81+
82+ Parameters:
83+ name (str): name of attribute to remove
84+ """
85+
6086 # Validate argument
6187 if not isinstance(name, str) or name == "":
6288 raise Exception("Attribute name must be a none empty string")
@@ -66,7 +92,17 @@
6692 self.attributes.remove(attr)
6793 return
6894
69- def get_attribute(self, name:str):
95+ def get_attribute(self, name:str) -> Attribute|None:
96+ """
97+ Get attribute
98+
99+ Parameters:
100+ name (str): name of attribute to get
101+
102+ Returns:
103+ attribute
104+ """
105+
70106 # Validate argument
71107 if not isinstance(name, str) or name == "":
72108 raise Exception("Attribute name must be a none empty string")
@@ -77,8 +113,14 @@
77113
78114 return None
79115
80- # returns a list of Entity's unique attributes
81- def unique_attributes(self):
116+ def unique_attributes(self) -> list[Attribute]:
117+ """
118+ Get a list of Entity's unique attributes
119+
120+ Returns:
121+ list of unique attributes
122+ """
123+
82124 unique_attrs = []
83125 for attr in self.attributes:
84126 if attr.unique:
modified rag_sdk/Schema/schema.py +94 −18
@@ -1,4 +1,5 @@
11 from falkordb import Graph
2+from rag_sdk.source import AbstractSource
23 from .entity import Entity
34 from .relation import Relation
45 from .encoder import SchemaEncoder
@@ -7,11 +8,19 @@
78 from .from_graph import schema_from_graph
89 from .auto_detect import schema_auto_detect
910
10-# Knowledge Graph schema
11-# The schema captures graph entities in addition to their attributes
12-# and the relationship types between the entities
11+
1312 class Schema(object):
13+ """
14+ Knowledge Graph schema (ontology)
15+ The schema captures entities types in addition to their attributes
16+ and the relationship types between the them
17+ """
18+
1419 def __init__(self):
20+ """
21+ Initialize Schema
22+ """
23+
1524 self.entities = {}
1625 self.relations = {}
1726
@@ -27,8 +36,18 @@
2736
2837 return True
2938
30- # Add a new entity to schema
31- def add_entity(self, name:str):
39+
40+ def add_entity(self, name:str) -> Entity:
41+ """
42+ Add a new entity to schema
43+
44+ Parameters:
45+ name (str): Entity name.
46+
47+ Returns:
48+ entity
49+ """
50+
3251 # Validate arguments
3352 if not isinstance(name, str) or name == "":
3453 raise Exception(f"Invalid name argument, expecting none empty string")
@@ -39,8 +58,14 @@
3958 self.entities[name] = e
4059 return e
4160
42- # Get an entity from schema
4361 def get_entity(self, name:str) -> Entity | None:
62+ """
63+ Get an entity from schema
64+
65+ Returns:
66+ entity
67+ """
68+
4469 if not isinstance(name, str) or name == "":
4570 raise Exception("Invalid argument, name should be a none empty string")
4671
@@ -49,8 +74,14 @@
4974 else:
5075 return None
5176
52- # Add a new relation to schema
53- def add_relation(self, name:str, src:Entity, dest:Entity):
77+ def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation:
78+ """
79+ Add a relationship to schema
80+
81+ Returns:
82+ relation
83+ """
84+
5485 # Validate arguments
5586 if not isinstance(src, Entity) and not isinstance(src, str):
5687 raise Exception(f"Invalid argument, src is expected to be either a string or an Entity")
@@ -85,9 +116,14 @@
85116
86117 return r
87118
88- # Validate schema
89- # Make sure schema is valid
90119 def validate(self) -> bool:
120+ """
121+ Validate schema
122+
123+ Returns:
124+ True if schema is valid
125+ """
126+
91127 # Make sure each Relation reference existing Entities
92128 # And each referenced entity has at least one unique attribute
93129 for r in self.relations:
@@ -109,32 +145,72 @@
109145
110146 return True
111147
112- # Save schema as an ontology graph
113- def save_graph(self, g:Graph):
148+ def save_graph(self, g:Graph) -> None:
149+ """
150+ Save schema as an ontology graph
151+
152+ Parameters:
153+ g (Graph): graph to create
154+ """
155+
114156 schema_to_graph(self, g)
115157
116- # encode schema to JSON string
117158 def to_JSON(self) -> str:
159+ """
160+ Encode schema to JSON string
161+
162+ Returns:
163+ JSON representation of schema
164+ """
165+
118166 encoder = SchemaEncoder()
119167 return encoder.to_JSON(self)
120168
121169 @classmethod
122- # Create a schema from an ontology graph
123- def from_graph(cls, g:Graph):
170+ def from_graph(cls, g:Graph) -> 'Schema':
171+ """
172+ Create a schema from an ontology graph
173+
174+ Parameters:
175+ g (Graph): ontology graph to load
176+
177+ Returns:
178+ Schema: schema
179+ """
180+
124181 s = cls()
125182 schema_from_graph(s, g)
126183 return s
127184
128185 @classmethod
129- # Auto detect schema from sources
130- def auto_detect(cls, sources, model="gpt-3.5-turbo-0125") -> 'Schema':
186+ def auto_detect(cls, sources: list[AbstractSource], model="gpt-3.5-turbo-0125") -> 'Schema':
187+ """
188+ Auto detect schema from sources
189+
190+ Parameters:
191+ sources (list[AbstractSource]): list of sources to extract schema from
192+ model (str): OpenAI model to use
193+
194+ Returns:
195+ Schema: schema
196+ """
197+
131198 s = cls()
132199 schema_auto_detect(s, sources, model)
133200 return s
134201
135202 @classmethod
136- # Create a schema from JSON
137203 def from_JSON(cls, json:str) -> 'Schema':
204+ """
205+ Create a schema from JSON
206+
207+ Parameters:
208+ json (str): the output from to_JSON
209+
210+ Returns:
211+ Schema: schema
212+ """
213+
138214 s = cls()
139215 decoder = SchemaDecoder()
140216 decoder.from_JSON(s, json)
modified rag_sdk/__init__.py +1 −1
@@ -1,2 +1,2 @@
1-from .kg import KG
1+from .kg import KnowledgeGraph
22 from .source import Source
modified rag_sdk/kg.py +26 −37
@@ -4,6 +4,7 @@
44 from typing_extensions import AbstractSet
55
66 from .prompts import *
7+from .template import TEMPLATE
78 from openai import OpenAI
89 from falkordb import FalkorDB
910 from .query_graph import query
@@ -12,11 +13,12 @@
1213 from .Schema.tools_gen import schema_to_tools
1314 from .Schema.functions_gen import schema_to_functions
1415
15-class KG(object):
16+class KnowledgeGraph(object):
1617 """Knowledge Graph model data as a network of entities and relations
1718 To create one it is best to provide a schema which will define the graph's ontology
1819 In addition to a set of sources from which entities and relations will be extracted.
1920 """
21+
2022 def __init__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None,
2123 model:str="gpt-4-1106-preview", schema:Schema|None=None):
2224 """
@@ -61,7 +63,7 @@
6163
6264 return s
6365
64- def remove_source(self, source:str|AbstractSource):
66+ def remove_source(self, source:str|AbstractSource) -> None:
6567 """
6668 Remove source from sources
6769
@@ -105,37 +107,25 @@
105107 functions_impl = [func[1] for func in funcs]
106108
107109 # Generate assistant
108- # Generate Python from template
109- code = None
110- with open("./template.py", "r") as f:
111- code = f.read()
112- code = code.replace("<TOOLS>", ",\n".join([str(tool) for tool in tools]))
113- code = code.replace("<GRAPH_ID>", "\"" + self.name + "\"")
114- code = code.replace("<FUNCTIONS>", "\n".join(functions_impl))
115- code = code.replace("<AVAILABLE_FUNCTIONS>", '{' + ",\n".join([f"'{f}': {f}" for f in functions_names]) +'}')
116-
117- # Load template
118- import sys
119- import importlib.util
120-
121- # Write code to a file
122- file_path = 'auto_gen.py'
123- with open(file_path, 'w') as file:
124- file.write(code)
125-
126- # Load the module dynamically
127- spec = importlib.util.spec_from_file_location("auto_gen", file_path)
128- dynamic_module = importlib.util.module_from_spec(spec)
129- sys.modules["dynamic_module"] = dynamic_module
130- spec.loader.exec_module(dynamic_module)
110+ # Generate code from template
111+ code = TEMPLATE
112+ code = code.replace("<TOOLS>", ",\n".join([str(tool) for tool in tools]))
113+ code = code.replace("<GRAPH_ID>", "\"" + self.name + "\"")
114+ code = code.replace("<FUNCTIONS>", "\n".join(functions_impl))
115+ code = code.replace("<AVAILABLE_FUNCTIONS>", '{' + ",\n".join([f"'{f}': {f}" for f in functions_names]) +'}')
116+
117+ # Execute the code string in the global namespace
118+ # Introduces the 'build_graph_from_sources' function
119+ # TODO: note multiple calls to _createKGWithSchema will overide one another.
120+ exec(code, globals())
131121
132122 # Run assistant
133- result = dynamic_module.build_graph_from_sources(self, self.client, self.sources)
123+ result = build_graph_from_sources(self, self.client, self.sources)
134124
135125 def _createKGWithoutSchema(self):
136126 pass
137127
138- def create(self):
128+ def create(self) -> None:
139129 """
140130 Create knowledge graph
141131 Extract entities and relations from sources
@@ -147,23 +137,22 @@
147137 else:
148138 self._createKGWithoutSchema()
149139
150-
151- def ask(self, question:str, messages:list=None) -> tuple[str, list]:
140+ def ask(self, question:str, history:list|None=None) -> tuple[str, list]:
152141 """
153142 Query the knowledge graph using natural language
154143 if the query is asked as part of a longer conversation make sure to
155- include past messages.
144+ include past history.
156145
157146 Rreturns:
158- tuple[str, list]: answer, conversation messages
147+ tuple[str, list]: answer, conversation history
159148
160149 Example:
161- >>> ans, msgs = kg.ask("Which actor has the most oscars")
162- >>> ans, msgs = kg.ask("List a few movies in which that actored played in", msgs)
150+ >>> ans, history = kg.ask("Which actor has the most oscars")
151+ >>> ans, history = kg.ask("List a few movies in which that actored played in", history)
163152 """
164153
165- if messages is None:
166- messages = []
154+ if history is None:
155+ history = []
167156
168- answer = query(self, question, messages, self.model)
169- return (answer, messages)
157+ answer = query(self, question, history, self.model)
158+ return (answer, history)
added rag_sdk/query_graph.py +144 −0
@@ -0,0 +1,144 @@
1+import json
2+from openai import OpenAI
3+
4+# Equipet assistant with tools:
5+tools = [
6+ {
7+ "type": "function",
8+ "function": {
9+ "name": "run_cypher_query",
10+ "description": "Run a Cypher query against the graph",
11+ "parameters": {
12+ "type": "object",
13+ "properties": {
14+ "query": {
15+ "type": "string",
16+ "description": "query to execute",
17+ },
18+ },
19+ "required": ["query"],
20+ },
21+ },
22+ }
23+]
24+
25+client = OpenAI()
26+
27+def run_cypher_query(g, q):
28+ return g.query(q).result_set
29+
30+# convert a schema into a string representation
31+def _graph_schema_to_prompt(s) -> str:
32+ # Build a string description of graph schema
33+ desc = "The knowladge graph schema is as follows:\n"
34+
35+ #--------------------------------------------------------------------------
36+ # Describe labels
37+ #--------------------------------------------------------------------------
38+
39+ # list labels
40+ desc = desc + "The graph contains the following node labels:\n";
41+ for e in s.entities:
42+ desc += e + "\n"
43+
44+ # specify attributes associated with each entity
45+ for e in s.entities:
46+ e = s.entities[e]
47+
48+ lbl_name = e.name
49+ attributes = e.attributes
50+ attr_count = len(attributes)
51+
52+ if (attr_count == 0):
53+ desc += f"The {lbl_name} label has no attributes\n"
54+ else:
55+ desc += f"The {lbl_name} label is associated with the following attribute(s):\n"
56+ for attr in attributes:
57+ attr_name = attr.name
58+ attr_type = attr.type.__name__
59+ desc += f"{attr_name} which is of type {attr_type}\n"
60+
61+ desc += "The graph contains the following relationship types:\n"
62+
63+ #--------------------------------------------------------------------------
64+ # Describe relationships
65+ #--------------------------------------------------------------------------
66+
67+ # list relations
68+ for rel in s.relations:
69+ rel = s.relations[rel]
70+
71+ src = rel.src.name
72+ relationship_type = rel.name
73+ dest = rel.dest.name
74+ desc += f"{relationship_type}\n"
75+ desc += f"The {relationship_type} relationship connects the following labels:\n"
76+ desc += f"{src} is connected via {relationship_type} to {dest}\n"
77+
78+ desc += "This is the end of the knowladge graph schema description.\n"
79+
80+ return desc;
81+
82+def run_conversation(g, question, messages, model) -> str:
83+ # Step 1: send the conversation and available functions to the model
84+ messages.append({"role": "user", "content": question})
85+
86+ response = client.chat.completions.create(
87+ model=model,
88+ messages=messages,
89+ tools=tools,
90+ tool_choice="auto", # auto is default, but we'll be explicit
91+ )
92+
93+ response_message = response.choices[0].message
94+ tool_calls = response_message.tool_calls
95+
96+ # Step 2: check if the model wanted to call a function
97+ if tool_calls:
98+ # Step 3: call the function
99+ # Note: the JSON response may not always be valid; be sure to handle errors
100+ available_functions = {
101+ "run_cypher_query": run_cypher_query,
102+ } # only one function in this example, but you can have multiple
103+ messages.append(response_message) # extend conversation with assistant's reply
104+ # Step 4: send the info for each function call and function response to the model
105+ for tool_call in tool_calls:
106+ function_name = tool_call.function.name
107+ function_to_call = available_functions[function_name]
108+ function_args = json.loads(tool_call.function.arguments)
109+ q = function_args.get("query")
110+ print(f"OpenAI suggested query: {q}")
111+ function_response = function_to_call(g, q)
112+ messages.append(
113+ {
114+ "tool_call_id": tool_call.id,
115+ "role": "tool",
116+ "name": function_name,
117+ "content": str(function_response),
118+ }
119+ ) # extend conversation with function response
120+ second_response = client.chat.completions.create(
121+ model=model,
122+ messages=messages,
123+ ) # get a new response from the model where it can see the function response
124+
125+ return second_response.choices[0].message.content
126+
127+ return None
128+
129+def query(kg, question:str, messages:list, model="gpt-4-1106-preview") -> str:
130+ # Build system message
131+ if len(messages) == 0:
132+ # graph schema
133+ schema_desc = _graph_schema_to_prompt(kg.schema)
134+ messages.append(
135+ {"role": "system", "content": f"""You are a graph database expert fluent in the Cypher query language
136+ with access to the following knowledge graph: {schema_desc}"""})
137+
138+ # Get an answer
139+ answer = run_conversation(kg.graph, question, messages, model)
140+
141+ # Append answer to conversation
142+ messages.append({"role": "assistant", "content": answer})
143+
144+ return answer
modified rag_sdk/template.py +8 −3
@@ -1,8 +1,12 @@
1-import json
1+# template file for entities and relationships extraction using OpenAI assistant
2+# The assistant is equipped with a set of auto generated tools
3+# e.g. Create_Actor, Create_Movie and CAST functions.
4+
5+TEMPLATE = '''import json
26 import time
37 import concurrent.futures
48 from openai import OpenAI
5-from prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
9+from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
610 from falkordb import FalkorDB
711
812 g = None # graph
@@ -121,7 +125,7 @@
121125
122126 def process_source(client, assistant, src):
123127 text = src.load()[:32000]
124- user_message = f"Extracts entities and relations from the following text:\n {text}"
128+ user_message = f"Extracts entities and relations from the following text: {text}"
125129
126130 run = initiate_interaction(client, assistant, user_message)
127131
@@ -146,3 +150,4 @@
146150 concurrent.futures.wait(tasks)
147151
148152 print("Done")
153+'''
modified tests/test_kg.py +3 −3
@@ -1,10 +1,10 @@
11 import unittest
2-from rag_sdk.kg import KG
2+from rag_sdk.kg import KnowledgeGraph
33 from rag_sdk.Schema import Schema
44
55 class TestKG(unittest.TestCase):
66 def test_kg_sources(self):
7- g = KG("UFC")
7+ g = KnowledgeGraph("UFC")
88
99 data_0 = g.add_source("data_0.pdf")
1010 data_1 = g.add_source("data_1.PDF")
@@ -34,7 +34,7 @@
3434 s.add_entity('Movie').add_attribute('title', str, unique=True)
3535 s.add_relation("ACTED", 'Actor', 'Movie')
3636
37- g = KG("IMDB", schema=s)
37+ g = KnowledgeGraph("IMDB", schema=s)
3838 g.add_source("./data/madoff.txt")
3939
4040 g.create()