kikocis/GraphRAG-SDK public
Changesets · Branches · Tags · Compare
| Changeset | db62d1677f39776c63b5f21288247b3bd043f51c35eeae1790bfd5162de4c72e |
|---|---|
| Author | Roi Lipman <roilipman@gmail.com> · 2024-05-28 09:56 +03:00 |
| Committer | Roi Lipman <roilipman@gmail.com> · 2024-05-28 09:56 +03:00 |
| Parents | ffd3815000e1 |
7 files changed
modified rag_sdk/Schema/entity.py +50 −8
| @@ -22,9 +22,19 @@ | ||
| 22 | 22 | def __hash__(self) -> int: |
| 23 | 23 | return hash(self.name) |
| 24 | 24 | |
| 25 | -# Represents an ontolegy entity | |
| 26 | 25 | class Entity(object): |
| 26 | + """ | |
| 27 | + Represents an ontolegy entity | |
| 28 | + """ | |
| 29 | + | |
| 27 | 30 | def __init__(self, name:str): |
| 31 | + """ | |
| 32 | + Initialize Entity | |
| 33 | + | |
| 34 | + Parameters: | |
| 35 | + name (str): name of entity | |
| 36 | + """ | |
| 37 | + | |
| 28 | 38 | if not isinstance(name, str) or name == "": |
| 29 | 39 | raise Exception("Entity name must be a none empty string") |
| 30 | 40 | |
| @@ -37,8 +47,18 @@ | ||
| 37 | 47 | |
| 38 | 48 | return (self.name == other.name and self.attributes == other.attributes) |
| 39 | 49 | |
| 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 | + | |
| 42 | 62 | # Validate arguments |
| 43 | 63 | if not isinstance(name, str) or name == "": |
| 44 | 64 | raise Exception("Attribute name must be a none empty string") |
| @@ -55,8 +75,14 @@ | ||
| 55 | 75 | desc = f"{self.name}'s {name}" if desc is None else desc |
| 56 | 76 | self.attributes.add(Attribute(name, type, desc, unique, mandatory)) |
| 57 | 77 | |
| 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 | + | |
| 60 | 86 | # Validate argument |
| 61 | 87 | if not isinstance(name, str) or name == "": |
| 62 | 88 | raise Exception("Attribute name must be a none empty string") |
| @@ -66,7 +92,17 @@ | ||
| 66 | 92 | self.attributes.remove(attr) |
| 67 | 93 | return |
| 68 | 94 | |
| 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 | + | |
| 70 | 106 | # Validate argument |
| 71 | 107 | if not isinstance(name, str) or name == "": |
| 72 | 108 | raise Exception("Attribute name must be a none empty string") |
| @@ -77,8 +113,14 @@ | ||
| 77 | 113 | |
| 78 | 114 | return None |
| 79 | 115 | |
| 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 | + | |
| 82 | 124 | unique_attrs = [] |
| 83 | 125 | for attr in self.attributes: |
| 84 | 126 | if attr.unique: |
modified rag_sdk/Schema/schema.py +94 −18
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | from falkordb import Graph |
| 2 | +from rag_sdk.source import AbstractSource | |
| 2 | 3 | from .entity import Entity |
| 3 | 4 | from .relation import Relation |
| 4 | 5 | from .encoder import SchemaEncoder |
| @@ -7,11 +8,19 @@ | ||
| 7 | 8 | from .from_graph import schema_from_graph |
| 8 | 9 | from .auto_detect import schema_auto_detect |
| 9 | 10 | |
| 10 | -# Knowledge Graph schema | |
| 11 | -# The schema captures graph entities in addition to their attributes | |
| 12 | -# and the relationship types between the entities | |
| 11 | + | |
| 13 | 12 | 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 | + | |
| 14 | 19 | def __init__(self): |
| 20 | + """ | |
| 21 | + Initialize Schema | |
| 22 | + """ | |
| 23 | + | |
| 15 | 24 | self.entities = {} |
| 16 | 25 | self.relations = {} |
| 17 | 26 | |
| @@ -27,8 +36,18 @@ | ||
| 27 | 36 | |
| 28 | 37 | return True |
| 29 | 38 | |
| 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 | + | |
| 32 | 51 | # Validate arguments |
| 33 | 52 | if not isinstance(name, str) or name == "": |
| 34 | 53 | raise Exception(f"Invalid name argument, expecting none empty string") |
| @@ -39,8 +58,14 @@ | ||
| 39 | 58 | self.entities[name] = e |
| 40 | 59 | return e |
| 41 | 60 | |
| 42 | - # Get an entity from schema | |
| 43 | 61 | def get_entity(self, name:str) -> Entity | None: |
| 62 | + """ | |
| 63 | + Get an entity from schema | |
| 64 | + | |
| 65 | + Returns: | |
| 66 | + entity | |
| 67 | + """ | |
| 68 | + | |
| 44 | 69 | if not isinstance(name, str) or name == "": |
| 45 | 70 | raise Exception("Invalid argument, name should be a none empty string") |
| 46 | 71 | |
| @@ -49,8 +74,14 @@ | ||
| 49 | 74 | else: |
| 50 | 75 | return None |
| 51 | 76 | |
| 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 | + | |
| 54 | 85 | # Validate arguments |
| 55 | 86 | if not isinstance(src, Entity) and not isinstance(src, str): |
| 56 | 87 | raise Exception(f"Invalid argument, src is expected to be either a string or an Entity") |
| @@ -85,9 +116,14 @@ | ||
| 85 | 116 | |
| 86 | 117 | return r |
| 87 | 118 | |
| 88 | - # Validate schema | |
| 89 | - # Make sure schema is valid | |
| 90 | 119 | def validate(self) -> bool: |
| 120 | + """ | |
| 121 | + Validate schema | |
| 122 | + | |
| 123 | + Returns: | |
| 124 | + True if schema is valid | |
| 125 | + """ | |
| 126 | + | |
| 91 | 127 | # Make sure each Relation reference existing Entities |
| 92 | 128 | # And each referenced entity has at least one unique attribute |
| 93 | 129 | for r in self.relations: |
| @@ -109,32 +145,72 @@ | ||
| 109 | 145 | |
| 110 | 146 | return True |
| 111 | 147 | |
| 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 | + | |
| 114 | 156 | schema_to_graph(self, g) |
| 115 | 157 | |
| 116 | - # encode schema to JSON string | |
| 117 | 158 | def to_JSON(self) -> str: |
| 159 | + """ | |
| 160 | + Encode schema to JSON string | |
| 161 | + | |
| 162 | + Returns: | |
| 163 | + JSON representation of schema | |
| 164 | + """ | |
| 165 | + | |
| 118 | 166 | encoder = SchemaEncoder() |
| 119 | 167 | return encoder.to_JSON(self) |
| 120 | 168 | |
| 121 | 169 | @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 | + | |
| 124 | 181 | s = cls() |
| 125 | 182 | schema_from_graph(s, g) |
| 126 | 183 | return s |
| 127 | 184 | |
| 128 | 185 | @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 | + | |
| 131 | 198 | s = cls() |
| 132 | 199 | schema_auto_detect(s, sources, model) |
| 133 | 200 | return s |
| 134 | 201 | |
| 135 | 202 | @classmethod |
| 136 | - # Create a schema from JSON | |
| 137 | 203 | 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 | + | |
| 138 | 214 | s = cls() |
| 139 | 215 | decoder = SchemaDecoder() |
| 140 | 216 | 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 | |
| 2 | 2 | from .source import Source |
modified rag_sdk/kg.py +26 −37
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | from typing_extensions import AbstractSet |
| 5 | 5 | |
| 6 | 6 | from .prompts import * |
| 7 | +from .template import TEMPLATE | |
| 7 | 8 | from openai import OpenAI |
| 8 | 9 | from falkordb import FalkorDB |
| 9 | 10 | from .query_graph import query |
| @@ -12,11 +13,12 @@ | ||
| 12 | 13 | from .Schema.tools_gen import schema_to_tools |
| 13 | 14 | from .Schema.functions_gen import schema_to_functions |
| 14 | 15 | |
| 15 | -class KG(object): | |
| 16 | +class KnowledgeGraph(object): | |
| 16 | 17 | """Knowledge Graph model data as a network of entities and relations |
| 17 | 18 | To create one it is best to provide a schema which will define the graph's ontology |
| 18 | 19 | In addition to a set of sources from which entities and relations will be extracted. |
| 19 | 20 | """ |
| 21 | + | |
| 20 | 22 | def __init__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None, |
| 21 | 23 | model:str="gpt-4-1106-preview", schema:Schema|None=None): |
| 22 | 24 | """ |
| @@ -61,7 +63,7 @@ | ||
| 61 | 63 | |
| 62 | 64 | return s |
| 63 | 65 | |
| 64 | - def remove_source(self, source:str|AbstractSource): | |
| 66 | + def remove_source(self, source:str|AbstractSource) -> None: | |
| 65 | 67 | """ |
| 66 | 68 | Remove source from sources |
| 67 | 69 | |
| @@ -105,37 +107,25 @@ | ||
| 105 | 107 | functions_impl = [func[1] for func in funcs] |
| 106 | 108 | |
| 107 | 109 | # 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()) | |
| 131 | 121 | |
| 132 | 122 | # 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) | |
| 134 | 124 | |
| 135 | 125 | def _createKGWithoutSchema(self): |
| 136 | 126 | pass |
| 137 | 127 | |
| 138 | - def create(self): | |
| 128 | + def create(self) -> None: | |
| 139 | 129 | """ |
| 140 | 130 | Create knowledge graph |
| 141 | 131 | Extract entities and relations from sources |
| @@ -147,23 +137,22 @@ | ||
| 147 | 137 | else: |
| 148 | 138 | self._createKGWithoutSchema() |
| 149 | 139 | |
| 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]: | |
| 152 | 141 | """ |
| 153 | 142 | Query the knowledge graph using natural language |
| 154 | 143 | if the query is asked as part of a longer conversation make sure to |
| 155 | - include past messages. | |
| 144 | + include past history. | |
| 156 | 145 | |
| 157 | 146 | Rreturns: |
| 158 | - tuple[str, list]: answer, conversation messages | |
| 147 | + tuple[str, list]: answer, conversation history | |
| 159 | 148 | |
| 160 | 149 | 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) | |
| 163 | 152 | """ |
| 164 | 153 | |
| 165 | - if messages is None: | |
| 166 | - messages = [] | |
| 154 | + if history is None: | |
| 155 | + history = [] | |
| 167 | 156 | |
| 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 | |
| 2 | 6 | import time |
| 3 | 7 | import concurrent.futures |
| 4 | 8 | from openai import OpenAI |
| 5 | -from prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT | |
| 9 | +from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT | |
| 6 | 10 | from falkordb import FalkorDB |
| 7 | 11 | |
| 8 | 12 | g = None # graph |
| @@ -121,7 +125,7 @@ | ||
| 121 | 125 | |
| 122 | 126 | def process_source(client, assistant, src): |
| 123 | 127 | 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}" | |
| 125 | 129 | |
| 126 | 130 | run = initiate_interaction(client, assistant, user_message) |
| 127 | 131 | |
| @@ -146,3 +150,4 @@ | ||
| 146 | 150 | concurrent.futures.wait(tasks) |
| 147 | 151 | |
| 148 | 152 | print("Done") |
| 153 | +''' |
modified tests/test_kg.py +3 −3
| @@ -1,10 +1,10 @@ | ||
| 1 | 1 | import unittest |
| 2 | -from rag_sdk.kg import KG | |
| 2 | +from rag_sdk.kg import KnowledgeGraph | |
| 3 | 3 | from rag_sdk.Schema import Schema |
| 4 | 4 | |
| 5 | 5 | class TestKG(unittest.TestCase): |
| 6 | 6 | def test_kg_sources(self): |
| 7 | - g = KG("UFC") | |
| 7 | + g = KnowledgeGraph("UFC") | |
| 8 | 8 | |
| 9 | 9 | data_0 = g.add_source("data_0.pdf") |
| 10 | 10 | data_1 = g.add_source("data_1.PDF") |
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | s.add_entity('Movie').add_attribute('title', str, unique=True) |
| 35 | 35 | s.add_relation("ACTED", 'Actor', 'Movie') |
| 36 | 36 | |
| 37 | - g = KG("IMDB", schema=s) | |
| 37 | + g = KnowledgeGraph("IMDB", schema=s) | |
| 38 | 38 | g.add_source("./data/madoff.txt") |
| 39 | 39 | |
| 40 | 40 | g.create() |